capellambse.diagram package

Various diagramming related tools.

This module is used to create diagrams, which can then be exported in various formats (such as SVG).

class capellambse.diagram.Box

Bases: object

A Box.

Some may call it rectangle.

CHILD_MARGIN = 2
JSON_TYPE = 'box'
PORT_OVERHANG = 2
__init__(pos, size, *, label='', floating_labels=None, description=None, uuid=None, parent=None, collapsed=False, minsize=(0, 0), maxsize=(inf, inf), context=None, port=False, features=None, styleclass=None, styleoverrides=None, hidelabel=False, hidden=False)

Create a new box.

Parameters:
  • pos (tuple[int | float, int | float] | Sequence[int | float]) – A Vector2D describing the spatial position.

  • size (tuple[int | float, int | float] | Sequence[int | float]) – A Vector2D describing the box’ size. If one or both of its components are 0, it/they will be calculated based on the Box’ label text and contained children.

  • label (str) – This box’ label text.

  • floating_labels (MutableSequence[Box] | None) – Additional box labels.

  • description (str | None) – Optional label text used only by Representation Links.

  • uuid (str | None) – UUID of the semantic element this box represents.

  • parent (Box | None) – This box’ parent box.

  • collapsed (bool) – Collapse this box and hide all its children. Note that setting this flag does not change the box’ size.

  • minsize (tuple[int | float, int | float] | Sequence[int | float]) – When dynamically calculating Box size, the minimum size it should have. Default: zero.

  • maxsize (tuple[int | float, int | float] | Sequence[int | float]) – When dynamically calculating Box size, the maximum size it can have. Default: infinite.

  • context (Iterable[str] | None) – A list of UUIDs of objects in this box’ context. This includes children and associated edges.

  • port (bool) – Flag this box as a port. Affects how context is added.

  • features (MutableSequence[str] | None) – Certain classes of Box (like Class) have features, which is a list of strings that will be displayed inside the Box, separated from the label by a horizontal line.

  • styleclass (str | None) – The CSS style class to use.

  • styleoverrides (Optional[MutableMapping[str, Union[str, RGB, MutableSequence[str | RGB]]]]) – A dict of CSS properties to override.

  • hidelabel (bool) – Set to True to skip drawing this box’ label.

  • hidden (bool) – Set to True to skip drawing this entire box.

Return type:

None

add_context(uuid)

Add a UUID as context for this box.

The context will bubble to the immediate parent if this box is a port.

Return type:

None

Parameters:

uuid (str)

property bounds: Box

Calculate the bounding box of this Box.

Notes

Labels with a text_transform in its styleoverrides are ignored during bounds calculation.

property center: Vector2D

Return the center point of this Box.

context: set[str]
create_portlabel(labeltext, margin=2)

Add a label to a port box.

The port that this is called for must be snapped to its parent’s left or right side.

Parameters:
  • labeltext (str) – The label text.

  • margin (float | int) – Space between the label text and the port Box.

Return type:

None

property hidden: bool

Return whether to skip this Box during rendering.

maxsize

A property that automatically converts 2-tuples into Vector2D.

minsize

A property that automatically converts 2-tuples into Vector2D.

move(offset, *, children=True)

Move the box by the specified offset.

Parameters:
  • offset (Vector2D) – The offset to move the box by.

  • children (bool) – Recursively move children as well. If False, the positions of children need to be adjusted separately.

Return type:

None

property padding: Vector2D

Return the horizontal and vertical padding of label text.

property parent: Box | None

Return the parent element of this Box.

pos

A property that automatically converts 2-tuples into Vector2D.

property size: Vector2D

Return the size of this Box.

snap_to_parent()

Snap this Box into the constraints set by its parent.

If this Box is a port, ensure it lines up with the parent’s border, keeping an overhang of 2px.

Otherwise, ensures that this Box will not overflow out of the parent’s border, keeping a padding of 2px.

Return type:

None

vector_snap(point, *, source=None, style=RoutingStyle.OBLIQUE)

Snap the point into this Box, coming from source.

Return type:

Vector2D

Parameters:
class capellambse.diagram.Circle

Bases: object

Represents a circle.

JSON_TYPE = 'circle'
__init__(center, radius, *, uuid=None, styleclass=None, styleoverrides=None, hidden=False, context=None)

Construct a Circle.

Parameters:
add_context(uuid)

Add a UUID as context for this circle.

Return type:

None

Parameters:

uuid (str)

property bounds: Box

Calculate the bounding box of this Circle.

center

A property that automatically converts 2-tuples into Vector2D.

collapsed = False
context: set[str]
hidelabel = True
label = None
move(offset, *, children=True)

Move this Circle on the 2-dimensional plane.

Return type:

None

Parameters:
port = False
vector_snap(vector, *, source, style=RoutingStyle.OBLIQUE)

Snap the vector onto this Circle, preferably in direction.

Return type:

Vector2D

Parameters:
class capellambse.diagram.Diagram

Bases: object

A complete diagram, including all elements required by it.

__init__(name='Untitled Diagram', viewport=None, elements=None, *, uuid=None, styleclass=None, params=None)

Construct a new diagram.

Parameters:
  • name (str) – The diagram’s name.

  • viewport (Box | None) – A Box describing this diagram’s viewport.

  • elements (Sequence[Union[Box, Edge, Circle]] | None) – A list containing the diagram’s initial elements.

  • uuid (str | None) – The unique ID of this diagram.

  • styleclass (str | None) – The diagram class.

  • params (dict[str, Any] | None) – Additional parameters.

add_element(element, extend_viewport=True, *, force=False)

Add an element to this diagram.

Parameters:
  • element (Union[Box, Edge, Circle]) – The element to add.

  • extend_viewport (bool) – True to automatically extend the diagram viewport so that the added element is fully visible.

  • force (bool) – Normally an exception will be raised if another element with the same UUID as the new one already exists in the diagram. If this is set to True, the old element will be overwritten instead.

Return type:

None

calculate_viewport()

Recalculate the viewport so that all elements are contained.

Return type:

None

normalize_viewport(offset=0)

Normalize the viewport.

This function moves all elements contained within this diagram so that the top left corner of the viewport is at (0, 0) (or the specified offset, if given).

If a single value is given as offset, it is applied to both X and Y coordinates.

Return type:

None

Parameters:

offset (float | int | tuple[int | float, int | float] | Sequence[int | float])

class capellambse.diagram.DiagramJSONEncoder

Bases: JSONEncoder

JSON encoder that knows how to handle AIRD diagrams.

default(o)

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return super().default(o)
Return type:

object

Parameters:

o (object)

class capellambse.diagram.Edge

Bases: Vec2List

An edge in the diagram.

An Edge consists of a series of points that are traversed in order. Each point is given as Vector2D containing absolute coordinates. At least two points are required.

JSON_TYPE = 'edge'
__init__(points, *, labels=None, uuid=None, source=None, target=None, styleclass=None, styleoverrides=None, hidden=False, context=None)

Construct an Edge.

Parameters:
add_context(uuid)

Add a UUID as context for this edge.

Return type:

None

Parameters:

uuid (str)

property bounds: Box

Calculate the bounding Box of this Edge.

property center: Vector2D

Calculate the point in the middle of this edge.

collapsed = False
context: set[str]
property hidden: bool

Return whether to skip this Edge during rendering.

hidelabel = False
property length: float

Return length of this edge.

move(offset, *, children=True)

Move all points of this edge by the specified offset.

Return type:

None

Parameters:
property points: Vec2List

Return an iterable over this edge’s points.

port = False
vector_snap(vector, *, source, style=RoutingStyle.OBLIQUE)

Snap the vector onto this Edge.

Return type:

Vector2D

Parameters:
class capellambse.diagram.RGB

Bases: NamedTuple

A color.

Each color component (red, green, blue) is an integer in the range of 0..255 (inclusive). The alpha channel is a float between 0.0 and 1.0 (inclusive). If it is 1, then the str() form does not include transparency information.

a: float

Alias for field number 3

b: int

Alias for field number 2

classmethod fromcss(cssstring)

Create an RGB from a CSS color definition.

Examples of recognized color definitions and their equivalent constructor calls:

"rgb(10, 20, 30)" -> RGB(10, 20, 30)
"rgba(50, 60, 70, 0.5)" -> RGB(50, 60, 70, 0.5)
"#FF00FF" -> RGB(255, 0, 255)
"#ff00ff" -> RGB(255, 0, 255)
"#f0f" -> RGB(255, 0, 255)
"#FF00FF80" -> RGB(255, 0, 255, 0.5)
"#f0fa" -> RGB(255, 0, 255, 2/3)
Return type:

RGB

Parameters:

cssstring (str | RGB)

classmethod fromcsv(csvstring)

Create an RGB from a "r, g, b[, a]" string.

Return type:

RGB

Parameters:

csvstring (str)

classmethod fromhex(hexstring)

Create an RGB from a hexadecimal string.

The string can have 3, 4, 6 or 8 hexadecimal characters. In the cases of 3 and 6 characters, the alpha channel is set to 1.0 (fully opaque) and the remaining characters are interpreted as the red, green and blue components.

Return type:

RGB

Parameters:

hexstring (str)

g: int

Alias for field number 1

r: int

Alias for field number 0

tohex()
Return type:

str

class capellambse.diagram.RoutingStyle

Bases: Enum

MANHATTAN = 2
OBLIQUE = 1
TREE = 3
class capellambse.diagram.Vec2List

Bases: MutableSequence[Vector2D]

A list that automatically converts its elements into Vector2D.

__init__(values)
Parameters:

values (Iterable[tuple[int | float, int | float] | Sequence[int | float]])

append(value)

S.append(value) – append value to the end of the sequence

Return type:

None

Parameters:

value (tuple[int | float, int | float] | Sequence[int | float])

copy()

Create a copy of this Vec2List.

Return type:

Vec2List

extend(values)

S.extend(iterable) – extend sequence by appending elements from the iterable

Return type:

None

Parameters:

values (Iterable[tuple[int | float, int | float] | Sequence[int | float]])

insert(index, value)

S.insert(index, value) – insert value before index

Return type:

None

Parameters:
class capellambse.diagram.Vec2Property

Bases: object

A property that automatically converts 2-tuples into Vector2D.

__init__(default=None)
Parameters:

default (tuple[int | float, int | float] | Sequence[int | float] | None)

default: Vector2D | None
name: str | None
class capellambse.diagram.Vector2D

Bases: NamedTuple

A vector in 2-dimensional space.

angleto(other)

Calculate the angle to other.

This method calculates the angle that other was rotated by in order to have the same direction as self, in radians.

Return type:

float

Parameters:

other (tuple[int | float, int | float] | Sequence[int | float])

Notes

The returned angle will always constitute the shortest rotation possible, i.e. it can have values between \(-\pi\) and \(+\pi\).

boxsnap(corner1, corner2)

Snap this vector to the side of a box and return the result.

Parameters:
Return type:

Vector2D

closestaxis()

Determine the axis closest to this Vector2D.

Return type:

Vector2D

property length: float

Calculate the length of this vector.

property normalized: Vector2D

Create a unit Vector2D with the same direction as this one.

Raises:

ZeroDivisionError – if this Vector2D has zero length

rotatedby(theta)

Rotate this Vector2D by theta radians.

Return type:

Vector2D

Parameters:

theta (int | float)

property sqlength: float

Calculate the squared length of this vector.

x: int | float

Alias for field number 0

y: int | float

Alias for field number 1

capellambse.diagram.get_icon(styleclass, /, *, size=16)

Get the icon of the given model element as standalone SVG.

Parameters:
  • styleclass (str) – The object’s style class.

  • size (int) – The desired size of the icon.

Returns:

The SVG data as string.

Return type:

str

Raises:

ValueError – Raised if there is no icon available for this object.

capellambse.diagram.get_style(diagramclass, objectclass)

Fetch the default style for the given drawtype and styleclass.

The style is returned as a dict with key-value pairs as used by CSS inside SVG graphics.

All values contained in this dict are either of type str, or of a class whose str() representation results in a valid CSS value for its respective key – with one exception: color gradients.

Flat colors are represented using the RGB tuple subclass. Gradients are returned as a two-element list of RGBs the first one is the color at the top of the object, the second one at the bottom.

Parameters:
  • diagramclass (str | None) – The style class of the diagram.

  • objectclass (str) –

    A packed str describing the element’s type and style class in the form:

    Type.StyleClass
    

    The type can be: Box, Edge. The style class can be any known style class.

Return type:

dict[str, Any]

capellambse.diagram.get_svg_symbol(styleclass, /)

Get the icon as reusable SVG symbol.

The resulting fragment may be referenced by a <use> element.

Parameters:

styleclass (str) – A string describing the object type.

Return type:

tuple[Symbol, tuple[str, ...]]

Returns:

  • Any – The element that needs to be deployed to the resulting SVG’s <defs> section.

  • tuple[str, …] – Dependencies of this element, which also need to be deployed to the SVG’s <defs>. This function may be called with each of the provided values in turn in order to obtain the actual SVG fragments.

Raises:

ValueError – Raised if there is no icon for the given typename.

capellambse.diagram.has_icon(styleclass, /)

Determine if an icon exists for the given styleclass.

Return type:

bool

Parameters:

styleclass (str)

capellambse.diagram.line_intersect(line1, line2)

Calculate the point where line1 and line2 intersect.

Both lines are straight lines with infinite length that are defined by the given points.

Return type:

Vector2D

Parameters:

Notes

The implementation is based on https://mathworld.wolfram.com/Line-LineIntersection.html.

Submodules

capellambse.diagram.capstyle module

The color palette and default style definitions used by Capella.

capellambse.diagram.capstyle.COLORS: dict[str, RGB] = {'_CAP_Activity_Border_Orange': (91, 64, 64, 1.0), '_CAP_Activity_Orange': (247, 218, 116, 1.0), '_CAP_Activity_Orange_min': (255, 255, 197, 1.0), '_CAP_Actor_Blue': (198, 230, 255, 1.0), '_CAP_Actor_Blue_label': (0, 0, 0, 1.0), '_CAP_Actor_Blue_min': (218, 253, 255, 1.0), '_CAP_Actor_Border_Blue': (74, 74, 151, 1.0), '_CAP_Association_Color': (0, 0, 0, 1.0), '_CAP_ChoicePseudoState_Border_Gray': (0, 0, 0, 1.0), '_CAP_ChoicePseudoState_Color': (168, 168, 168, 1.0), '_CAP_Class_Border_Brown': (123, 105, 79, 1.0), '_CAP_Class_Brown': (232, 224, 210, 1.0), '_CAP_CombinedFragment_Gray': (242, 242, 242, 1.0), '_CAP_Component_Blue': (150, 177, 218, 1.0), '_CAP_Component_Blue_min': (195, 230, 255, 1.0), '_CAP_Component_Border_Blue': (74, 74, 151, 1.0), '_CAP_Component_Label_Blue': (74, 74, 151, 1.0), '_CAP_ConfigurationItem_Gray': (242, 238, 225, 1.0), '_CAP_ConfigurationItem_Gray_min': (249, 248, 245, 1.0), '_CAP_Datatype_Border_Gray': (103, 103, 103, 1.0), '_CAP_Datatype_Gray': (225, 223, 215, 1.0), '_CAP_Datatype_LightBrown': (232, 224, 210, 1.0), '_CAP_Entity_Gray': (221, 221, 200, 1.0), '_CAP_Entity_Gray_border': (69, 69, 69, 1.0), '_CAP_Entity_Gray_label': (0, 0, 0, 1.0), '_CAP_Entity_Gray_min': (249, 248, 245, 1.0), '_CAP_ExchangeItem_Pinkkish': (246, 235, 235, 1.0), '_CAP_FCD': (233, 243, 222, 1.0), '_CAP_FCinFCD_Green': (148, 199, 97, 1.0), '_CAP_InterfaceDataPackage_LightGray': (250, 250, 250, 1.0), '_CAP_Interface_Border_Reddish': (124, 61, 61, 1.0), '_CAP_Interface_Pink': (240, 221, 221, 1.0), '_CAP_Lifeline_Gray': (128, 128, 128, 1.0), '_CAP_MSM_Mode_Gray': (195, 208, 208, 1.0), '_CAP_MSM_Mode_Gray_min': (234, 239, 239, 1.0), '_CAP_MSM_State_Gray': (208, 208, 208, 1.0), '_CAP_MSM_State_Gray_min': (239, 239, 239, 1.0), '_CAP_Mode_Gray': (165, 182, 180, 1.0), '_CAP_Node_Yellow': (255, 252, 183, 1.0), '_CAP_Node_Yellow_Border': (123, 105, 79, 1.0), '_CAP_Node_Yellow_Label': (0, 0, 0, 1.0), '_CAP_Node_Yellow_min': (255, 255, 220, 1.0), '_CAP_OperationalRole_Purple': (203, 174, 200, 1.0), '_CAP_Operational_Process_Reference_Orange': (250, 239, 203, 1.0), '_CAP_PhysicalPort_Yellow': (255, 244, 119, 1.0), '_CAP_StateMode_Border_Gray': (117, 117, 117, 1.0), '_CAP_StateTransition_Color': (0, 0, 0, 1.0), '_CAP_State_Gray': (228, 228, 228, 1.0), '_CAP_Unit_LightBrown': (214, 197, 171, 1.0), '_CAP_Unset_Gray': (205, 205, 205, 1.0), '_CAP_Unset_Gray_min': (234, 234, 234, 1.0), '_CAP_Value_LightBrown': (254, 253, 250, 1.0), '_CAP_xAB_Activity_Label_Orange': (91, 64, 64, 1.0), '_CAP_xAB_Function_Border_Green': (9, 92, 46, 1.0), '_CAP_xAB_Function_Green': (197, 255, 166, 1.0), '_CAP_xAB_Function_Label_Green': (9, 92, 46, 1.0), '_CAP_xBD_ControlNode': (223, 223, 223, 1.0), '_CAP_xDFB_Function_Border_Green': (77, 137, 20, 1.0), '_CAP_xDFB_Function_Green': (197, 255, 166, 1.0), '_CAP_xDFB_Function_Green_Label': (0, 0, 0, 1.0), '_CAP_xDFB_Function_Green_min': (244, 255, 224, 1.0), '_CAP_xDF_Activity_Label_Orange': (0, 0, 0, 1.0), 'black': (0, 0, 0, 1.0), 'dark_gray': (69, 69, 69, 1.0), 'dark_orange': (224, 133, 3, 1.0), 'dark_purple': (114, 73, 110, 1.0), 'gray': (136, 136, 136, 1.0), 'light_purple': (217, 196, 215, 1.0), 'light_yellow': (255, 245, 181, 1.0), 'red': (239, 41, 41, 1.0), 'white': (255, 255, 255, 1.0)}

This dict maps the color names used by Capella to RGB tuples.

capellambse.diagram.capstyle.CSSdef = int | str | capellambse.diagram.capstyle.RGB | list[capellambse.diagram.capstyle.RGB] | None

This dict contains the default styles that Capella applies, grouped by the diagram class they belong to.

The first level of keys are the diagrams’ styleclasses. The special key “__GLOBAL__” applies to all diagrams.

The second level contains the style definitions for each element that can appear in the diagram. The keys work in the following way:

Type.Class

  • Type is the element type; one of “Box” or “Edge” (note casing!)

  • Class is the element’s styleclass, e.g. “LogicalComponent”

The Class and the preceding dot may be absent, in which case that styling applies to all elements of that Type regardless of their style class.

The order of precedence for the four possible cases is the following, from most to least important:

  1. Diagram class specific, element type and class

  2. __GLOBAL__, element type and class

  3. Diagram class specific, only element type

  4. __GLOBAL__, only element type

class capellambse.diagram.capstyle.RGB

Bases: NamedTuple

A color.

Each color component (red, green, blue) is an integer in the range of 0..255 (inclusive). The alpha channel is a float between 0.0 and 1.0 (inclusive). If it is 1, then the str() form does not include transparency information.

a: float

Alias for field number 3

b: int

Alias for field number 2

classmethod fromcss(cssstring)

Create an RGB from a CSS color definition.

Examples of recognized color definitions and their equivalent constructor calls:

"rgb(10, 20, 30)" -> RGB(10, 20, 30)
"rgba(50, 60, 70, 0.5)" -> RGB(50, 60, 70, 0.5)
"#FF00FF" -> RGB(255, 0, 255)
"#ff00ff" -> RGB(255, 0, 255)
"#f0f" -> RGB(255, 0, 255)
"#FF00FF80" -> RGB(255, 0, 255, 0.5)
"#f0fa" -> RGB(255, 0, 255, 2/3)
Return type:

RGB

Parameters:

cssstring (str | RGB)

classmethod fromcsv(csvstring)

Create an RGB from a "r, g, b[, a]" string.

Return type:

RGB

Parameters:

csvstring (str)

classmethod fromhex(hexstring)

Create an RGB from a hexadecimal string.

The string can have 3, 4, 6 or 8 hexadecimal characters. In the cases of 3 and 6 characters, the alpha channel is set to 1.0 (fully opaque) and the remaining characters are interpreted as the red, green and blue components.

Return type:

RGB

Parameters:

hexstring (str)

g: int

Alias for field number 1

r: int

Alias for field number 0

tohex()
Return type:

str

capellambse.diagram.capstyle.get_style(diagramclass, objectclass)

Fetch the default style for the given drawtype and styleclass.

The style is returned as a dict with key-value pairs as used by CSS inside SVG graphics.

All values contained in this dict are either of type str, or of a class whose str() representation results in a valid CSS value for its respective key – with one exception: color gradients.

Flat colors are represented using the RGB tuple subclass. Gradients are returned as a two-element list of RGBs the first one is the color at the top of the object, the second one at the bottom.

Parameters:
  • diagramclass (str | None) – The style class of the diagram.

  • objectclass (str) –

    A packed str describing the element’s type and style class in the form:

    Type.StyleClass
    

    The type can be: Box, Edge. The style class can be any known style class.

Return type:

dict[str, Any]