Skip to content

generic

Functionality for collection of model data from an instance of MelodyModel and conversion of it into _elkjs.ELKInputData.

CONNECTOR_ATTR_NAMES module-attribute ๐Ÿ”—

CONNECTOR_ATTR_NAMES = ('ports', 'inputs', 'outputs')

Attribute of ModelElements for receiving connections.

DIAGRAM_TYPE_TO_CONNECTOR_NAMES module-attribute ๐Ÿ”—

DIAGRAM_TYPE_TO_CONNECTOR_NAMES: dict[DiagramType, tuple[str, ...]] = {OAB: (), OAIB: (), OCB: (), MCB: (), SAB: CONNECTOR_ATTR_NAMES, SDFB: CONNECTOR_ATTR_NAMES, LAB: CONNECTOR_ATTR_NAMES, LDFB: CONNECTOR_ATTR_NAMES, PAB: CONNECTOR_ATTR_NAMES + PHYSICAL_CONNECTOR_ATTR_NAMES, PDFB: CONNECTOR_ATTR_NAMES + PHYSICAL_CONNECTOR_ATTR_NAMES}

Supported diagram types mapping to the attribute name of connectors.

MARKER_PADDING module-attribute ๐Ÿ”—

MARKER_PADDING = PORT_PADDING

Default padding of markers in pixels.

MARKER_SIZE module-attribute ๐Ÿ”—

MARKER_SIZE = 3

Default size of marker-ends in pixels.

PHYSICAL_CONNECTOR_ATTR_NAMES module-attribute ๐Ÿ”—

PHYSICAL_CONNECTOR_ATTR_NAMES = ('physical_ports')

Attribute of PhysicalComponents for receiving connections.

ExchangeData ๐Ÿ”—

Bases: NamedTuple

Exchange data for ELK.

elkdata instance-attribute ๐Ÿ”—

elkdata: ELKInputData

The collected elkdata to add the edges in there.

exchange instance-attribute ๐Ÿ”—

exchange: ModelElement

An exchange from the capellambse model.

filter_iterable instance-attribute ๐Ÿ”—

filter_iterable: Iterable[str]

A string that maps to a filter label adjuster callable in FILTER_LABEL_ADJUSTERS.

is_hierarchical class-attribute instance-attribute ๐Ÿ”—

is_hierarchical: bool = False

True if exchange isn't global, i.e. nested inside a box.

params class-attribute instance-attribute ๐Ÿ”—

params: dict[str, Any] | None = None

Optional dictionary of additional render params.

collect_exchange_endpoints ๐Ÿ”—

collect_exchange_endpoints(ex: ExchangeData | m.ModelElement) -> SourceAndTarget

Safely collect exchange endpoints from ex.

Source code in capellambse_context_diagrams/collectors/generic.py
73
74
75
76
77
78
79
80
81
def collect_exchange_endpoints(
    ex: ExchangeData | m.ModelElement,
) -> SourceAndTarget:
    """Safely collect exchange endpoints from ``ex``."""
    if isinstance(ex, ExchangeData):
        if ex.is_hierarchical:
            return ex.exchange.target, ex.exchange.source
        return ex.exchange.source, ex.exchange.target
    return ex.source, ex.target

collect_label ๐Ÿ”—

collect_label(obj: m.ModelElement) -> str | None

Return the label of a given object.

The label usually comes from the .name attribute. Special handling for interaction.AbstractCapabilityExtend and interaction.AbstractCapabilityInclude`.

Source code in capellambse_context_diagrams/collectors/generic.py
182
183
184
185
186
187
188
189
190
191
192
193
def collect_label(obj: m.ModelElement) -> str | None:
    """Return the label of a given object.

    The label usually comes from the `.name` attribute. Special handling
    for [`interaction.AbstractCapabilityExtend`][capellambse.metamodel.interaction.AbstractCapabilityExtend]
    and [interaction.AbstractCapabilityInclude`][capellambse.metamodel.interaction.AbstractCapabilityInclude].
    """
    if isinstance(obj, interaction.AbstractCapabilityExtend):
        return "ยซ e ยป"
    elif isinstance(obj, interaction.AbstractCapabilityInclude):
        return "ยซ i ยป"
    return "" if obj.name.startswith("(Unnamed") else obj.name

collector ๐Ÿ”—

collector(diagram: context.ContextDiagram, *, width: int | float = makers.EOI_WIDTH, no_symbol: bool = False) -> _elkjs.ELKInputData

Returns ELKInputData with only centerbox in children and config.

Source code in capellambse_context_diagrams/collectors/generic.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def collector(
    diagram: context.ContextDiagram,
    *,
    width: int | float = makers.EOI_WIDTH,
    no_symbol: bool = False,
) -> _elkjs.ELKInputData:
    """Returns ``ELKInputData`` with only centerbox in children and config."""
    data = makers.make_diagram(diagram)
    data.children = [
        makers.make_box(
            diagram.target,
            width=width,
            no_symbol=no_symbol,
            slim_width=diagram._slim_center_box,
        )
    ]
    return data

exchange_data_collector ๐Ÿ”—

exchange_data_collector(data: ExchangeData, endpoint_collector: cabc.Callable[[m.ModelElement], SourceAndTarget] = collect_exchange_endpoints) -> SourceAndTarget

Return source and target port from exchange.

Additionally inflate elkdata.children with input data for ELK. You can handover a filter name that corresponds to capellambse filters. This will apply filter functionality from filters.FILTER_LABEL_ADJUSTERS.

PARAMETER DESCRIPTION
data

Instance of ExchangeData storing all needed elements for collection.

TYPE: ExchangeData

endpoint_collector

Optional collector function for Exchange endpoints. Defaults to collect_exchange_endpoints.

TYPE: Callable[[ModelElement], SourceAndTarget] DEFAULT: collect_exchange_endpoints

RETURNS DESCRIPTION
(source, target)

A tuple consisting of the exchange's source and target elements.

Source code in capellambse_context_diagrams/collectors/generic.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def exchange_data_collector(
    data: ExchangeData,
    endpoint_collector: cabc.Callable[
        [m.ModelElement], SourceAndTarget
    ] = collect_exchange_endpoints,
) -> SourceAndTarget:
    """Return source and target port from `exchange`.

    Additionally inflate `elkdata.children` with input data for ELK.
    You can handover a filter name that corresponds to capellambse
    filters. This will apply filter functionality from
    [`filters.FILTER_LABEL_ADJUSTERS`][capellambse_context_diagrams.filters.FILTER_LABEL_ADJUSTERS].

    Parameters
    ----------
    data
        Instance of [`ExchangeData`][capellambse_context_diagrams.collectors.generic.ExchangeData]
        storing all needed elements for collection.
    endpoint_collector
        Optional collector function for Exchange endpoints. Defaults to
        [`collect_exchange_endpoints`][capellambse_context_diagrams.collectors.generic.collect_exchange_endpoints].

    Returns
    -------
    source, target
        A tuple consisting of the exchange's source and target elements.
    """
    source, target = endpoint_collector(data.exchange)
    if data.is_hierarchical:
        target, source = source, target

    params = (data.params or {}).copy()
    # Remove simple render parameters from params
    no_edgelabels: bool = params.pop("no_edgelabels", False)
    params.pop("transparent_background", False)
    _ = params.pop("font_family", "Open Sans")
    _ = params.pop("font_size", 12)

    render_adj: dict[str, t.Any] = {}
    for name, value in params.items():
        try:
            filters.RENDER_ADJUSTERS[name](value, data.exchange, render_adj)
        except KeyError:
            logger.exception(
                "There is no render parameter solver labelled: '%s' "
                "in filters.RENDER_ADJUSTERS",
                name,
            )

    data.elkdata.edges.append(
        _elkjs.ELKInputEdge(
            id=render_adj.get("id", data.exchange.uuid),
            sources=[render_adj.get("sources", source.uuid)],
            targets=[render_adj.get("targets", target.uuid)],
        )
    )

    label = collect_label(data.exchange)
    for filter in data.filter_iterable:
        try:
            label = filters.FILTER_LABEL_ADJUSTERS[filter](
                data.exchange, label
            )
        except KeyError:
            logger.exception(
                "There is no filter labelled: '%s' in "
                "filters.FILTER_LABEL_ADJUSTERS",
                filter,
            )

    if label and not no_edgelabels:
        data.elkdata.edges[-1].labels = makers.make_label(
            render_adj.get("labels_text", label),
            max_width=makers.MAX_LABEL_WIDTH,
        )

    return source, target

get_all_owners ๐Ÿ”—

get_all_owners(obj: m.ModelElement) -> cabc.Iterator[str]

Return the UUIDs from all owners of obj.

Source code in capellambse_context_diagrams/collectors/generic.py
264
265
266
267
268
269
def get_all_owners(obj: m.ModelElement) -> cabc.Iterator[str]:
    """Return the UUIDs from all owners of ``obj``."""
    current: m.ModelElement | None = obj
    while current is not None:
        yield current.uuid
        current = getattr(current, "owner", None)

move_edges ๐Ÿ”—

move_edges(boxes: cabc.Mapping[str, _elkjs.ELKInputChild], connections: cabc.Iterable[m.ModelElement], data: _elkjs.ELKInputData) -> None

Move edges to boxes.

Source code in capellambse_context_diagrams/collectors/generic.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
def move_edges(
    boxes: cabc.Mapping[str, _elkjs.ELKInputChild],
    connections: cabc.Iterable[m.ModelElement],
    data: _elkjs.ELKInputData,
) -> None:
    """Move edges to boxes."""
    edges_to_remove: list[str] = []
    for c in connections:
        source_owner_uuids = list(get_all_owners(c.source))
        target_owner_uuids = list(get_all_owners(c.target))
        if c.source == c.target:
            source_owner_uuids.remove(c.source.uuid)
            target_owner_uuids.remove(c.source.uuid)

        if c.source.owner is not None and c.target.owner is not None:
            cycle_detected = c.source.owner.uuid == c.target.owner.uuid
        else:
            cycle_detected = False

        common_owner_uuid = None
        for owner in source_owner_uuids:
            if owner in target_owner_uuids:
                common_owner_uuid = owner
                if cycle_detected:
                    cycle_detected = False
                else:
                    break

        if not common_owner_uuid or not (
            owner_box := boxes.get(common_owner_uuid)
        ):
            continue

        for edge in data.edges:
            if edge.id == c.uuid:
                owner_box.edges.append(edge)
                edges_to_remove.append(edge.id)

    data.edges = [e for e in data.edges if e.id not in edges_to_remove]

move_parent_boxes_to_owner ๐Ÿ”—

move_parent_boxes_to_owner(boxes: dict[str, _elkjs.ELKInputChild], obj: m.ModelElement, data: _elkjs.ELKInputData, filter_types: tuple[type, ...] = PackageTypes) -> None

Move boxes to their owner box.

Source code in capellambse_context_diagrams/collectors/generic.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def move_parent_boxes_to_owner(
    boxes: dict[str, _elkjs.ELKInputChild],
    obj: m.ModelElement,
    data: _elkjs.ELKInputData,
    filter_types: tuple[type, ...] = PackageTypes,
) -> None:
    """Move boxes to their owner box."""
    boxes_to_remove: list[str] = []
    for child in data.children:
        if not child.children:
            continue

        owner = obj._model.by_uuid(child.id)
        if (
            isinstance(owner, filter_types)
            or not (oowner := owner.owner)
            or isinstance(oowner, filter_types)
            or not (oowner_box := boxes.get(oowner.uuid))
        ):
            continue

        oowner_box.children.append(child)
        boxes_to_remove.append(child.id)

    data.children = [b for b in data.children if b.id not in boxes_to_remove]