### Install py-capellambse from GitHub for Development Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/installation.md Clone the repository and install py-capellambse with development extras, including Jupyter notebooks and Excel export demos. This method is recommended for contributing to the project or using its full example suite. ```bash git clone https://github.com/dbinfrago/py-capellambse.git cd py-capellambse python3 -m venv .venv source .venv/bin/activate pip install . pip install jupyter cd examples jupyter-notebook ``` -------------------------------- ### Run Example Notebooks Source: https://github.com/dbinfrago/py-capellambse/blob/master/CONTRIBUTING.md Execute this command to verify that example notebooks produce up-to-date output. This is part of the CI process. ```sh make verify-examples ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/developing-docs.md Installs the necessary dependencies required for building the documentation. Run this command before building or serving the docs. ```bash make install ``` -------------------------------- ### Start Jupyter Server Source: https://github.com/dbinfrago/py-capellambse/blob/master/CONTRIBUTING.md Launch a Jupyter server to develop and re-run example notebooks locally. A static seed is provided for the pseudo-random number generator, which is not recommended for production. ```bash make jupyter ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/developing-docs.md Builds the documentation and starts a local development server. The documentation can then be accessed at http://localhost:8000. ```bash make docs-serve ``` -------------------------------- ### Set Up Development Environment Source: https://github.com/dbinfrago/py-capellambse/blob/master/CONTRIBUTING.md Clone the repository, install development dependencies, and set up git hooks. Activate the virtual environment for tool availability. ```bash git clone https://github.com/dbinfrago/py-capellambse cd py-capellambse make dev make install-hooks # You may need to explicitly activate the project venv # to make code completion and tools available: source .venv/bin/activate.sh # for Linux / Mac .venv\Scripts\activate # for Windows ``` -------------------------------- ### Install py-capellambse Source: https://github.com/dbinfrago/py-capellambse/blob/master/README.md Install the latest released version of py-capellambse from PyPI. ```bash pip install capellambse ``` -------------------------------- ### Install Context Diagrams Extension Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/10 Declarative Modeling.ipynb Installs the capellambse_context_diagrams extension. This is an optional step for visualizing modeling results. ```bash !pip install -q capellambse_context_diagrams ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/dbinfrago/py-capellambse/blob/master/CONTRIBUTING.md Set up the pre-commit framework to perform basic code checks before committing changes. Ensure this is installed and configured as per the development instructions. ```bash make install-hooks ``` -------------------------------- ### Apply Declarative Model via CLI Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/declarative.md Use the `capellambse.decl` module from the command line to apply a YAML model to a Capella model. Requires `capellambse[decl,cli]` to be installed. ```sh python -m capellambse.decl --model path/to/model.aird coffee-machine.yml ``` -------------------------------- ### Export Actor Data to Pandas DataFrame in Python Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/01 Introduction.ipynb This example demonstrates how to extract actor names and their allocated functions, then organize this data into a pandas DataFrame for further analysis or display. It requires the pandas library to be installed. ```python import pandas as pd data = [] for actor in model.la.all_actors: actor_functions = ( "; ".join(function.name for function in actor.allocated_functions) or "no functions assigned" ) data.append({"actor": actor.name, "functions": actor_functions}) df = pd.DataFrame(data) df ``` -------------------------------- ### Export Requirements to Excel with Pandas Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/06 Introduction to Requirement access and management.ipynb Use pandas to create a DataFrame from requirements and export it to an Excel file. Requires pandas and xlsxwriter to be installed. ```python import pandas as pd requirements = [ {"id": f"Req_{i}", "uuid": req.uuid, "text": req.text} for i, req in enumerate(model.oa.all_requirements) ] data = pd.DataFrame(requirements) data.to_excel(excel_writer="Test_requirements.xlsx") ``` -------------------------------- ### Load Capella Model and Silence Warnings Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/02 Intro to Physical Architecture API.ipynb Loads a Capella model using the MelodyModel class and sets the logging level to critical to suppress warnings. Ensure pandas is installed for potential table construction and visualization. ```python import logging import pandas as pd import capellambse logging.getLogger().setLevel(logging.CRITICAL) path_to_model = "../../../tests/data/models/test7_0/Model Test 7.0.aird" model = capellambse.MelodyModel(path_to_model) ``` -------------------------------- ### Create Deeply Nested Functions with Outputs Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/declarative.md Create arbitrarily nested functions, including defining their outputs. This example shows a 'brew coffee' function with nested 'grind beans' and 'heat water' functions, each having an output port. ```yaml - parent: !uuid f28ec0f8-f3b3-43a0-8af7-79f194b29a2d extend: functions: - name: brew coffee functions: - name: grind beans outputs: - name: Ground Beans port - name: heat water outputs: - name: Hot Water port ``` -------------------------------- ### Configure Model Badge Github Action Source: https://github.com/dbinfrago/py-capellambse/blob/master/ci-templates/github/README.rst Use this configuration to add the Model Badge action to your Github workflow. This minimal setup generates a badge, pushes it to the repository, and uploads it as a workflow artifact. ```yaml on: [push] jobs: generate-model-badge: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: dbinfrago/py-capellambse/ci-templates/github/model-complexity-badge@master ``` -------------------------------- ### Get Key Model Elements Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/10 Declarative Modeling.ipynb Retrieves references to key elements in the System Analysis (SA) layer, including the root function, root component, and component package. These are needed for subsequent modeling operations. ```python root_function = model.sa.root_function root_component = model.sa.root_component structure = model.sa.component_pkg ``` -------------------------------- ### Recursively Get Software Components Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/02 Intro to Physical Architecture API.ipynb Recursively retrieves all software components ('BEHAVIOR' nature) associated with a given hardware component, flattening the hierarchy. ```python def get_sw_components(sw_component): subcmp = sw_component.related_components.by_nature("BEHAVIOR") for cmp in subcmp: subcmp += get_sw_components(cmp) return subcmp get_sw_components(cmps_with_sw.by_name("Compute Card 1")) ``` -------------------------------- ### Instantiate MelodyModel with Path and Entrypoint Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/specifying-models.md Use the MelodyModel constructor with explicit 'path' and 'entrypoint' arguments. The entrypoint is optional if only one *.aird file exists in the path. ```python model = capellambse.MelodyModel( path="/home/username/models/coffee-machine", entrypoint="coffee-machine.aird", ) ``` -------------------------------- ### Build Documentation Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/developing-docs.md Builds the project documentation. The output will be located in the `docs/build/html` directory. ```bash make docs ``` -------------------------------- ### Launch capellambse REPL Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/repl.md Launches the interactive REPL for exploring Capella models. Replace with the path to your Capella model. ```shell capellambse repl ``` -------------------------------- ### Access Diagram by Name Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/07 Code Generation.ipynb Retrieves a specific diagram from the model by its name. This is often a starting point for interacting with model elements. ```python model.diagrams.by_name("[CDB] CodeGeneration") ``` -------------------------------- ### Inspecting Class Properties Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/03 Data Values.ipynb Access and examine the properties of a retrieved class. This snippet shows how to get the first property of the 'Wand' class. ```python model.la.data_pkg.classes[0].properties[0] ``` -------------------------------- ### Load Capella Model Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/08 Property Values.ipynb Initializes the MelodyModel by providing the path to the .aird file. Ensure the path is correct relative to your project. ```python import capellambse model = capellambse.MelodyModel( "../../../tests/data/models/test7_0/Model Test 7.0.aird" ) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/dbinfrago/py-capellambse/blob/master/CONTRIBUTING.md Execute the project's unit tests. Use 'make test-cov' for coverage reporting. ```bash make test # Alternatively, with coverage reporting enabled make test-cov ``` -------------------------------- ### Filter Requirement Types by Class Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/06 Introduction to Requirement access and management.ipynb Filter the requirement types within a folder by their class, for example, 'RequirementType', and access the first one found. ```python reqtype = model.oa.requirement_types_folders[0].types.by_class( "RequirementType" )[0] reqtype ``` -------------------------------- ### Launch capellambse REPL with development flags Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/repl.md Launches the REPL with development flags enabled for enhanced debugging and warning visibility. This is useful when developing capellambse itself. ```shell python -Xdev -Xfrozen_modules=off -m capellambse repl ``` -------------------------------- ### Initialize Capella Model Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/10 Declarative Modeling.ipynb Initializes an empty Capella 5.2 model. Ensure the model path is correct. ```python import io import capellambse from capellambse import decl model = capellambse.MelodyModel("../../../tests/data/models/empty/empty.aird") ``` -------------------------------- ### Create and Filter Requirements by Type Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/06 Introduction to Requirement access and management.ipynb Create a new requirement and assign it a type, then filter by that type to confirm its inclusion. This demonstrates dynamic requirement management. ```python new_req.type = reqtype model.oa.all_requirements.by_type("ReqType") ``` -------------------------------- ### Describe HW-SW Allocations Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/02 Intro to Physical Architecture API.ipynb Generates a dictionary describing a hardware component and its deployed software components, formatted for a DataFrame. Uses the `get_sw_components` function. ```python def describe_hw_component_sw_allocations(hw_component): return { "hardware_component": hw_component.name, "deployed_sw_components": "; ".join( i.name for i in get_sw_components(hw_component) ), } df = pd.DataFrame( list(map(describe_hw_component_sw_allocations, cmps_with_sw)) ) df ``` -------------------------------- ### Load and Search Capella Model Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/index.md Load a Capella model from a Git repository and search for a specific system function by name. This demonstrates basic model interaction and element retrieval. ```python >>> import capellambse >>> model = capellambse.MelodyModel("git+https://github.com/dbinfrago/coffee-machine.git") >>> model.search("SystemFunction").by_name("make coffee") .available_in_states = [0] .context_diagram = .inputs = [0] [1] .is_leaf = True .kind = .layer = .name = 'make coffee' .outputs = [0] [1] [2] .parent = .pvmt = > .realization_view = .uuid = '8b0d19df-7446-4c3a-98e7-4a739c974059' .visible_on_diagrams = [0] [1] [2] [3] .xtype = 'org.polarsys.capella.core.data.ctx:SystemFunction' ``` -------------------------------- ### Clean Built Documentation Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/developing-docs.md Deletes previously built documentation files. Use this to ensure a clean build. ```bash make docs-clean ``` -------------------------------- ### Load Libraries and Model Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/04 Intro to Jinja templating.ipynb Imports necessary libraries and loads a Capella model for use with Jinja2 templating. Ensure the model path is correct. ```python import jinja2 from IPython.core.display import HTML import capellambse path_to_model = "../../../tests/data/models/test7_0/Model Test 7.0.aird" model = capellambse.MelodyModel(path_to_model) env = jinja2.Environment() ``` -------------------------------- ### Load a Capella Model with py-capella-mbse Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/01 Introduction.ipynb This snippet shows how to import the library and load a Capella model using its file path. Ensure the path to the .aird file is correct. ```python import capellambse path_to_model = "../../../tests/data/models/test7_0/Model Test 7.0.aird" model = capellambse.MelodyModel(path_to_model) model ``` -------------------------------- ### Specify Model by Path Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/specifying-models.md Provide the path to the main *.aird file. The path can be absolute, relative, or just the directory if there's only one *.aird file. ```text /home/username/models/coffee-machine/coffee-machine.aird C:\\Capella\\workspace\\coffee-machine\\coffee-machine.aird ./model/model.aird model.aird ``` ```text /home/username/models/coffee-machine/ C:\\Capella\\workspace\\coffee-machine ./model . ``` -------------------------------- ### Enable Sphinx Extension in conf.py Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/tools/sphinx-extension.md Add 'capellambse.sphinx' to your `extensions` list in Sphinx's `conf.py` file to enable the extension. ```python # conf.py extensions = [ ..., 'capellambse.sphinx', ] ``` -------------------------------- ### Find Meta-model Files Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/how-to-explore-capella-mm.md Use the `find` command to locate ECore, GenModel, and ODesign files within the cloned Capella repository. These files define the meta-model structure and Sirius diagram configurations. ```bash find -name '*.ecore' -o -name '*.genmodel' ``` ```bash find -name '*.odesign' ``` -------------------------------- ### Load Capella Model Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/09 Context Diagrams.ipynb Load a Capella model using capellambse.MelodyModel. Ensure the path to the model's .aird file is correct. ```python from IPython.display import HTML, display # we'll need that later import capellambse path_to_model = "../../../tests/data/models/test7_0/Model Test 7.0.aird" model = capellambse.MelodyModel(path_to_model) ``` -------------------------------- ### Generate and Write Protobuf File Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/07 Code Generation.ipynb Generates the Protobuf definition for a 'Trajectory' class and writes it to a '.proto' file. Assumes 'data_pkg' and 'class_to_proto' are defined. ```python trajectory = data_pkg.classes.by_name("Trajectory") text = class_to_proto(trajectory) filename = f"{trajectory.name}.proto" with open(filename, "w") as file: file.write(text) print(f"# file: {filename} \n{text}\n") ``` -------------------------------- ### Retrieve and Display a PAB Diagram Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/02 Intro to Physical Architecture API.ipynb Retrieves a specific Physical Architecture Blank (PAB) diagram by its name and displays it. Uncomment the diagram variable to render the diagram if needed. ```python diagram = model.pa.diagrams.by_name("[PAB] A sample vehicle arch") diagram ``` -------------------------------- ### Enumerate Known Models CLI Command Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/specifying-models.md Run this bash command to print the location of the user's `known_models` folder, which is used to manage custom models. ```bash python -m capellambse.cli_helpers ``` -------------------------------- ### Load Model Information with loadinfo Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/specifying-models.md Use `loadinfo` to load model metadata. You can modify options like `diagram_cache` before creating the `MelodyModel` instance. ```python def main(): modelinfo = capellambse.loadinfo(sys.argv[1]) # change any options, for example: modelinfo["diagram_cache"] = "/tmp/diagrams" model = MelodyModel(**modelinfo) ``` -------------------------------- ### xpath(query, namespaces=None, roots=None) Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/low-level-api.md Runs an XPath query on all fragments. Unlike iter_* methods, placeholder elements are not followed into their respective fragments. ```APIDOC ## xpath(query, namespaces=None, roots=None) ### Description Runs an XPath query on all fragments. Placeholder elements are not followed into their respective fragments. ### Parameters #### Query Parameters - **query** (str | XPath) - The XPath query. - **namespaces** (dict[str, str] | None) - Namespaces used in the query. Defaults to all known namespaces. - **roots** (_Element | Iterable[_Element] | None) - A list of XML elements to use as roots for the query. Defaults to all tree roots. ### Returns A list of all matching elements. ### Return type list[lxml.etree._Element] ``` -------------------------------- ### Create and Display a New Requirement Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/06 Introduction to Requirement access and management.ipynb Dynamically create a new requirement within a specified module and display it. This also shows how to access all requirements in the layer. ```python new_req = model.oa.requirement_modules[0].requirements.create( name="New showcase req1" ) display(new_req) model.oa.all_requirements ``` -------------------------------- ### Load Capella Model Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/07 Code Generation.ipynb Loads a Capella Melody model from a specified .aird file path. Ensure the path is correct relative to the execution environment. ```python path_to_model = "../../../tests/data/models/test7_0/Model Test 7.0.aird" model = capellambse.MelodyModel(path_to_model) ``` -------------------------------- ### Generate Component Context Diagram Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/09 Context Diagrams.ipynb Generate a context diagram for a specific Capella component. This view shows the component and its immediate environment. ```python cmp = model.la.all_components.by_name("Whomping Willow") cmp.context_diagram ``` -------------------------------- ### Handle Missing Library Resources Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/05 Introduction to Libraries.ipynb Demonstrates how to catch and report a MissingResourceLocationError when loading a Capella model that depends on a library. This helps identify the name of the missing library. ```python import capellambse path_to_model = ( "../../../tests/data/models/library_project/Library Project.aird" ) try: capellambse.MelodyModel(path_to_model) except Exception as err: # noqa: BLE001 print(f"{type(err).__module__}.{type(err).__name__}: {err}") ``` -------------------------------- ### Inspect Property Value Group Applicability Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/08 Property Values.ipynb Use the `help()` function to inspect the `applies_to` method of a property value group to understand its applicability criteria. ```python help(group.applies_to) ``` -------------------------------- ### Display Context Diagrams for Activities in OA Layer Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/09 Context Diagrams.ipynb Iterate through all activities in the Operational Analysis (OA) layer and display their context diagrams. This requires importing HTML and display from IPython.display. ```python for act in model.oa.all_activities: display(HTML(f"

Context of {act.name}

")) display(act.context_diagram) ``` -------------------------------- ### Use Known Models by Name Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/specifying-models.md Define models with short names by placing JSON configuration files in the user's 'known_models' folder. These names can then be used on the CLI instead of full model definitions. ```bash python -m capellambse.cli_helpers ``` ```bash python -m capellambse.repl coffee-machine ``` -------------------------------- ### Visualize Context Diagram Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/10 Declarative Modeling.ipynb Generates and displays the context diagram for the 'Coffee Machine' component after applying declarative updates. This visualization helps verify the changes made to the model. ```python root_component.context_diagram ``` -------------------------------- ### Clone Capella Source Code Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/how-to-explore-capella-mm.md Clone the Capella repository to access its source code, including meta-model definitions. This is the initial step to obtain the necessary files. ```bash mkdir capella-mm && cd capella-mm git clone https://github.com/eclipse/capella.git ``` -------------------------------- ### xpath2(query, namespaces=None, roots=None) Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/low-level-api.md Runs an XPath query and returns the fragments and elements. The tuples contain the fragment where the match was found as the first element, and the LXML element as the second. ```APIDOC ## xpath2(query, namespaces=None, roots=None) ### Description Runs an XPath query and returns the fragments and elements. The tuples have the fragment where the match was found as first element, and the LXML element as second one. ### Parameters #### Query Parameters - **query** (str | XPath) - The XPath query. - **namespaces** (dict[str, str] | None) - Namespaces used in the query. Defaults to all known namespaces. - **roots** (_Element | Iterable[_Element] | None) - A list of XML elements to use as roots for the query. Defaults to all tree roots. ### Returns A list of 2-tuples, containing: 1. The fragment name where the match was found. 2. The matching element. ### Return type list[tuple[pathlib.PurePosixPath, lxml.etree._Element]] ``` -------------------------------- ### MelodyLoader - Tree Traversal Methods Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/low-level-api.md Methods for iterating over ancestors, children, and descendants of an element, with support for fragmented files. ```APIDOC ## class capellambse.loader.core.MelodyLoader ### iterancestors(element, *tags) Iterate over the ancestors of `element`. This method will follow fragment links back to the origin point. * **Parameters:** * **element** ( *\_Element*) – The element to start at. * **tags** (*str*) – Only yield elements that have the given XML tag. * **Return type:** *Iterator*[ *\_Element*] ### iterchildren_xt(element, *xtypes) Iterate over the children of `element`. This method will follow links into different fragment files and yield those elements as if they were direct children. * **Parameters:** * **element** ( *\_Element*) – The parent element under which to search for children. * **xtypes** (*str*) – Only yield elements whose `xsi:type` matches one of those given here. If no types are given, all elements are yielded. * **Return type:** *Iterator*[ *\_Element*] ### iterdescendants(root_elm, *tags) Iterate over all descendants of `root_elm`. This method will follow links into different fragment files and yield those elements as if they were part of the origin subtree. * **Parameters:** * **root_elm** ( *\_Element*) – The root element of the tree * **tags** (*str*) – Only yield elements with a matching XML tag. If none are given, all elements are yielded. * **Return type:** *Iterator*[ *\_Element*] ### iterdescendants_xt(element, *xtypes) Iterate over all descendants of `element` by `xsi:type`. This method will follow links into different fragment files and yield those elements as if they were part of the origin subtree. * **Parameters:** * **element** ( *\_Element*) – The root element of the tree * **xtypes** (*str*) – Only yield elements whose `xsi:type` matches one of those given here. If no types are given, all elements are yielded. * **Return type:** *Iterator*[ *\_Element*] ``` -------------------------------- ### Load Model with Library Resources Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/05 Introduction to Libraries.ipynb Loads a Capella model by providing a dictionary of resource locations, which includes definitions for any dependent libraries. This resolves 'MissingResourceLocationError' issues. ```python model = capellambse.MelodyModel(path_to_model, resources=resources) ``` -------------------------------- ### Load Model Directly with loadcli Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/specifying-models.md Use `loadcli` for a convenient way to load both model information and the model itself from a file or JSON string. ```python def main(): model = capellambse.loadcli(sys.argv[1]) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/11 Complexity Assessment.ipynb Imports the SVG display function from IPython.display and the capellambse library. ```python from IPython.display import SVG import capellambse ``` -------------------------------- ### Run XPath Query and Return Fragments and Elements Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/low-level-api.md Use `xpath2` to execute an XPath query and retrieve both the fragment name and the matching LXML element. Placeholder elements are not followed into their respective fragments. ```python model.xpath2(query, namespaces=None, roots=None) ``` -------------------------------- ### Load Capella model and display complexity badge Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/11 Complexity Assessment.ipynb Loads a Capella model from a specified path and displays its complexity badge as an SVG object. Ensure the model path is correct. ```python path_to_model = "../../../tests/data/models/test7_0/Model Test 7.0.aird" model = capellambse.MelodyModel(path_to_model) SVG(model.description_badge) ``` -------------------------------- ### Render Diagrams in Different Formats Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/01 Introduction.ipynb Render a diagram in SVG, data URI SVG, HTML image tag, or raw PNG format. The output is truncated for brevity. ```python print(repr( diagram.render("svg") )[:100], "...") # The raw SVG format as simple python `str` ``` ```python print(repr( diagram.render("datauri_svg") )[:100], "...") # An SVG, base64-encoded as `data:` URI ``` ```python print(repr( diagram.render("html_img") )[:100], "...") # An HTML `` tag, using the above `data:` URI as `src` ``` ```python print(repr( diagram.render("png") )[:100], "...") # A raw PNG byte stream, which can be written to a `.png` file ``` -------------------------------- ### MelodyLoader.iterall Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/low-level-api.md Iterates over all elements in all trees, optionally restricted by tags. ```APIDOC ## MelodyLoader.iterall(*tags) ### Description Iterate over all elements in all trees by tags. ### Parameters #### Path Parameters * **tags** (*str*) – Optionally restrict the iterator to the given tags. ### Return type *Iterator*[ *_*Element*] ``` -------------------------------- ### Copy Meta-model Dependencies Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/how-to-explore-capella-mm.md Copy relevant meta-model dependency projects from the cloned Capella repository into a new directory. This consolidates the necessary files for opening as a single Eclipse project. ```bash mkdir capella-metamodel cp -r capella/common/plugins/org.polarsys.capella.common.data.activity.gen capella-metamodel cp -r capella/common/plugins/org.polarsys.capella.common.data.behavior.gen capella-metamodel cp -r capella/common/plugins/org.polarsys.capella.common.data.core.gen capella-metamodel cp -r capella/common/plugins/org.polarsys.capella.common.libraries.gen capella-metamodel cp -r capella/common/plugins/org.polarsys.capella.common.re.gen capella-metamodel cp -r capella/core/plugins/org.polarsys.capella.core.data.gen capella-metamodel cp -r capella/releng/cdo/plugins/org.polarsys.kitalpha.emde.model.cdo capella-metamodel cp -r capella/tests/plugins/org.polarsys.capella.test.diagram.layout.ju capella-metamodel ``` -------------------------------- ### capellambse.cli_helpers.loadcli(value) Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/specifying-models.md Loads a Capella model from a specified file path or JSON string. This function is convenient as it loads the model directly. ```APIDOC ## capellambse.cli_helpers.loadcli(value) ### Description Load a model from a file or JSON string. This function works like `loadinfo()`, and also loads the model for convenience. ### Parameters #### Parameters - **value** (str | PathLike) - As described for `loadinfo()`. ### Returns - **MelodyModel** - The loaded model, as described by the *value*. ### Example ```python def main(): model = capellambse.loadcli(sys.argv[1]) ``` ``` -------------------------------- ### Access Data Package in Logical Architecture Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/03 Data Values.ipynb Access the data package within the Logical Architecture. This pattern can be adapted for other architectures by changing the prefix (e.g., `oa` for Operational Architecture). ```python model.la.data_pkg ``` -------------------------------- ### Load Model from Remote URL Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/specifying-models.md Specify models using URLs with supported protocols like file, git, http, https, and zip. These URLs can include parameters for authentication or specific file selection. ```text file:///local/folder git://host.name/repo.git git+https://host.name/repo git@host.name:repo http:// and https:// https://host.name/path/%s?param=arg zip://, zip+https:// etc. zip:///local/file.zip zip+https://host.name/remote/file.zip zip+https://host.name/remote/%s?param=arg!file.zip ``` -------------------------------- ### Render Context Diagrams with Custom Options Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/09 Context Diagrams.ipynb Iterate through all capabilities in the model, access their context diagrams, and render them with symbols displayed as boxes and edge labels disabled. The rendered diagrams are then displayed. ```python for cap in model.oa.all_capabilities: display(HTML(f"

Context of {cap.name}

")) diag = cap.context_diagram diag.display_symbols_as_boxes = True diag.render(None, no_edgelabels=True) display(diag) ``` -------------------------------- ### Specify Model using JSON Configuration Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/specifying-models.md For complex cases, especially with remote models requiring credentials, pass a JSON-encoded dictionary to the MelodyModel constructor or CLI. Ensure the JSON string is properly escaped for shell usage. ```bash python -m capellambse.repl '{"path": "git@example.com:demo-model.git", "revision": "dev", ...}' ``` -------------------------------- ### Render Capella Diagrams to SVG and PNG Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/intro-to-api.md Access a specific Capella diagram by name and render it to SVG or PNG format. Ensure the diagram name is correctly specified. ```python diagram = model.diagrams.by_name("[SDFB] System Context") svg_data = diagram.render("svg") png_data = diagram.render("png") ``` -------------------------------- ### Define Resource Locations for Libraries Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/05 Introduction to Libraries.ipynb Shows three methods for defining resource locations for Capella libraries: a simple string path, a nested dictionary with a 'path' key, and a constructed FileHandler object. These are used to resolve missing library dependencies. ```python # Simple `str` resources = { "Library Test": "/data/models/library_test", } # Nested `dict` resources = { "Library Test": { "path": "https://raw.githubusercontent.com/dbinfrago/py-capellambse/master/tests/data/models/library_test", # More options can be added here if necessary, e.g.: # "username": "demouser", # "password": "super secret passphrase", } } # `FileHandler` object # (Be aware that constructing a `FileHandler` may already involve network access, # for example cloning a remote git repository into a local cache.) lib_handler = capellambse.get_filehandler( "git+https://github.com/dbinfrago/py-capellambse.git", subdir="tests/data/models/library_test", revision="master", # More options can be added here as well, e.g.: # username="demouser", # password="super secret passphrase", ) resources = {"Library Test": lib_handler} ``` -------------------------------- ### Replace Diagram Rendering Properties with render() Method Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/migrating-0.8.md Use the `render()` method instead of deprecated `as_` properties for diagram rendering. The `render()` method supports various formats and its calls are cached. ```python diagram = model.diagrams.by_name("My Diagram") svg_data = diagram.as_svg png_data = diagram.as_png ``` ```python diagram = model.diagrams.by_name("My Diagram") svg_data = diagram.render("svg") png_data = diagram.render("png") ``` ```python diagram = model.diagrams.by_name("My Diagram") raw_svg = diagram.render("svg") datauri = diagram.render("datauri_svg") png = diagram.render("png") ``` -------------------------------- ### capellambse command usage Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/repl.md General usage of the capellambse command-line tool. ```shell capellambse [OPTIONS] COMMAND [ARGS]... ``` -------------------------------- ### create_link Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/low-level-api.md Creates a link from a source element to a target element, returning the link in a string format. ```APIDOC ## create_link(from_element, to_element, include_target_type=None) ### Description Create a link to `to_element` from `from_element`. ### Parameters #### Path Parameters * **from_element** (*_Element*) – The source element of the link. * **to_element** (*_Element*) – The target element of the link. * **include_target_type** (*bool* | *None*) – Whether to include the target type in cross-fragment link definitions. If set to True, it will always be included, False will always exclude it. Setting it to None (the default) will use a simple heuristic: It will be added *unless* the `from_element` is in a visual-only fragment (aird / airdfragment). Regardless of this setting, the target type will never be included if the link does not cross fragment boundaries. ### Returns A link in one of the formats described by `follow_link()`. Which format is used depends on whether `from_element` and `to_element` live in the the same fragment, and whether the `include_target_type` parameter is set. ### Return type str ``` -------------------------------- ### Access Model Diagrams Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/05 Introduction to Libraries.ipynb Retrieves and displays all diagrams within a loaded Capella model. It also shows how to access a specific diagram by its name. ```python model.diagrams ``` ```python model.diagrams.by_name("[LAB] E-Commerce") ``` -------------------------------- ### Import CapellaPy Libraries Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/07 Code Generation.ipynb Imports necessary libraries from the capellambse package for model interaction and metamodel access. ```python import capellambse import capellambse.metamodel as mm ``` -------------------------------- ### Define Model Option with ModelCLI Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/specifying-models.md Use `ModelCLI` as the type for a Click option to directly load a Capella model. This simplifies CLI argument handling for models. ```python @click.command() @click.option("-m", "--model", type=capellambse.ModelCLI()) def main(model: capellambse.MelodyModel) -> None: ... ``` -------------------------------- ### MelodyLoader.iterall_xt Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/low-level-api.md Iterates over all elements in all trees by their xsi:type, with options to filter by specific types or trees. ```APIDOC ## MelodyLoader.iterall_xt(*xtypes, trees=None) ### Description Iterate over all elements in all trees by `xsi:type`s. ### Parameters #### Path Parameters * **xtypes** (*str*) – Optionally restrict the iterator to these `xsi:type`s * **trees** (*Container* [ *PurePosixPath* ] | *None*) – Optionally restrict the iterator to elements that reside in any of the named trees. ### Return type *Iterator*[ *_*Element*] ``` -------------------------------- ### Run XPath Query on All Fragments Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/low-level-api.md Use `xpath` to execute an XPath query across all model fragments. Placeholder elements are not followed into their respective fragments. ```python model.xpath(query, namespaces=None, roots=None) ``` -------------------------------- ### Render Diagram to Different Formats in Python Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/01 Introduction.ipynb Render a diagram to various formats using the `.render(format)` method. This is useful for integrating diagrams into documentation or pipelines, with optional automatic conversion to PNG if dependencies are met. ```python # Example of rendering a diagram (format can be 'svg', 'png', etc.) # diagram.render(format='svg') ``` -------------------------------- ### follow_links Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/low-level-api.md Follows multiple links and returns all results as a list. Broken links can be ignored. ```APIDOC ## follow_links(from_element, links, ignore_broken=False) ### Description Follow multiple links and return all results as list. The format for an individual link is the same as accepted by `follow_link()`. Multiple links are separated by a single space. If any target cannot be found, `None` will be inserted at that point in the returned list. ### Parameters #### Path Parameters * **from_element** (*_Element* | *None*) – The element at the start of the link. This is needed to verify cross-fragment links. * **links** (*str*) – A string containing space-separated links as described in `follow_link()`. * **ignore_broken** (*bool*) – Ignore broken references instead of raising a KeyError. ### Raises * **KeyError** – If any link points to a non-existing target. Can be suppressed with `ignore_broken`. * **ValueError** – If any link is malformed. * **RuntimeError** – If any expected `xsi:type` does not match the actual `xsi:type` of the found target. ### Return type list[ *_*Element*] ``` -------------------------------- ### Apply Declarative Model Programmatically Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/declarative.md Apply a declarative YAML model programmatically using `capellambse.decl.apply()`. The YAML content can be passed as a string via `io.StringIO`. ```python import io, capellambse.decl my_model = capellambse.MelodyModel(...) my_yaml = "..." capellambse.decl.apply(my_model, io.StringIO(my_yaml)) my_model.save() ``` -------------------------------- ### Accessing Requirement Properties Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/06 Introduction to Requirement access and management.ipynb Demonstrates how to access various properties of a requirement object, including its type, text content, and associated diagrams. This is useful for programmatic analysis and manipulation of requirement data. ```python requirement = ... # Assume requirement object is already obtained print(requirement.requirement_type_proxy) print(requirement.requirements) print(requirement.sid) print(requirement.text) print(requirement.type) print(requirement.uuid) print(requirement.visible_on_diagrams) ``` -------------------------------- ### follow_link Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/low-level-api.md Follows a single link from a given element and returns the target element. It supports different link formats, including intra-fragment and cross-fragment references. ```APIDOC ## follow_link(from_element, link) ### Description Follow a single link and return the target element. Valid links have one of the following two formats: - Within the same fragment, a reference is the target’s UUID prepended with a `#`, for example `#7a5b8b30-f596-43d9-b810-45ab02f4a81c`. - A reference to a different fragment contains the target’s `xsi:type` and the path of the fragment, relative to the current one. For example, to link from `main.capella` into `frag/logical.capellafragment`, the reference could be: `org.polarsys.capella.core.data.capellacore:Constraint frag/logical.capellafragment#7a5b8b30-f596-43d9-b810-45ab02f4a81c`. To link back to the project root from there, it could look like: `org.polarsys.capella.core.data.pa:PhysicalArchitecture ../main.capella#26e187b6-72e7-4872-8d8d-70b96243c96c`. ### Parameters #### Path Parameters * **from_element** (*_Element* | *None*) – The element at the start of the link. This is needed to verify cross-fragment links. * **link** (*str*) – A string containing a valid link to another model element. ### Raises * **ValueError** – If the link is malformed * **FileNotFoundError** – If the target fragment is not loaded (only applicable if `from_element` is not None and `fragment` is part of the link) * **RuntimeError** – If the expected `xsi:type` does not match the actual `xsi:type` of the found target * **KeyError** – If the target cannot be found ### Return type *_*Element* ``` -------------------------------- ### Enumerate PVMT Domains Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/08 Property Values.ipynb List all defined domains within the PVMT configuration. Each domain can contain multiple groups. ```python model.pvmt.domains ``` -------------------------------- ### capellambse.cli_helpers.enumerate_known_models() Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/specifying-models.md Enumerates all Capella models found in the configured 'known_models' directories. This helps in discovering and managing available models. ```APIDOC ## capellambse.cli_helpers.enumerate_known_models() ### Description Enumerate the models that are found in the `known_models` folders. Two places are searched for models: The *known_models* folder in the user’s configuration directory, and the *known_models* folder in the installed `capellambse` package. Run the following command to print the location of the user’s *known_models* folder: ```bash python -m capellambse.cli_helpers ``` In order to make a custom model known, place a JSON file in one of these *known_models* folders. It should contain a dictionary with the keyword arguments to `MelodyModel` - specifically it needs a `path`, optionally an `entrypoint`, and any additional arguments that the underlying `FileHandler` might need to gain access to the model. Files in the user’s configuration directory take precedence over files in the package directory. If a file with the same name exists in both places, the one in the user’s configuration directory will be used. Be aware that relative paths in the JSON will be interpreted relative to the current working directory. ### Returns - **Iterator[Traversable]** - An iterator yielding Traversable objects representing the known models. ``` -------------------------------- ### capellambse REPL command usage Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/repl.md Specific usage for the capellambse repl command, including available options and arguments. ```shell capellambse repl [OPTIONS] [MODELINFO] ``` -------------------------------- ### Synchronize Component and Part Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/declarative.md Synchronizes a LogicalComponent and its associated Part, ensuring the component exists and its part is correctly configured. Uses 'find' to locate existing elements and 'promise_id' for referencing. ```yaml - parent: !find _type: "LogicalComponent" name: "System" sync: components: - find: name: "My Component" set: description: This is my new component. promise_id: my-component parts: - find: # Note: `type` (no leading underscore) should be the only `find` argument # if component reuse through parts is disabled, as it is by default. type: !promise my-component set: name: "My Component" ``` -------------------------------- ### Access PVMT Configuration Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/08 Property Values.ipynb Access the PVMT configuration object from the model root. This package is automatically created if it does not exist. ```python model.pvmt ``` -------------------------------- ### Create ElementList from LXML Elements Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/development/low-level-api.md Construct a high-level ElementList from a list of low-level lxml._Element instances. This is useful for handling collections of related model elements. ```python >>> mycomp = model.search("LogicalComponent")[0] >>> children = mycomp._element.getchildren() >>> len(children) 7 >>> mylist = ElementList(model, children) >>> mylist [0] [1] [2] [3] [4] [5] [6] ``` -------------------------------- ### Define ModelInfo Option with ModelInfoCLI Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/specifying-models.md Use `ModelInfoCLI` as the type for a Click option to load model information. This allows modification of options like `diagram_cache` before model instantiation. ```python @click.command() @click.open("-m", "modelinfo", type=capellambse.ModelInfoCLI()) def main(modelinfo: dict[str, t.Any]) -> None: # change any options, for example: modelinfo["diagram_cache"] = "/tmp/diagrams" model = capellambse.MelodyModel(**modelinfo) ``` -------------------------------- ### Generate Functional Context Diagram Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/09 Context Diagrams.ipynb Generate a context diagram for a Capella function. This view illustrates dependencies and required inputs for a function. ```python fnc = model.la.all_functions.by_name("educate Wizards") fnc.context_diagram ``` -------------------------------- ### Synchronize Subfunction and Promise Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/start/declarative.md Ensures a root LogicalFunction contains a subfunction named 'brew coffee', creating it if it doesn't exist. It also sets a promise_id for referencing this function. ```yaml - parent: !uuid f28ec0f8-f3b3-43a0-8af7-79f194b29a2d # the root function sync: functions: - find: name: brew coffee set: description: This function brews coffee. promise_id: brew-coffee - parent: !uuid 0d2edb8f-fa34-4e73-89ec-fb9a63001440 # the root component extend: allocated_functions: - !promise brew-coffee ``` -------------------------------- ### Read Diagram File Content Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/01 Introduction.ipynb Read and print the first 10 lines of a saved diagram file. This is useful for verifying file content after saving. ```python with open("[LAB] Wizard Education.svg") as f: print(*f.readlines()[:10], "...", sep="") ``` -------------------------------- ### List Parts on a Diagram Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/02 Intro to Physical Architecture API.ipynb Retrieves all 'Part' elements visible on a given diagram and maps them to their types. This is useful for identifying components displayed in a specific view. ```python components_on_diagram = diagram.nodes.by_class("Part").map("type") components_on_diagram ``` -------------------------------- ### Generate Component Exchange Context Diagram Source: https://github.com/dbinfrago/py-capellambse/blob/master/docs/source/examples/09 Context Diagrams.ipynb Generate a context diagram for a specific Component Exchange. This provides an overview of functional interactions between components. ```python cmp.related_exchanges.by_name("Punishment").context_diagram ```