API Reference

The previous section showed examples of what can be achieved using SysIDE Automator. This section describes the Python API provided by SysIDE Automator that enables building such and more complicated workflows.

A typical workflow using SysIDE Automator will consist of some subset of the following steps, each of which is described in more detail in the following sections:

  1. Loading a model from KerML and SysML v2 textual notation files and converting them into abstract syntax.

  2. Querying the abstract syntax of the model.

  3. Modifying the abstract syntax of the model.

  4. Exporting the abstract syntax into textual notation or JSON format.

Loading a Model

In SysIDE, a model is represented using Model class. It can be loaded using try_load_model or load_model functions, which take a list of KerML and SysML v2 files as input and return a Model instance. The files can be collected by using collect_files_recursively function, which is a convenience function that collects all files in a directory recursively. The key difference between load_model and try_load_model is that the former raises a ModelError exception if the model contains errors while the latter produces some model even for files with errors. Both functions return a diagnostics object containing the errors, warnings, and informational messages found when loading the model.

Table: Main Functions and Objects

The following table lists the functions and objects related to loading SysML models:

try_load_model

Load a SysMLv2 model.

load_model

Load a SysMLv2 model.

collect_files_recursively

Recursively collect all .sysml and .kerml files in the specified directory.

Model

A SysMLv2 model represented using abstract syntax.

Table: Diagnostics

Loading a model can result in errors, warnings, and informational messages, which are reported using diagnostics. The following table lists the diagnostic-related objects:

ModelError

An exception thrown when model contains errors.

Diagnostics

All model diagnostics.

Diagnostic

DiagnosticMessage

A diagnostic providing information about a model.

DiagnosticSeverity

DiagnosticRelatedInformation

DocumentSegment

CodeDescription

Table: (Advanced) Pipeline Construction

If load_model is not flexible enough for your use case, the following table lists the lower level primitives that can be used to build a custom model loading pipeline:

get_default_executor

Get a default initialized Executor for running schedules. Default executor will use half the logical cores that are available on the current machine. An executor is just a thread pool so there is no reason for constructing and destroying one all the time.

Environment

Standard library environment for use with user models.

Executor

ExecutionResult

IOSchedule

Schedule

ScheduleError

ScheduleOptions

ValidationTiming

DiagnosticResults

Pipeline

PipelineOptions

DocumentTimes

DocumentKind

Is this a model-created document?

StageTimes

build_model

Build the AST for document from its text_document. Any existing model will be cleared, and the built model will not have its references linked. Instead, most references will use placeholder references that will be replaced by actual targets in linking stage. Only sysml and kerml languages are supported.

collect_exports

Collect and cache symbols exported by document. This must be called before the document is indexed, otherwise wrong or no symbols may be indexed. Returns the number of symbols cached.

make_pipeline

sema_reset

Reset semantic state of element. This will typically remove any implied relationships, and reverse a few other changes made by sema. After this completes, element.sema_state == SemaState.None.

Sema

Semantic resolver for SysML. This is responsible for linking references and resolving semantic rules in the pipeline.

StaticIndex

Stdlib

Cache of standard library elements used by sema.

SemaState

Semantic resolution state of Elements. Sema will use this information to discard duplicate work, e.g. when resolving elements in a group of related documents.

ModelLanguage

ImplicitSpecializationKind

UnexpectedDifferentReference

Querying the Abstract Syntax

When SysIDE loads a SysML model from textual notation, it converts it into abstract syntax as defined in the specification. SysML v2 abstract syntax is based on object-oriented principles and, therefore, can be modeled using Python classes. Page Metamodel (Abstract Syntax) shows a list of all element kinds defined in KerML and SysML v2 specifications and to which Python classes they are mapped. The Python classes were created based on the specification by following these principles:

  • The SysIDE Automator API uses Python convention for class and attribute names instead of the Java convention used in the specification. For example, attribute assertedConstraint on AssertConstraintUsage is mapped to asserted_constraint.

  • According to the specification, a SysML v2 model is a set of root namespaces, which are namespaces that have no owner. Since root namespaces do not have names, there is no direct way of selecting a specific namespace. For this reason, SysIDE design exploits the KerML clause 10 that defines that each root namespace corresponds to a single file and shows a model as a collection of documents. The documents are divided into two groups: documents that are part of the standard library documents and documents that are not. The former can be accessed through field stdlib_docs and the latter through field user_docs.

  • Since try_load_model can produce a model even if the model contains errors, most attributes are defined as potentially returning None even if according to the specification they are required.

  • All Python classes modeling abstract syntax are subclasses of AstNode, which provides several methods and fields that are often useful for querying the abstract syntax:

    • cast and try_cast methods for casting the node to a specific type (discussed below).

    • document attribute for accessing the document the node belongs to.

    • parent attribute for accessing the parent node.

    • isinstance method for checking if the node is an instance of a specific type.

    • owned_elements attribute for accessing the owned elements of the node.

    • cst_node attribute for accessing the concrete syntax node corresponding to the abstract syntax node.

  • The specification uses multiple inheritance extensively, modelling which in Python is challenging. For this reason, a class corresponding to a SysML element (for example, AssertConstraintUsage) that according to the specification specializes two other elements (ConstraintUsage and Invariant) will show only one class as a base class (in this case, ConstraintUsage).

    When using static type checkers such as mypy and Pyright, the behavior of the specification can be emulated by casting elements to standard conforming unions which are declared as STD class variables on every element, e.g. Connector.STD. Also be aware that mypy uses joins to infer generic types, reducing them to the most-derived common base type, while pyright correctly infers the generic union types.

    Example of casting an element to a standard conforming type:

    element: syside.Element
    connector = element.cast(syside.Connector.STD)
    typing.reveal_type(connector)  # pyright: syside.Connector | syside.ConnectorAsUsage
    

    For type hints, a similar Std type alias can be used, however it is only defined during type checking so cannot be used at runtime. This distinction is required due to limitations of the Python type system which does not allow type aliases and variables to be bound to the same name. Example of using standard type aliases:

    def example(element: syside.Element) -> syside.Connector.Std:
        return element.cast(syside.Connector.STD)
    

Table: Main Helper Classes for Querying

The following classes are likely to be needed when working with querying models written in textual notation:

  • AstNode is a base class for all classes representing abstract syntax.

  • CstNode is a class providing information about the text from which the node was parsed. An instance of this class can be obtained using cst_node attribute of AstNode class.

  • Document is a class representing a document in the model. A document of an abstract syntax node can be obtained using document attribute of AstNode class. An element representing the root namespace can be obtained by using root_node attribute. Document class also provides two methods for obtaining all elements of specific kind present in the document: all_elements and all_nodes. The former returns all elements of a given kind excluding subtypes, while the latter returns all elements of a given kind including subtypes. This functionality is also exposed on Model class as method all_elements.

  • Url is a class representing an URL of a document, which typically corresponds to a file path. An URL of a document can be obtained using url attribute of Document class.

  • Heritage is a class containing type specializations and conjugations of a type. It can be obtained using heritage attribute of Type class.

Table: Abstract Syntax

The table with all classes modelling the abstract syntax can be found on page Metamodel (Abstract Syntax).

Table: Containers

The following table shows container classes that are used in Python classes modelling the abstract syntax:

ContainerView

An immutable view into a native random-access container. Implements Sequence protocol.

ChildrenNodesView

A view to a container of children nodes.

ChildrenNodes

Container that stores a vector of children nodes.

OwnedChildrenNodes

Container that stores a vector of potentially owned children nodes.

ChainedChildrenNodes

Container that stores a vector of children nodes that may own feature chainings.

LazyIterator

VisitAction

SharedMutex

WriteLocked

Stream

QualifiedName

A sequence of qualified name segments that stringifies with unrestricted names as needed. Unlike string, this allows querying segments in a qualified name without having to parse it again, and is cheaper to construct as string conversion is performed only when needed.

TypeGuard

The type used in a type check expression, e.g. istype, hastype. The actual expression result type is ScalarValues::Boolean.

Table: Compiler

The following table shows the classes related to the compiler:

Table: Urls

Internally, documents are referenced by their Urls. We provide Url bindings as well.

Url

URL as described using the Uniform Resource Identifier (URI) specification (RFC3986).

make_file_url

Construct a Url for a filesystem path with file:// scheme. This correctly handles Windows and Posix paths, and percent escapes Unicode characters.

decode_path

Decode a filesystem path from a Url. This correctly handles Windows and Posix paths using file:// scheme and returns other Urls as is.

EncodingOpts

Percent-encoding options

HostType

IPv4Address

IPv6Address

Scheme

Table: (Advanced) Documents

The following table shows additional classes related to documents, which may be needed for advanced use cases:

Table: (Advanced) Text Documents

Modifying the Abstract Syntax

For convenient modification of the abstract syntax, SysIDE provides a set of additional properties and methods on the abstract syntax classes. Most commonly used ones are:

  • children is a property defined on class Namespace that represents and allows modifying elements in the body of the element (in textual notation, between brackets { and }) and expression arguments.

  • prefixes is a property defined on class Namespace that represents a group for metadata prefixes, prefixed with # in textual notation.

  • type_relationships is a property defined on class Type that represents non-specialization type relationships appearing after specialization part, including feature chaining.

  • declared_ends and declared_messages are end features and messages before the children block. In the textual syntax they appear in the same position, hence in contrast to similar groups there are additional try_append and try_insert methods that return None without throwing if modification failed because the slot is already occupied by block.

  • Accessors are used to provide mutable access to specific attributes of an element. For example, attribute receiver_member on AcceptActionUsage is an accessor of type ParameterAccessor that allows modifying the receiver. The receivers can be seen in the list of SysIDE specific attributes on the page of the corresponding element. They are typically indicated by _member or _target suffixes.

When modifying the abstract syntax, the following constraints must be observed:

  • An element can have only a single owner. Violating this constraint raises ValueError exception. However, the same element can be referenced by multiple elements.

  • Moving an element from one document to another is not supported and will raise ValueError exception.

  • Stealing ownership of an element is not allowed because the desired semantics are unclear. Remove the element from the model first before re-parenting it.

  • Adding a new owned or referenced element must satisfy the typing constraints and will raise TypeError exception if violated.

  • An element can be added only to an element that is not removed from the model. If this constraint is violated, a RuntimeError exception is raised. The problem can be fixed by adding the parent element back to the document as an owned element.

Table: Helper Classes

The following table shows the helper classes for modifying the abstract syntax:

Table: Member Accessors

The following table gives the list of accessor classes:

Table: Reference Accessors

Table: Containers Accessors

Annotations

ConnectorEndsAccessor

ConnectorAsUsageEnds

ConnectorEnds

DependencyEnds

DependencyPrefixes

Heritage

Messages

NamespaceBody

NamespacePrefixes

RelationshipBody

Container for relationship bodies. Works similarly to ChildrenNodes except relationships are not needed and all elements are taken ownership off.

TypeRelationships

Exporting to Textual Notation or JSON

SysIDE provides two ways of exporting the modified abstract syntax:

  • pprint function for pretty printing the abstract syntax in textual notation.

  • json.dumps function for serializing the abstract syntax into JSON format.

Table: Pretty Printing SysML and KerML

The following table shows the classes and functions related to pretty printing SysML and KerML in textual notation:

Table: JSON Serialization

SerializationError

Error serializing element to SysML v2 JSON.

DeserializationError

Error serializing element to SysML v2 JSON.

SerdeWarning

Class for warnings from serialization and deserialization

dumps

Serialize element to a SysML v2 JSON str.

loads

loads implementation

Table: (Advanced) Formatting

Table: (Advanced) Serialization Low Level

The following table shows the classes and functions related to serialization:

serialize

Convenience function for serialization. Prefer using Serializer to avoid allocations when doing repeated serializations.

deserialize

Convenience function for deserialization. Prefer using Deserializer to avoid allocations when doing repeated deserializations.

Writer

Abstract base class for serialization writer implementations.

Serializer

Serializer for SysML models. The actual serialization output depends on used Writer.

Reader

Abstract base class for all deserialization readers.

Deserializer

Deserializer for SysML models. The actual deserialization input depends on used Reader.

FailAction

Action taken when a serialization error is encountered.

SerdeMessage

Message emitted during (de)serialization

SerializationOptions

Options for SysML model serialization. Attribute options are ordered in descending precedence.

SerdeReport

(De)Serialization report containing emitted messages.

DeserializedModel

The model as it was deserialized, with references potentially unresolved.

PendingReference

Reference that has yet to be linked.

IdMap

DeserializedModel compatible mapping for elements. This will typically be used for linking pending references:

Table: (Advanced) JSON Low Level

The following table shows the classes and functions related to JSON serialization:

JsonStringWriter

Serialization writer that outputs JSON string

JsonReader

Unbound reader for JSON deserialization

JsonStringOptions

Options for serialization writer to JSON strings

AttributeMap

Internal opaque type for deserialization attribute mapping

DESERIALIZE_INTERNAL

DESERIALIZE_STANDARD