Module scenariogeneration.xosc.utils

scenariogeneration https://github.com/pyoscx/scenariogeneration

This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.

Copyright (c) 2022 The scenariogeneration Authors.

Expand source code
"""
  scenariogeneration
  https://github.com/pyoscx/scenariogeneration

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at https://mozilla.org/MPL/2.0/.

  Copyright (c) 2022 The scenariogeneration Authors.

"""

import os


from .exceptions import OpenSCENARIOVersionError, NotAValidElement
import xml.etree.ElementTree as ET
from ..helpers import printToFile

from .enumerations import (
    ParameterType,
    PedestrianGestureType,
    PedestrianMotionType,
    Rule,
    ReferenceContext,
    DynamicsShapes,
    DynamicsDimension,
    _MINOR_VERSION,
    XSI,
    XMLNS,
    VehicleCategory,
    PrecipitationType,
    CloudState,
    VehicleComponentType,
    VersionBase,
    SpeedTargetValueType,
    LightMode,
    ColorType,
    ControllerType,
    FractionalCloudCover,
    Wetness,
    Role,
    FollowingMode,
    _OscEnum,
)
import datetime as dt


class _StochasticDistributionType(VersionBase):
    """helper class for typesetting"""

    pass


class _PositionType(VersionBase):
    """helper class for typesetting"""

    pass

    def get_element(self, param):
        pass


class _TriggerType(VersionBase):
    """helper class for typesetting"""

    pass


class _ValueTriggerType(VersionBase):
    """helper class for typesetting"""

    pass


class _EntityTriggerType(VersionBase):
    """helper class for typesetting"""

    pass


class _AnimationType(VersionBase):
    """helper class for typesetting animations"""

    pass


class _AnimationTypeFactory:
    @staticmethod
    def parse_animationtype(element):
        print(element)
        if element.find("ComponentAnimation") is not None:
            return _ComponentAnimation.parse(element.find("ComponentAnimation"))
        elif element.find("PedestrianAnimation") is not None:
            return PedestrianAnimation.parse(element.find("PedestrianAnimation"))
        elif element.find("AnimationFile") is not None:
            return AnimationFile.parse(element.find("AnimationFile"))
        elif element.find("UserDefinedAnimation") is not None:
            return UserDefinedAnimation.parse(element.find("UserDefinedAnimation"))
        else:
            raise NotAValidElement(
                "element ", element, " is not a valid animation type"
            )


class ParameterDeclarations(VersionBase):
    """The ParameterDeclarations class creates the ParameterDeclaration of OpenScenario

    Attributes
    ----------
        parameters: list of Parameter objects

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

        add_parameter(Parameter)
            adds a Parameter to the ParameterDeclarations

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

    """

    def __init__(self):
        """initalizes the ParameterDeclarations"""
        self.parameters = []

    @staticmethod
    def parse(element):
        """Parses the xml element of ParameterDeclarations

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A parameterdeclarations element (same as generated by the class itself)

        Returns
        -------
            parameterdeclaration (ParameterDeclaration): a ParameterDeclarationn object

        """
        parameter_declarations = ParameterDeclarations()
        declarations = element.findall("ParameterDeclaration")
        for declaration in declarations:
            parameter_declaration = Parameter.parse(declaration)
            parameter_declarations.add_parameter(parameter_declaration)
        return parameter_declarations

    def __eq__(self, other):
        if isinstance(other, ParameterDeclarations):
            if self.parameters == other.parameters:
                return True
        return False

    def add_parameter(self, parameter):
        """add_parameter adds a Parameter to the ParameterDeclarations

        Parameters
        ----------
            parameter (Parameter): a new parameter


        """
        if not isinstance(parameter, Parameter):
            raise TypeError("parameter input is not of type Parameter")
        self.parameters.append(parameter)
        return self

    def get_element(self):
        """returns the elementTree of the ParameterDeclarations"""
        if self.parameters:
            element = ET.Element("ParameterDeclarations")
            for p in self.parameters:
                element.append(p.get_element())
            return element


class VariableDeclarations(VersionBase):
    """The VariableDeclarations class creates the VariableDeclarations of OpenScenario
    (Valid from V1.2)
    Attributes
    ----------
        variables: list of Variable objects

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

        add_variable(Variable)
            adds a Variable to the VariableDeclarations

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

    """

    def __init__(self):
        """initalizes the VariableDeclarations"""
        self.variables = []

    @staticmethod
    def parse(element):
        """Parses the xml element of VariableDeclarations

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A VariableDeclarations element (same as generated by the class itself)

        Returns
        -------
            VariableDeclarations (VariableDeclarations): a VariableDeclarations object

        """
        variable_declarations = VariableDeclarations()
        declarations = element.findall("VariableDeclaration")
        for declaration in declarations:
            variable = Variable.parse(declaration)
            variable_declarations.add_variable(variable)
        return variable_declarations

    def __eq__(self, other):
        if isinstance(other, VariableDeclarations):
            if self.variables == other.variables:
                return True
        return False

    def add_variable(self, variable):
        """add_variable adds a Variable to the VariableDeclarations

        Parameters
        ----------
            variable (Variable): a new variable


        """
        if not isinstance(variable, Variable):
            raise TypeError("variable input is not of type Variable")
        self.variables.append(variable)
        return self

    def get_element(self):
        """returns the elementTree of the VariableDeclarations"""
        if self.version_minor < 2:
            OpenSCENARIOVersionError("Variables were introduced in OSC 1.2")
        element = ET.Element("VariableDeclarations")
        for p in self.variables:
            element.append(p.get_element())
        return element


class EntityRef(VersionBase):
    """EntityRef creates an EntityRef element of openscenario

    Parameters
    ----------
        entity (str): name of the entity

    Attributes
    ----------
        entity (str): name of the entity

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, entity):
        """initalize the EntityRef

        Parameters
        ----------
            entity (str): name of the entity

        """
        self.entity = entity

    @staticmethod
    def parse(element):
        """Parses the xml element of EntityRef

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A entityref element (same as generated by the class itself)

        Returns
        -------
            entityref (EntityRef): a EntityRef object

        """
        entity = element.attrib["entityRef"]
        return EntityRef(entity)

    def __eq__(self, other):
        if isinstance(other, EntityRef):
            if self.entity == other.entity:
                return True
        return False

    def get_attributes(self):
        """returns the attributes of the EntityRef as a dict"""
        return {"entityRef": self.entity}

    def get_element(self):
        """returns the elementTree of the EntityRef"""
        return ET.Element("EntityRef", attrib=self.get_attributes())


class Parameter(VersionBase):
    """Parameter is a declaration of a ParameterDeclaration for declarations

    Parameters
    ----------
        name (str): name of parameter

        parameter_type (ParameterType): type of the parameter

        value (str): value of the parameter

    Attributes
    ----------
        name (str): name of parameter

        parameter_type (ParameterType): type of the parameter

        value (str): value of the parameter

        constraint_group (ValueConstraintGroup) constraint groups to the parameter value

    Methods
    -------
        add_parameter ???

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        add_value_constraint_group(constraint_group)
            adds a value constraint group to the Parameter

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, name, parameter_type, value):
        """initalize the Parameter

        Parameters
        ----------
            name (str): name of parameter

            parameter_type (ParameterType): type of the parameter

            value (str): value of the parameter

        """
        self.name = name
        self.parameter_type = convert_enum(parameter_type, ParameterType, False)
        if isinstance(value, bool):
            value = get_bool_string(value)
        self.value = value
        self.constraint_groups = []

    def __eq__(self, other):
        if isinstance(other, Parameter):
            if (
                self.get_attributes() == other.get_attributes()
                and self.constraint_groups == other.constraint_groups
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Parameter

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A parameter element (same as generated by the class itself)

        Returns
        -------
            parameter (Parameter): Parameter object

        """
        name = element.attrib["name"]
        value = element.attrib["value"]
        parameter_type = convert_enum(
            element.attrib["parameterType"], ParameterType, False
        )
        parameter = Parameter(name, parameter_type, value)
        constraint_groups = element.findall("ConstraintGroup")
        for constraint_group in constraint_groups:
            parameter.add_value_constraint_group(
                ValueConstraintGroup.parse(constraint_group)
            )
        return parameter

    def add_value_constraint_group(self, constraint_group):
        """adds a value constraint to the value constraint group

        Parameters
        ----------
            constraint_group (ValueConstraintGroup): the value constraint group to be added

        """
        if not isinstance(constraint_group, ValueConstraintGroup):
            raise TypeError(
                "value_conatraint input is not of type ValueConstraintGroup"
            )
        self.constraint_groups.append(constraint_group)
        return self

    def get_attributes(self):
        """returns the attributes of the Parameter as a dict"""
        return {
            "name": self.name,
            "parameterType": self.parameter_type.get_name(),
            "value": str(self.value),
        }

    def get_element(self):
        """returns the elementTree of the Parameter"""
        element = ET.Element("ParameterDeclaration", attrib=self.get_attributes())
        if self.constraint_groups:
            for constraint_group in self.constraint_groups:
                element.append(constraint_group.get_element())
        return element


class Variable(VersionBase):
    """Variable is a declaration of an entry in VariableDeclaration
    (valid from V1.2)
    Parameters
    ----------
        name (str): name of variable

        variable_type (ParameterType): type of the variable

        value (str): value of the variable

    Attributes
    ----------
        name (str): name of variable

        variable_type (ParameterType): type of the variable

        value (str): value of the variable

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, name, variable_type, value):
        """initalize the Variable

        Parameters
        ----------
            name (str): name of variable

            variable_type (ParameterType): type of the variable

            value (str): value of the variable

        """
        self.name = name
        self.variable_type = convert_enum(variable_type, ParameterType, False)
        self.value = value
        self.constraint_groups = []

    def __eq__(self, other):
        if isinstance(other, Variable):
            if (
                self.get_attributes() == other.get_attributes()
                and self.constraint_groups == other.constraint_groups
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Variable

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A variable element (same as generated by the class itself)

        Returns
        -------
            variable (Variable): Variable object

        """
        name = element.attrib["name"]
        value = element.attrib["value"]
        variable_type = convert_enum(
            element.attrib["variableType"], ParameterType, False
        )
        variable = Variable(name, variable_type, value)
        constraint_groups = element.findall("ValueConstraintGroup")
        for constraint_group in constraint_groups:
            variable.add_value_constraint_group(
                ValueConstraintGroup.parse(constraint_group)
            )
        return variable

    def get_attributes(self):
        """returns the attributes of the Variable as a dict"""
        return {
            "name": self.name,
            "variableType": self.variable_type.get_name(),
            "value": str(self.value),
        }

    def get_element(self):
        """returns the elementTree of the Variable"""
        if self.isVersionEqLess(minor=1):
            raise OpenSCENARIOVersionError("Variables were introduced in OSC 1.2")
        element = ET.Element("VariableDeclaration", attrib=self.get_attributes())
        return element


class Orientation(VersionBase):
    """Orientation describes the angular orientation of an entity

    Parameters
    ----------
        h (float): header

        p (float): pitch

        r (float): roll

        reference (ReferenceContext): absolute or relative

    Attributes
    ----------
        h (float): header

        p (float): pitch

        r (float): roll

        reference (ReferenceContext): absolute or relative

    Methods
    -------
        is_filled()
            check is any orientations are set

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, h=None, p=None, r=None, reference=None):
        """initalize Orientation

        Parameters
        ----------
            h (float): header

            p (float): pitch

            r (float): roll

            reference (ReferenceContext): absolute or relative
        """
        self.h = convert_float(h)
        self.p = convert_float(p)
        self.r = convert_float(r)
        self.ref = convert_enum(reference, ReferenceContext, True)

    def __eq__(self, other):
        if isinstance(other, Orientation):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Orientation

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A orientation element (same as generated by the class itself)

        Returns
        -------
            orientation (Orientation): a Orientation object

        """
        h = None
        p = None
        r = None
        reference = None
        if "h" in element.attrib:
            h = convert_float(element.attrib["h"])
        if "p" in element.attrib:
            p = convert_float(element.attrib["p"])
        if "r" in element.attrib:
            r = convert_float(element.attrib["r"])
        if "type" in element.attrib:
            reference_str = element.attrib["type"]
            reference = convert_enum(reference_str, ReferenceContext, False)

        return Orientation(h, p, r, reference)

    def is_filled(self):
        """is_filled check is any orientations are  set

        Returns: boolean

        """
        if (
            self.h is not None
            or self.p is not None
            or self.r is not None
            or self.ref is not None
        ):
            return True
        else:
            return False

    def get_attributes(self):
        """returns the attributes of the Orientation as a dict"""
        retdict = {}
        if self.h is not None:
            retdict["h"] = str(self.h)

        if self.p is not None:
            retdict["p"] = str(self.p)

        if self.r is not None:
            retdict["r"] = str(self.r)

        if self.ref is not None:
            retdict["type"] = self.ref.get_name()

        return retdict

    def get_element(self):
        """returns the elementTree of the Orientation"""
        return ET.Element("Orientation", attrib=self.get_attributes())


class TransitionDynamics(VersionBase):
    """TransitionDynamics is used to define how the dynamics of a change

    Parameters
    ----------
        shape (DynamicsShapes): shape of the transition

        dimension (DynamicsDimension): the dimension of the transition (rate, time or distance)

        value (float): the value of the dynamics (time rate or distance)

        following_mode (FollowingMode): the following mode of the TransitionDynamics (valid from OSC V1.2)
            Default: None

    Attributes
    ----------
        shape (DynamicsShapes): shape of the transition

        dimension (DynamicsDimension): the dimension of the transition (rate, time or distance)

        value (float): the value of the dynamics (time rate or distance)

        following_mode (FollowingMode): the following mode of the TransitionDynamics (valid from OSC V1.2)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, shape, dimension, value: float, following_mode=None):
        """
        Parameters
        ----------
            shape (DynamicsShapes): shape of the transition

            dimension (DynamicsDimension): the dimension of the transition (rate, time or distance)

            value (float): the value of the dynamics (time rate or distance)

            following_mode (FollowingMode): the following mode of the TransitionDynamics (valid from OSC V1.2)
                Default: None
        """

        self.shape = convert_enum(shape, DynamicsShapes, False)
        self.dimension = convert_enum(dimension, DynamicsDimension, False)
        self.value = convert_float(value)
        self.following_mode = convert_enum(following_mode, FollowingMode, True)

    def __eq__(self, other):
        if isinstance(other, TransitionDynamics):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TransitionDynamics

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A TransitionDynamics element (same as generated by the class itself)

        Returns
        -------
            transitiondynamics (TransitionDynamics): a TransitionDynamics object

        """
        shape = convert_enum(element.attrib["dynamicsShape"], DynamicsShapes)
        dimension = convert_enum(element.attrib["dynamicsDimension"], DynamicsDimension)
        value = convert_float(element.attrib["value"])
        following_mode = None
        if "followingMode" in element.attrib:
            following_mode = convert_enum(
                element.attrib["followingMode"], FollowingMode
            )
        return TransitionDynamics(shape, dimension, value, following_mode)

    def get_attributes(self):
        """returns the attributes of the TransitionDynamics as a dict"""
        retdict = {
            "dynamicsShape": self.shape.get_name(),
            "value": str(self.value),
            "dynamicsDimension": self.dimension.get_name(),
        }
        if self.following_mode is not None:
            retdict["followingMode"] = self.following_mode.get_name()
        return retdict

    def get_element(self, name="TransitionDynamics"):
        """returns the elementTree of the TransitionDynamics"""
        return ET.Element(name, self.get_attributes())


class DynamicsConstraints(VersionBase):
    """DynamicsConstraints is used by triggers

    Parameters
    ----------
        max_acceleration (float): maximum acceleration allowed

        max_deceleration (float): maximum deceleration allowed

        max_speed (float): maximum speed allowed

        max_acceleration_rate (float): maximum acceleration rate allowed

        max_deceleration_rate (float): maximum deceleration rate allowed

    Attributes
    ----------
        max_acceleration (float): maximum acceleration allowed

        max_deceleration (float): maximum deceleration allowed

        max_speed (float): maximum speed allowed

        max_acceleration_rate (float): maximum acceleration rate allowed

        max_deceleration_rate (float): maximum deceleration rate allowed

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        is_filled()
            check is any constraints are set

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(
        self,
        max_acceleration=None,
        max_deceleration=None,
        max_speed=None,
        max_acceleration_rate=None,
        max_deceleration_rate=None,
    ):
        """initalize DynamicsConstrains"""

        self.max_acceleration = convert_float(max_acceleration)
        self.max_deceleration = convert_float(max_deceleration)
        self.max_speed = convert_float(max_speed)
        self.max_acceleration_rate = convert_float(max_acceleration_rate)
        self.max_deceleration_rate = convert_float(max_deceleration_rate)

    @staticmethod
    def parse(element):
        """Parses the xml element of DynamicsConstraints

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A dynamics constraint element (same as generated by the class itself)

        Returns
        -------
            constrains (DynamicsConstrains): a DynamicsConstrains object

        """
        max_acceleration = None
        max_deceleration = None
        max_speed = None
        max_acceleration_rate = None
        max_deceleration_rate = None

        if "maxAcceleration" in element.attrib:
            max_acceleration = convert_float(element.attrib["maxAcceleration"])
        if "maxDeceleration" in element.attrib:
            max_deceleration = convert_float(element.attrib["maxDeceleration"])
        if "maxSpeed" in element.attrib:
            max_speed = convert_float(element.attrib["maxSpeed"])
        if "maxAccelerationRate" in element.attrib:
            max_acceleration_rate = convert_float(element.attrib["maxAccelerationRate"])
        if "maxDecelerationRate" in element.attrib:
            max_deceleration_rate = convert_float(element.attrib["maxDecelerationRate"])

        return DynamicsConstraints(
            max_acceleration,
            max_deceleration,
            max_speed,
            max_acceleration_rate,
            max_deceleration_rate,
        )

    def __eq__(self, other):
        if isinstance(other, DynamicsConstraints):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    def is_filled(self):
        """is_filled check is any constraints are set

        Returns: boolean

        """

        if self.max_acceleration or self.max_deceleration or self.max_speed:
            return True
        else:
            return False

    def get_attributes(self):
        """returns the attributes of the DynamicsConstrains as a dict"""
        retdict = {}
        if self.max_speed is not None:
            retdict["maxSpeed"] = str(self.max_speed)
        if self.max_deceleration is not None:
            retdict["maxDeceleration"] = str(self.max_deceleration)
        if self.max_acceleration is not None:
            retdict["maxAcceleration"] = str(self.max_acceleration)
        if self.max_acceleration_rate is not None:
            if not self.isVersion(minor=2):
                raise OpenSCENARIOVersionError(
                    "maxAccelerationRate was introduced in OpenSCENARIO V1.2"
                )
            retdict["maxAccelerationRate"] = str(self.max_acceleration_rate)
        if self.max_deceleration_rate is not None:
            if not self.isVersion(minor=2):
                raise OpenSCENARIOVersionError(
                    "maxDecelerationRate was introduced in OpenSCENARIO V1.2"
                )
            retdict["maxDecelerationRate"] = str(self.max_deceleration_rate)
        return retdict

    def get_element(self, name="DynamicConstraints"):
        """returns the elementTree of the DynamicsConstrains"""
        return ET.Element(name, attrib=self.get_attributes())


class License(VersionBase):
    """License creates the License used by FileHeader in the OpenScenario file
    (valid from OpenSCENARIO V1.1)

    Parameters
    ----------
        name (str): name of the License

        resource (str): link to URL
            Default: None

        spdxId (str): license identifier
            Default: None

    Attributes
    ----------
        name (str): name of the License

        resource (str): link to URL

        spdxId (str): license identifier

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of FileHeader

        get_attributes()
            Returns a dictionary of all attributes of FileHeader

    """

    def __init__(self, name, resource=None, spdxId=None):
        """init the License

        Parameters
        ----------
            name (str): name of the License

            resource (str): link to URL
                Default: None

            spdxId (str): license identifier
                Default: None
        """
        self.name = name
        self.resource = resource
        self.spdxId = spdxId

    def __eq__(self, other):
        if isinstance(other, License):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    # TODO: Check Class License test string 0..1 The full license

    @staticmethod
    def parse(element):
        """Parses the xml element of License

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A license element (same as generated by the class itself)

        Returns
        -------
            license (License): a License object

        """
        name = element.attrib["name"]
        resource = None
        if "resource" in element.attrib:
            resource = element.attrib["resource"]
        spdxId = None
        if "spdxId" in element.attrib:
            spdxId = element.attrib["spdxId"]

        return License(name, resource, spdxId)

    def get_attributes(self):
        """returns the attributes as a dict of the License"""
        retdict = {}
        retdict["name"] = self.name
        if self.resource:
            retdict["resource"] = self.resource
        if self.spdxId:
            retdict["spdxId"] = self.spdxId
        return retdict

    def get_element(self):
        """returns the elementTree of the License"""
        if self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "License was introduced in OpenSCENARIO V1.1"
            )
        element = ET.Element("License", attrib=self.get_attributes())

        return element


class FileHeader(VersionBase):
    """FileHeader creates the header of the OpenScenario file1

    Parameters
    ----------
        name (str): name of the scenario

        author (str): the author of the scenario

        revMinor (int): the minor revision of the standard
            Default: 2

        license (License): license (valid from OpenSCENARIO V1.1)
            Default: None

        creation_date (datetime.datetime): optional hardcoded creation date
            Default: datetime.datetime.now() (when actually generating the xml)

        properties (Properties): additional info about the scenario
            Default: None
    Attributes
    ----------
        name (str): name of the scenario

        author (str): the author of the scenario

        license (License): license (valid from OpenSCENARIO V1.1)

        creation_date (datetime.datetime): optional hardcoded creation date

        properties (Properties): additional info about the scenarios
    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of FileHeader

        get_attributes()
            Returns a dictionary of all attributes of FileHeader

    """

    def __init__(
        self,
        author,
        description,
        revMinor=_MINOR_VERSION,
        license=None,
        creation_date=None,
        properties=None,
    ):
        """FileHeader creates the header of the OpenScenario file1

        Parameters
        ----------
            name (str): name of the scenario

            author (str): the author of the scenario

            revMinor (int): the minor revision of the standard
                Default: 1

            license (License): license (valid from OpenSCENARIO V1.1)
                Default: None

            creation_date (datetime.datetime): optional hardcoded creation date
                Default: datetime.datetime.now() (when actually generating the xml)
            properties (Properties): additional info about the scenario
                Default: None
        """
        self.description = description
        self.author = author
        self._revMajor = 1
        self._revMinor = revMinor
        self.creation_date = creation_date
        self.setVersion(minor=revMinor)
        if license and not isinstance(license, License):
            raise TypeError("license is not of type License")
        self.license = license
        if properties and not isinstance(properties, Properties):
            raise TypeError("properties is not of type Properties")
        self.properties = properties

    def __eq__(self, other):
        if isinstance(other, FileHeader):
            if (
                self.description == other.description
                and self.author == other.author
                and self._revMajor == other._revMajor
                and self._revMinor == other._revMinor
                and self.properties == other.properties
            ):
                # will not compare date, since this will never be the same
                return True
        return False

    # TODO: License handling add_license ???

    @staticmethod
    def parse(element):
        """Parses the xml element of FileHeader

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A file header element (same as generated by the class itself)

        Returns
        -------
            header (FileHeader): a FileHeader object

        """
        author = element.attrib["author"]
        description = element.attrib["description"]
        # revMinor = element.attrib['revMinor']
        # revMajor = element.attrib['revMajor']
        license = None
        if element.find("license") != None:
            license = License.parse(element.find("license"))

        return FileHeader(author=author, description=description, license=license)

    def get_attributes(self):
        """returns the attributes as a dict of the FileHeader"""
        retdict = {
            "description": self.description,
            "author": self.author,
            "revMajor": str(self.version_major),
            "revMinor": str(self.version_minor),
        }
        if self.creation_date != None:
            retdict["date"] = self.creation_date.isoformat()
        else:
            retdict["date"] = dt.datetime.now().isoformat()
        return retdict

    def get_element(self):
        """returns the elementTree of the FileHeader"""
        element = ET.Element("FileHeader", attrib=self.get_attributes())
        if self.license:
            if self.isVersionEqLarger(minor=1):
                element.append(self.license.get_element())
            else:
                raise OpenSCENARIOVersionError(
                    "License in FileHeader was introduced in OSC 1.1"
                )
        if self.properties:
            if self.isVersionEqLarger(minor=2):
                element.append(self.properties.get_element())
            else:
                raise OpenSCENARIOVersionError(
                    "Properties in FileHeader was introduced in OSC 1.2"
                )

        return element


class TimeReference(VersionBase):
    """the TimeReference class creates a TimeReference,

    Parameters
    ----------
        referece_domain (ReferenceContext): absolute or relative time reference (must be combined with scale and offset)
            Default: None

        scale (float): scalefactor of the timeings (must be combined with referece_domain and offset)
            Default: None

        offset (float): offset for time values (must be combined with referece_domain and scale)
            Default: None

    Attributes
    ----------
        referece_domain (ReferenceContext): absolute or relative time reference

        scale (float): scalefactor of the timeings

        offset (float): offset for time values

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, reference_domain=None, scale=None, offset=None):
        """initalize the TimeReference

        Parameters
        ----------
        referece_domain (ReferenceContext): absolute or relative time reference (must be combined with scale and offset)
            Default: None

        scale (float): scalefactor of the timeings (must be combined with referece_domain and offset)
            Default: None

        offset (float): offset for time values (must be combined with referece_domain and scale)
            Default: None

        """
        nones = [reference_domain == None, scale == None, offset == None]
        if sum(nones) == 3:
            self._only_nones = True
        elif sum(nones) == 0:
            self._only_nones = False
        else:
            raise ValueError("missing inputs for time reference")
        self.reference_domain = convert_enum(reference_domain, ReferenceContext, True)
        self.scale = convert_float(scale)
        self.offset = convert_float(offset)

    def __eq__(self, other):
        if isinstance(other, TimeReference):
            if not self._only_nones and not other._only_nones:
                if self.get_attributes() == other.get_attributes():
                    return True
            elif self._only_nones == other._only_nones:
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TimeReference

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A time reference element (same as generated by the class itself)

        Returns
        -------
            timing (TimeReference): a TimeReference object

        """
        if element.find("None") != None:
            return TimeReference()

        timing_element = element.find("Timing")
        scale = None
        offset = None
        reference_domain = None

        if "offset" in timing_element.attrib:
            offset = timing_element.attrib["offset"]
        if "scale" in timing_element.attrib:
            scale = timing_element.attrib["scale"]
        if "domainAbsoluteRelative" in timing_element.attrib:
            reference_domain = convert_enum(
                timing_element.attrib["domainAbsoluteRelative"], ReferenceContext
            )

        return TimeReference(reference_domain, scale, offset)

    def get_attributes(self):
        """returns the attributes of the TimeReference as a dict"""
        retdict = {}
        retdict["domainAbsoluteRelative"] = self.reference_domain.get_name()
        retdict["scale"] = str(self.scale)
        retdict["offset"] = str(self.offset)
        return retdict

    def get_element(self):
        """returns the elementTree of the TimeReference"""

        element = ET.Element("TimeReference")
        if self._only_nones:
            ET.SubElement(element, "None")
        else:
            ET.SubElement(element, "Timing", self.get_attributes())

        return element


class _TrafficSignalState(VersionBase):
    """crates a _TrafficSignalState used by Phase

    Parameters
    ----------
        signal_id (str): id of the traffic signal

        state (str): state of the signal

    Attributes
    ----------
        signal_id (str): id of the traffic signal

        state (str): state of the signal

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, signal_id, state):
        """initalize the _TrafficSignalState

        Parameters
        ----------
            signal_id (str): id of the traffic signal

            state (str): state of the signal

        """

        self.signal_id = signal_id
        self.state = state

    def __eq__(self, other):
        if isinstance(other, _TrafficSignalState):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of _TrafficSignalState

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A traffice signal state element (same as generated by the class itself)

        Returns
        -------
            ts_state (_TrafficSignalState): a _TrafficSignalState object

        """
        signal_id = element.attrib["trafficSignalId"]
        state = element.attrib["state"]
        return _TrafficSignalState(signal_id=signal_id, state=state)

    def get_attributes(self):
        """returns the attributes of the _TrafficSignalState"""
        retdict = {}
        retdict["trafficSignalId"] = self.signal_id
        retdict["state"] = self.state
        return retdict

    def get_element(self):
        """returns the elementTree of the _TrafficSignalState"""
        return ET.Element("TrafficSignalState", attrib=self.get_attributes())


class Phase(VersionBase):
    """crates a Traffic light phase

    Parameters
    ----------
        name (str): if of the phase

        duration (float): duration of the phase

        traffic_group_state (str): state for a group of signals (valid since V1.2)
            Default: None

    Attributes
    ----------
        name (str): if of the phase

        duration (float): duration of the phase

        signalstates (list of _TrafficSignalState): traffic signal states

        traffic_group_state (str): state for a group of signals (valid since V1.2)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

        add_stignal_state(signal_id,state)
            add a traffic signal state
    """

    def __init__(self, name, duration, traffic_group_state=None):
        """initalize the Phase

        Parameters
        ----------
            name (str): if of the phase

            duration (float): duration of the phase

            traffic_group_state (str): state for a group of signals (valid since V1.2)
                Default: None

        """

        self.name = name
        self.duration = convert_float(duration)
        self.signalstates = []
        self.traffic_group_state = traffic_group_state

    def __eq__(self, other):
        if isinstance(other, Phase):
            if (
                self.get_attributes() == other.get_attributes()
                and self.signalstates == other.signalstates
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Phase

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A phase element (same as generated by the class itself)

        Returns
        -------
            phase (Phase): a Phase object

        """
        duration = convert_float(element.attrib["duration"])
        name = element.attrib["name"]
        group = None
        # NOTE: Misspelling according to standard...
        if element.find("TrafficeSignalGroupState") is not None:
            group = element.find("TrafficeSignalGroupState").attrib["state"]
        phase = Phase(name, duration, group)
        signalstates = element.findall("TrafficSignalState")
        if signalstates != None:
            for signalstate in signalstates:
                traffic_signal_state = _TrafficSignalState.parse(signalstate)
                phase.signalstates.append(traffic_signal_state)
        return phase

    def add_signal_state(self, signal_id, state):
        """Adds a phase of the traffic signal

        Parameters
        ----------
            signal_id (str): id of the traffic signal in the road network

            state (str): state of the signal defined in the road network

        """
        self.signalstates.append(_TrafficSignalState(signal_id, state))
        return self

    def get_attributes(self):
        """returns the attributes of the TrafficSignalController"""
        retdict = {}
        retdict["name"] = self.name
        retdict["duration"] = str(self.duration)
        return retdict

    def get_element(self):
        """returns the elementTree of the Polyline"""
        element = ET.Element("Phase", attrib=self.get_attributes())
        for s in self.signalstates:
            element.append(s.get_element())
        if self.traffic_group_state is not None:
            # NOTE: Misspelling according to standard...
            if self.isVersionEqLess(minor=1):
                raise OpenSCENARIOVersionError(
                    "TrafficSignalGroupStage was added in OSC 1.2."
                )
            ET.SubElement(
                element,
                "TrafficeSignalGroupState",
                attrib={"state": self.traffic_group_state},
            )
        return element


class TrafficSignalController(VersionBase):
    """the TrafficSignalController class creates a polyline of (minimum 2) positions

    Parameters
    ----------
        name (str): if of the trafic signal

        delay (float): delay of the phase shift
            Default: None

        reference (string): id to the controller in the roadnetwork
            Default: None

    Attributes
    ----------
        name (str): if of the trafic signal

        delay (float): delay of the phase shift
            Default: None
        reference (string): id to the controller in the roadnetwork
            Default: None

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

        add_phase(Phase)
            add a phase to the trafficsitnal controller
    """

    def __init__(self, name, delay=None, reference=None):
        """initalize the TrafficSignalController

        Parameters
        ----------
            name (str): if of the trafic signal

            delay (float): delay of the phase shift
                Default: None

            reference (string): id to the controller in the RoadNetwork
                Default: None

        """

        self.name = name
        self.delay = delay
        self.reference = reference
        self.phases = []

    def __eq__(self, other):
        if isinstance(other, TrafficSignalController):
            if (
                self.get_attributes() == other.get_attributes()
                and self.phases == other.phases
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TrafficSignalController

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A traffice signal controller element (same as generated by the class itself)

        Returns
        -------
            tsc (TrafficSignalController): a TrafficSignalController object

        """
        name = element.attrib["name"]

        delay = None
        if "delay" in element.attrib:
            delay = element.attrib["delay"]

        reference = None
        if "reference" in element.attrib:
            reference = element.attrib["reference"]

        tsc = TrafficSignalController(name, delay, reference)

        phases = element.findall("Phase")
        if phases != None:
            for phase in phases:
                tsc.phases.append(Phase.parse(phase))

        return tsc

    def add_phase(self, phase):
        """Adds a phase of the traffic signal

        Parameters
        ----------
            phase (Phase): a phase of the trafficsignal

        """
        if not isinstance(phase, Phase):
            raise TypeError("phase input is not of type Phase")
        self.phases.append(phase)
        return self

    def get_attributes(self):
        """returns the attributes of the TrafficSignalController"""
        retdict = {}
        retdict["name"] = self.name
        if self.delay is not None:
            retdict["delay"] = str(self.delay)
        if self.reference:
            retdict["reference"] = self.reference
        return retdict

    def get_element(self):
        """returns the elementTree of the TrafficSignalController"""
        element = ET.Element("TrafficSignalController", attrib=self.get_attributes())
        for ph in self.phases:
            element.append(ph.get_element())
        return element


class TrafficDefinition(VersionBase):
    """the TrafficDefinition class creates a TrafficDefinition used by the different TrafficActions

    Parameters
    ----------
        name (str): name of the traffic definition


    Attributes
    ----------
        name (str): name of the traffic definition

        vehicleweights (list of floats): The weights of the vehicle categories (VehicleCategoryDistribution-weight)

        vehiclecategories (list of VehicleCategory): the vehicle category ((VehicleCategoryDistribution-category))

        controllerweights (list of floats): The weights of the controllers

        controllers (list of Controller/CatalogReference): The controllers for the traffic


    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

        add_vehicle(vehiclecategory,weight)
            Adds a vehicle to the traffic definition

        add_controller(controller,weight)
            Adds a controller to the traffic definition

    """

    def __init__(self, name):
        """initalize the TrafficDefinition

        Parameters
        ----------
            name (str): name of the traffic definition

        """

        self.name = name
        self.vehicleweights = []
        self.vehiclecategories = []
        self.controllerweights = []
        self.controllers = []
        self.vehicle_roles = []
        self.vehicle_roles_weights = []

    def __eq__(self, other):
        if isinstance(other, TrafficDefinition):
            if (
                self.get_attributes() == other.get_attributes()
                and self.vehicleweights == other.vehicleweights
                and self.vehiclecategories == other.vehiclecategories
                and self.controllerweights == other.controllerweights
                and self.controllers == other.controllers
                and self.vehicle_roles == other.vehicle_roles
                and self.vehicle_roles_weights == other.vehicle_roles_weights
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TrafficDefinition

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A traffic definition element (same as generated by the class itself)

        Returns
        -------
            td (TrafficDefinition): a TrafficDefinition object

        """
        name = element.attrib["name"]
        td = TrafficDefinition(name)

        vehicle_distributions = element.find("VehicleCategoryDistribution")
        vehicle_entries = vehicle_distributions.findall(
            "VehicleCategoryDistributionEntry"
        )
        for entry in vehicle_entries:
            weight = convert_float(entry.attrib["weight"])
            category = convert_enum(entry.attrib["category"], VehicleCategory)
            td.add_vehicle(category, weight)

        controller_distributions = element.find("ControllerDistribution")
        controller_entries = controller_distributions.findall(
            "ControllerDistributionEntry"
        )
        for controller_dist in controller_entries:
            weight = convert_float(controller_dist.attrib["weight"])
            if controller_dist.find("Controller"):
                controller = Controller.parse(controller_dist.find("Controller"))
                td.add_controller(controller, weight)
            else:
                catalog_reference = CatalogReference.parse(
                    controller_dist.find("CatalogReference")
                )
                td.add_controller(catalog_reference, weight)

        vehicle_role_distributions = element.find("VehicleRoleDistribution")
        if vehicle_role_distributions is not None:
            for entry in vehicle_role_distributions.findall(
                "VehicleRoleDistributionEntry"
            ):
                td.add_vehicle_role(
                    convert_enum(entry.attrib["role"], Role), entry.attrib["weight"]
                )
        return td

    def add_vehicle(self, vehiclecategory, weight):
        """Adds a vehicle to the traffic distribution

        Parameters
        ----------
            vehiclecategory (VehicleCategory): vehicle category of the entity in the traffic

            weight (float): the corresponding weight for the distribution of the vehicle category

        """
        self.vehiclecategories.append(convert_enum(vehiclecategory, VehicleCategory))
        self.vehicleweights.append(weight)
        return self

    def add_vehicle_role(self, vehicle_role, weight):
        """Adds a vehicle role to a distribution

        Parameters
        ----------
            vehicle_role (Role): add a role to the vehicle role distribution

            weight (float): the weight of that vehicle role
        """
        self.vehicle_roles_weights.append(convert_float(weight))
        self.vehicle_roles.append(convert_enum(vehicle_role, Role))

    def add_controller(self, controller, weight):
        """Adds a controller to the traffic distribution

        Parameters
        ----------
            controller (Controller or CatalogReference): a controller or catalog reference to a controller

            weight (float): the corresponding weight for the controller

        """
        if not (
            isinstance(controller, Controller)
            or isinstance(controller, CatalogReference)
        ):
            raise TypeError(
                "controller input not of type Controller or CatalogReference"
            )
        self.controllers.append(controller)
        self.controllerweights.append(weight)
        return self

    def get_attributes(self):
        """returns the attributes of the TrafficDefinition"""
        retdict = {}
        retdict["name"] = self.name
        return retdict

    def get_element(self):
        """returns the elementTree of the TrafficDefinition"""
        if not self.controllers:
            ValueError("No controllers defined for the TrafficDefinition")
        if not self.vehiclecategories:
            ValueError("No Vehicles defined for the TrafficDefinition")

        element = ET.Element("TrafficDefinition", attrib=self.get_attributes())

        veh_element = ET.SubElement(element, "VehicleCategoryDistribution")
        for i in range(len(self.vehiclecategories)):
            ET.SubElement(
                veh_element,
                "VehicleCategoryDistributionEntry",
                attrib={
                    "category": self.vehiclecategories[i].get_name(),
                    "weight": str(self.vehicleweights[i]),
                },
            )

        cnt_element = ET.SubElement(element, "ControllerDistribution")
        for i in range(len(self.controllers)):
            tmp_controller = ET.SubElement(
                cnt_element,
                "ControllerDistributionEntry",
                attrib={"weight": str(self.controllerweights[i])},
            )
            tmp_controller.append(self.controllers[i].get_element())
        if self.vehicle_roles:
            if self.version_minor < 2:
                raise OpenSCENARIOVersionError(
                    "VehicleRoleDistribution was added in OSC V1.2"
                )
            role_element = ET.SubElement(element, "VehicleRoleDistribution")
            for i in range(len(self.vehicle_roles)):
                ET.SubElement(
                    role_element,
                    "VehicleRoleDistributionEntry",
                    attrib={
                        "role": self.vehicle_roles[i].get_name(),
                        "weight": str(self.vehicle_roles_weights[i]),
                    },
                )
        return element


class CatalogFile(VersionBase):
    """The CatalogFile class handles any catalogs in open scenario, such as writing, and updating them

    Parameters
    ----------
        prettyprint (boolean): if the final file should have prettyprint or not
            Default: True

    Attributes
    ----------
        prettyprint: if the final file should have prettyprint or not

        catalog_element (Element): the element that is worked with

        filename (str): path to the file to be written to

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

        add_catalog(catalogname, path)
            Adds a new catalog
    """

    def __init__(self, prettyprint=True, encoding="utf-8"):
        """initalize the CatalogFile class

        Parameters
        ----------
            prettyprint (boolean): if the final file should have prettyprint or not
                Default: True
        """
        self.prettyprint = prettyprint
        self.catalog_element = None
        self.filename = ""
        self.encoding = encoding

    def add_to_catalog(self, obj, osc_minor_version=_MINOR_VERSION):
        """add_to_catalog adds an element to the catalog

        Parameters
        ----------
            obj (*pyoscx): any pyoscx object (should be matching with the catalog)

            osc_minor_version (int): the minor version of OpenSCENARIO to write to the catalog
                Default: same as package
        """
        if self.catalog_element == None:
            OSError("No file has been created or opened")
        fileheader = self.catalog_element.find("FileHeader")
        self.version_minor = osc_minor_version
        if fileheader.attrib["revMinor"] != osc_minor_version:
            Warning(
                "The Catalog and the added object does not have the same OpenSCENARIO version."
            )
        catalogs = self.catalog_element.find("Catalog")
        catalogs.append(obj.get_element())
        return self

    def open_catalog(self, filename):
        """open_catalog reads an existing catalog file

        Parameters
        ----------
            filename (str): path to the catalog file

        """
        self.filename = filename
        tree = ET.parse(self.filename)
        self.catalog_element = tree.getroot()

    def create_catalog(self, filename, catalogtype, description, author):
        """create_catalog_element creates an empty catalog of a desiered type,

        Parameters
        ----------
            filename (str): path of the new catalog file

            catalogtype (str): name of the catalog

            description (str): description of the catalog

            author (str): author of the catalog

        """
        self.filename = filename
        self.catalog_element = self.create_catalog_element(
            catalogtype, description, author
        )

    def create_catalog_element(self, catalogtype, description, author):
        """create_catalog_element creates an empty catalog of a desiered type,

        Parameters
        ----------
            catalogtype (str): name of the catalog

            description (str): description of the catalog

            author (str): author of the catalog

        """
        element = ET.Element(
            "OpenSCENARIO",
            attrib={
                "xmlns:xsi": XMLNS,
                "xsi:noNamespaceSchemaLocation": "../../" + XSI,
            },
        )
        #         header = FileHeader(description, author)
        header = FileHeader(author, description)
        element.append(header.get_element())
        ET.SubElement(element, "Catalog", attrib={"name": catalogtype})

        return element

    def dump(self):
        """writes the new/updated catalog file"""
        printToFile(
            self.catalog_element, self.filename, self.prettyprint, self.encoding
        )


class _BaseCatalog(VersionBase):
    """the _BaseCatalog should be inherited by other classes that should be able to create catalogs from their elements"""

    def __init__(self):
        super().__init__()
        self.parameters = ParameterDeclarations()

    def add_parameter(self, parameter):
        """adds a parameter to the Trajectory

        Parameters
        ----------
            parameter (Parameter): the parameter to add

        """
        if not isinstance(parameter, Parameter):
            raise TypeError("input parameter is not of type Parameter")
        self.parameters.add_parameter(parameter)
        return self

    def add_parameters_to_element(self, element):
        """adds the parameterdeclaration to the element"""
        param_element = self.parameters.get_element()
        if param_element:
            element.append(param_element)

    def dump_to_catalog(self, filename, catalogtype, description, author):
        """dump_to_catalog creates a new catalog and adds the element to it

        Parameters
        ----------
            filename (str): path of the new catalog file

            catalogtype (str): name of the catalog

            description (str): description of the catalog

            author (str): author of the catalog

        """
        cf = CatalogFile()
        cf.create_catalog(filename, catalogtype, description, author)
        cf.add_to_catalog(self)
        cf.dump()

    def append_to_catalog(self, filename):
        """adds the the element to an existing catalog

        Parameters
        ----------
            filename (str): path to the catalog file

        """
        cf = CatalogFile()
        cf.open_catalog(filename)
        cf.add_to_catalog(self)
        cf.dump()


class Catalog(VersionBase):
    """The Catalog class creates the CatalogLocation of the OpenScenario input

    Parameters
    ----------

    Attributes
    ----------
        catalogs: dict of catalogs to add, and their path
    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        add_catalog(catalogname, path)
            Adds a new catalog
    """

    _CATALOGS = [
        "VehicleCatalog",
        "ControllerCatalog",
        "PedestrianCatalog",
        "MiscObjectCatalog",
        "EnvironmentCatalog",
        "ManeuverCatalog",
        "TrajectoryCatalog",
        "RouteCatalog",
    ]

    def __init__(self):
        """initalize the Catalog class"""
        self.catalogs = {}

    def __eq__(self, other):
        if isinstance(other, Catalog):
            if self.catalogs == other.catalogs:
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Catalog

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A Catalog element (same as generated by the class itself)

        Returns
        -------
            catalog (Catalog): a Catalog object

        """
        catalog = Catalog()

        vc_element = element.find("VehicleCatalog")
        if vc_element is not None:
            path = vc_element.find("Directory").attrib["path"]
            catalog.add_catalog("VehicleCatalog", path)

        cc_element = element.find("ControllerCatalog")
        if cc_element is not None:
            path = cc_element.find("Directory").attrib["path"]
            catalog.add_catalog("ControllerCatalog", path)

        pc_element = element.find("PedestrianCatalog")
        if pc_element is not None:
            path = pc_element.find("Directory").attrib["path"]
            catalog.add_catalog("PedestrianCatalog", path)

        moc_element = element.find("MiscObjectCatalog")
        if moc_element is not None:
            path = moc_element.find("Directory").attrib["path"]
            catalog.add_catalog("MiscObjectCatalog", path)

        ec_element = element.find("EnvironmentCatalog")
        if ec_element is not None:
            path = ec_element.find("Directory").attrib["path"]
            catalog.add_catalog("EnvironmentCatalog", path)

        mc_element = element.find("ManeuverCatalog")
        if mc_element is not None:
            path = mc_element.find("Directory").attrib["path"]
            catalog.add_catalog("ManeuverCatalog", path)

        tc_element = element.find("TrajectoryCatalog")
        if tc_element is not None:
            path = tc_element.find("Directory").attrib["path"]
            catalog.add_catalog("TrajectoryCatalog", path)

        rc_element = element.find("RouteCatalog")
        if rc_element is not None:
            path = rc_element.find("Directory").attrib["path"]
            catalog.add_catalog("RouteCatalog", path)

        return catalog

    def add_catalog(self, catalogname, path):
        """add new catalog to be used

        Parameters
        ----------
            catalogname (str): name of the catalog

            path (str): path to the catalog

        """

        if catalogname not in self._CATALOGS:
            raise ValueError(
                f"Not a correct catalog, approved catalogs are: {', '.join(self._CATALOGS)}."
            )

        self.catalogs[catalogname] = path
        return self

    def get_element(self):
        """returns the elementTree of the Catalog"""

        catloc = ET.Element("CatalogLocations")

        for i in self.catalogs:
            tmpel = ET.SubElement(catloc, i)
            ET.SubElement(tmpel, "Directory", {"path": self.catalogs[i]})
        return catloc


class CatalogReference(VersionBase):
    """CatalogReference creates an CatalogReference element of openscenario

    Parameters
    ----------
        catalogname (str): name of the catalog

        entryname (str): name of the entry in the catalog

    Attributes
    ----------
        catalogname (str): name of the catalog

        entryname (str): name of the entry in the catalog

        parameterassignments (list of ParameterAssignment): the parameter assignments for the given catalogreference

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        add_parameter_assignment(parameterref,value)
            Assigns a parameter with a value

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, catalogname, entryname):
        """initalize the CatalogReference

        Parameters
        ----------
            catalogname (str): name of the catalog

            entryname (str): name of the entry in the catalog

        """
        self.catalogname = catalogname
        self.entryname = entryname
        self.parameterassignments = []

    def __eq__(self, other):
        if isinstance(other, CatalogReference):
            if (
                self.get_attributes() == other.get_attributes()
                and self.parameterassignments == other.parameterassignments
            ):
                return True
        return False

    # TODO: CatalogElement???

    @staticmethod
    def parse(element):
        """Parses the xml element of CatalogReference

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A catalog reference element (same as generated by the class itself)

        Returns
        -------
            reference (CatalogReference): a catalog reference object

        """
        catalogname = element.attrib["catalogName"]
        entryname = element.attrib["entryName"]
        reference = CatalogReference(catalogname, entryname)

        parameter_assignments = element.find("ParameterAssignments")
        if parameter_assignments != None:
            parameters = parameter_assignments.findall("ParameterAssignment")
            for parameter in parameters:
                parameter_assignment = ParameterAssignment.parse(parameter)
                reference.parameterassignments.append(parameter_assignment)

        return reference

    def add_parameter_assignment(self, parameterref, value):
        """add_parameter_assignment adds a parameter and value to the catalog reference

        Parameters
        ----------
            parameterref (str): name of the parameter

            value (str): assigned value of the parameter
        """
        self.parameterassignments.append(ParameterAssignment(parameterref, value))
        return self

    def get_attributes(self):
        """returns the attributes of the CatalogReference as a dict"""
        return {"catalogName": self.catalogname, "entryName": self.entryname}

    def get_element(self):
        """returns the elementTree of the CatalogReference"""
        element = ET.Element("CatalogReference", attrib=self.get_attributes())
        if self.parameterassignments:
            parameterassigns = ET.SubElement(element, "ParameterAssignments")
        for parass in self.parameterassignments:
            parameterassigns.append(parass.get_element())
        return element


class ParameterAssignment(VersionBase):
    """ParameterAssignment creates an ParameterAssignment element of openscenario

    Parameters
    ----------
        parameterref (str): name of the parameter

        value (str): assigned value of the parameter


    Attributes
    ----------
        parameterref (str): name of the parameter

        value (str): assigned value of the parameter

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, parameterref, value):
        """initalize the ParameterAssignment

        Parameters
        ----------
            parameterref (str): name of the parameter

            value (str): assigned value of the parameter

        """
        self.parameterref = parameterref
        self.value = value

    def __eq__(self, other):
        if isinstance(other, ParameterAssignment):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of ParameterAssignment

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A parameter assignment element (same as generated by the class itself)

        Returns
        -------
            parameterassignment (ParameterAssignment): a ParameterAssignment object

        """

        value = element.attrib["value"]
        parameterref = element.attrib["parameterRef"]

        return ParameterAssignment(parameterref, value)

    def get_attributes(self):
        """returns the attributes of the ParameterAssignment as a dict"""
        retdict = {}
        retdict["parameterRef"] = self.parameterref
        retdict["value"] = str(self.value)
        return retdict

    def get_element(self):
        """returns the elementTree of the ParameterAssignment"""
        return ET.Element("ParameterAssignment", attrib=self.get_attributes())


class TimeOfDay(VersionBase):
    """TimeOfDay creates an TimeOfDay element of openscenario

    Parameters
    ----------
        animation (bool): if animation should be used

        year (int): year

        month (int): month

        day (int): day

        hour (int): hour

        minute (int): minute

        second (int): second

    Attributes
    ----------
        animation (bool): if animation should be used

        year (int): year

        month (int): month

        day (int): day

        hour (int): hour

        minute (int): minute

        second (int): second

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, animation, year, month, day, hour, minute, second):
        """initalize the TimeOfDay

        Parameters
        ----------
            animation (bool): if animation should be used

            year (int): year

            month (int): month

            day (int): day

            hour (int): hour

            minute (int): minute

            second (int): second

        """
        self.animation = convert_bool(animation)
        self.year = year
        self.month = month
        self.day = day
        self.hour = hour
        self.minute = minute
        self.second = second

    def __eq__(self, other):
        if isinstance(other, TimeOfDay):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TimeOfDay

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A time of day element (same as generated by the class itself)

        Returns
        -------
            timeofday (TimeOfDay): a TimeOfDay object
        """
        animation = convert_bool(element.attrib["animation"])
        var = element.attrib["dateTime"]
        year = convert_int(var[0:4])
        month = convert_int(var[5:7])
        day = convert_int(var[8:10])

        hour = convert_int(var[11:13])
        minute = convert_int(var[14:16])
        second = convert_int(var[17:19])

        return TimeOfDay(animation, year, month, day, hour, minute, second)

    def get_attributes(self):
        """returns the attributes of the TimeOfDay as a dict"""
        dt = (
            str(self.year)
            + "-"
            + "{:0>2}".format(self.month)
            + "-"
            + "{:0>2}".format(self.day)
            + "T"
            + "{:0>2}".format(self.hour)
            + ":"
            + "{:0>2}".format(self.minute)
            + ":"
            + "{:0>2}".format(self.second)
        )
        return {"animation": get_bool_string(self.animation), "dateTime": dt}

    def get_element(self):
        """returns the elementTree of the TimeOfDay"""
        return ET.Element("TimeOfDay", attrib=self.get_attributes())


class Weather(VersionBase):
    """Weather creates an Weather element of openscenario

    Parameters
    ----------
        cloudstate (CloudState, or FractionalCloudCover): cloudstate of the weather (CloudState (V1.0-1.1), FractionalCloudCover (>V1.2 ))
            Default: None

        atmosphericPressure (float): atmospheric pressure in Pa (valid from OpenSCENARIO V1.1)
            Default: None

        temperature (float): outside temperature (valid from OpenSCENARIO V1.1)
            Default: None

        sun (Sun): the sun position
            Default: None

        fog (Fog): fot state
            Default: None

        precipitation (Precipitation): the precipitation state
            Default: None

        wind (Wind): the wind (valid from OpenSCENARIO V1.1)
            Default: None

        dome_image (str): image file for the sky (valid from OpenSCENARIO V1.2)
            Default: None

        dome_azimuth_offset (float): offset for dome image (valid from OpenSCENARIO V1.2)
            Default: None
    Attributes
    ----------
        cloudstate (CloudState): cloudstate of the weather

        atmosphericPressure (float): atmospheric pressure in Pa (valid from OpenSCENARIO V1.1)

        temperature (float): outside temperature (valid from OpenSCENARIO V1.1)

        sun (Sun): the sun position

        fog (Fog): fot state

        precipitation (Precipitation): the precipitation state

        wind (Wind): the wind (valid from OpenSCENARIO V1.1)

        dome_image (str): image file for the sky (valid from OpenSCENARIO V1.2)

        dome_azimuth_offset (float): offset for dome image (valid from OpenSCENARIO V1.2)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(
        self,
        cloudstate=None,
        atmosphericPressure=None,
        temperature=None,
        sun=None,
        fog=None,
        precipitation=None,
        wind=None,
        dome_image=None,
        dome_azimuth_offset=None,
    ):
        """initalize the Weather

        Parameters
        ----------
            cloudstate (CloudState, or FractionalCloudCover): cloudstate of the weather (CloudState (V1.0-1.1), FractionalCloudCover (>V1.2 ))
                Default: None

            atmosphericPressure (float): atmospheric pressure in Pa (valid from OpenSCENARIO V1.1)
                Default: None

            temperature (float): outside temperature (valid from OpenSCENARIO V1.1)
                Default: None

            sun (Sun): the sun position
                Default: None

            fog (Fog): fot state
                Default: None

            precipitation (Precipitation): the precipitation state
                Default: None

            wind (Wind): the wind (valid from OpenSCENARIO V1.1)
                Default: None

            dome_image (str): image file for the sky (valid from OpenSCENARIO V1.2)
                Default: None

            dome_azimuth_offset (float): offset for dome image (valid from OpenSCENARIO V1.2)
                Default: None
        """
        try:
            self.cloudstate = convert_enum(cloudstate, CloudState, True)
        except Exception as e:
            self.cloudstate = convert_enum(cloudstate, FractionalCloudCover, True)

        if precipitation and not isinstance(precipitation, Precipitation):
            raise TypeError("precipitation input is not of type Precipitation")
        if fog and not isinstance(fog, Fog):
            raise TypeError("fog input is not of type Fog")
        if wind and not isinstance(wind, Wind):
            raise TypeError("wind input is not of type Wind")
        if sun and not isinstance(sun, Sun):
            raise TypeError("sun input is not of type Sun")

        # self.cloudstate = cloudstate
        self.atmosphericPressure = atmosphericPressure
        self.temperature = temperature
        self.fog = fog
        self.sun = sun
        self.wind = wind
        self.precipitation = precipitation
        self.dome_image = dome_image
        self.dome_azimuth_offset = convert_float(dome_azimuth_offset)

    def __eq__(self, other):
        if isinstance(other, Weather):
            if (
                self.get_attributes() == other.get_attributes()
                and self.fog == other.fog
                and self.wind == other.wind
                and self.sun == other.sun
                and self.precipitation == other.precipitation
                and self.dome_image == other.dome_image
                and self.dome_azimuth_offset == other.dome_azimuth_offset
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Weather

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A weather element (same as generated by the class itself)

        Returns
        -------
            weather (Weather): a Weather object

        """
        temperature = None
        atmosphericPressure = None
        cloudstate = None
        fog = None
        sun = None
        wind = None
        precipitation = None
        dome_file = None
        dome_azimuth = None

        if "temperature" in element.attrib:
            temperature = element.attrib["temperature"]
        if "atmosphericPressure" in element.attrib:
            atmosphericPressure = element.attrib["atmosphericPressure"]
        if "cloudState" in element.attrib:
            cloudstate = convert_enum(element.attrib["cloudState"], CloudState, False)
        if "fractionalCloudCover" in element.attrib:
            cloudstate = convert_enum(
                element.attrib["fractionalCloudCover"], FractionalCloudCover
            )
        if element.find("Sun") != None:
            sun = Sun.parse(element.find("Sun"))
        if element.find("Fog") != None:
            fog = Fog.parse(element.find("Fog"))
        if element.find("Precipitation") != None:
            precipitation = Precipitation.parse(element.find("Precipitation"))
        if element.find("Wind") != None:
            wind = Wind.parse(element.find("Wind"))
        if element.find("DomeImage") != None:
            dome_file = element.find("DomeImage").find("DomeFile").attrib["filepath"]

            if "azimuthOffset" in element.find("DomeImage").attrib:
                dome_azimuth = convert_float(
                    element.find("DomeImage").attrib["azimuthOffset"]
                )
        return Weather(
            cloudstate,
            atmosphericPressure,
            temperature,
            sun,
            fog,
            precipitation,
            wind,
            dome_file,
            dome_azimuth,
        )

    def get_attributes(self):
        """returns the attributes of the Weather as a dict"""
        retdict = {}
        if self.cloudstate:
            if hasattr(CloudState, str(self.cloudstate)):
                if self.isVersionEqLarger(minor=2):
                    raise OpenSCENARIOVersionError(
                        "Cloudstate is replaced with FractionalCloudCover for OSC versions > 1.1"
                    )
                retdict["cloudState"] = self.cloudstate.get_name()
            elif hasattr(FractionalCloudCover, str(self.cloudstate)):
                if self.isVersionEqLess(minor=1):
                    raise OpenSCENARIOVersionError(
                        "FractionalCloudCover was introduced in OSC 1.2"
                    )
                retdict["fractionalCloudCover"] = self.cloudstate.get_name()
            elif str(self.cloudstate)[0] == "$":
                if self.isVersionEqLarger(minor=2):
                    retdict["fractionalCloudCover"] = self.cloudstate.get_name()
                else:
                    retdict["cloudState"] = self.cloudstate.get_name()
        if self.temperature is not None and not self.isVersion(minor=0):
            retdict["temperature"] = str(self.temperature)
        elif self.temperature is not None and self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "temperature was introduced in OpenSCENARIO V1.1"
            )
        if self.atmosphericPressure is not None and not self.isVersion(minor=0):
            retdict["atmosphericPressure"] = str(self.atmosphericPressure)
        elif self.atmosphericPressure is not None and self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "atmosphericPressure was introduced in OpenSCENARIO V1.1"
            )
        return retdict

    def get_element(self):
        """returns the elementTree of the Weather"""
        if self.isVersion(minor=0):
            if self.sun == None:
                raise OpenSCENARIOVersionError("In OpenScenario 1.0, Sun is required.")
            if self.cloudstate == None:
                raise OpenSCENARIOVersionError(
                    "In OpenScenario 1.0, CloudState is required."
                )
            if self.fog == None:
                raise OpenSCENARIOVersionError("In OpenScenario 1.0, Fog is required.")
            if self.precipitation == None:
                raise OpenSCENARIOVersionError(
                    "In OpenScenario 1.0, Precipitation is required."
                )
        element = ET.Element("Weather", attrib=self.get_attributes())
        if self.sun:
            element.append(self.sun.get_element())
        if self.fog:
            element.append(self.fog.get_element())
        if self.precipitation:
            element.append(self.precipitation.get_element())
        if self.wind and not self.isVersion(minor=0):
            element.append(self.wind.get_element())
        if self.wind and self.isVersion(minor=0):
            raise OpenSCENARIOVersionError("Wind was introduced in OpenSCENARIO V1.1")
        if self.dome_image and (self.isVersion(minor=0) or self.isVersion(minor=1)):
            raise OpenSCENARIOVersionError(
                "DomeImage was introduced in OpenSCENARIO V1.2"
            )
        if self.dome_image:
            dome_attr = {}
            if self.dome_azimuth_offset:
                dome_attr["azimuthOffset"] = str(self.dome_azimuth_offset)
            dome_element = ET.SubElement(element, "DomeImage", attrib=dome_attr)
            ET.SubElement(
                dome_element, "DomeFile", attrib={"filepath": self.dome_image}
            )
        return element


class Fog(VersionBase):
    """Fog creates an Fog element used by the Weather element of openscenario

    Parameters
    ----------
        visual_range (int): visual range of fog

        bounding_box (BoundingBox): bounding box of fog
            Default: None

    Attributes
    ----------
        visual_range (int): visual range of fog

        bounding_box (BoundingBox): bounding box of fog

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, visual_range, bounding_box=None):
        """initalize the Fog

        Parameters
        ----------
            visual_range (int): visual range of fog

            bounding_box (BoundingBox): bounding box of fog
                Default: None

        """

        self.visual_range = visual_range
        if bounding_box and not isinstance(bounding_box, BoundingBox):
            raise TypeError("bounding_box not of type BoundingBox")
        self.bounding_box = bounding_box

    def __eq__(self, other):
        if isinstance(other, Fog):
            if (
                self.get_attributes() == other.get_attributes()
                and self.bounding_box == other.bounding_box
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Fog

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A fog element (same as generated by the class itself)

        Returns
        -------
            fog (Fog): a Fog object

        """

        visual_range = element.attrib["visualRange"]
        bounding_box = None
        if element.find("BoundingBox") != None:
            bounding_box = BoundingBox.parse(element.find("BoundingBox"))

        return Fog(visual_range, bounding_box)

    def get_attributes(self):
        """returns the attributes of the Precipitation as a dict"""
        retdict = {}
        retdict["visualRange"] = str(self.visual_range)

        return retdict

    def get_element(self):
        """returns the elementTree of the Fog"""
        element = ET.Element("Fog", attrib=self.get_attributes())
        if self.bounding_box is not None:
            element.append(self.bounding_box.get_element())

        return element


class Sun(VersionBase):
    """Sun creates an Sun element used by the Weather element of openscenario

    Parameters
    ----------
        intensity (float): intensity of the sun (in lux)

        azimuth (float): azimuth of the sun 0 north, pi/2 east, pi south, 3/2pi west

        elevation (float): sun elevation angle 0 x/y plane, pi/2 zenith

    Attributes
    ----------
        intensity (float): intensity of the sun (in lux)

        azimuth (float): azimuth of the sun 0 north, pi/2 east, pi south, 3/2pi west

        elevation (float): sun elevation angle 0 x/y plane, pi/2 zenith

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, intensity, azimuth, elevation):
        """initalize the Sun

        Parameters
        ----------
            intensity (float): intensity of the sun (in lux)

            azimuth (float): azimuth of the sun 0 north, pi/2 east, pi south, 3/2pi west

            elevation (float): sun elevation angle 0 x/y plane, pi/2 zenith

        """

        self.azimuth = azimuth
        self.intensity = intensity
        self.elevation = elevation

    def __eq__(self, other):
        if isinstance(other, Sun):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Sun

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A sun element (same as generated by the class itself)

        Returns
        -------
            sun (Sun): a Sun object

        """
        azimuth = element.attrib["azimuth"]
        elevation = element.attrib["elevation"]
        if "intensity" in element.attrib:
            intensity = element.attrib["intensity"]
        else:
            intensity = element.attrib["illuminance"]

        return Sun(intensity, azimuth, elevation)

    def get_attributes(self):
        """returns the attributes of the Precipitation as a dict"""
        retdict = {}
        retdict["azimuth"] = str(self.azimuth)
        if self.isVersion(minor=2):
            retdict["illuminance"] = str(self.intensity)
        else:
            retdict["intensity"] = str(self.intensity)
        retdict["elevation"] = str(self.elevation)
        return retdict

    def get_element(self):
        """returns the elementTree of the Sun"""
        element = ET.Element("Sun", attrib=self.get_attributes())

        return element


class Precipitation(VersionBase):
    """Precipitation creates an Precipitation element used by the Weather element of openscenario

    Parameters
    ----------
        precipitation (PrecipitationType): dry, rain or snow

        intensity (float): intensity of precipitation (0...1)

    Attributes
    ----------
        precipitation (PrecipitationType): dry, rain or snow

        intensity (float): intensity of precipitation (0...1)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, precipitation, intensity):
        """initalize the Precipitation

        Parameters
        ----------
            precipitation (PrecipitationType): dry, rain or snow

            intensity (float): intensity of precipitation (0...1)

        """
        self.precipitation = convert_enum(precipitation, PrecipitationType, False)
        self.intensity = convert_float(intensity)

    def __eq__(self, other):
        if isinstance(other, Precipitation):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Precipitation

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A precipitation element (same as generated by the class itself)

        Returns
        -------
            precipitation (Precipitation): a Precipitation object

        """
        intesity = None
        if "precipitationIntensity" in element.attrib:
            intesity = element.attrib["precipitationIntensity"]
        elif "intensity" in element.attrib:
            intesity = element.attrib["intensity"]
        precipitation = convert_enum(
            element.attrib["precipitationType"], PrecipitationType, False
        )

        return Precipitation(precipitation, intesity)

    def get_attributes(self):
        """returns the attributes of the Precipitation as a dict"""
        retdict = {}
        retdict["precipitationType"] = self.precipitation.get_name()
        if self.isVersion(minor=0):
            retdict["intensity"] = str(self.intensity)
        else:
            retdict["precipitationIntensity"] = str(self.intensity)
        return retdict

    def get_element(self):
        """returns the elementTree of the Precipitation"""
        element = ET.Element("Precipitation", attrib=self.get_attributes())

        return element


class Wind(VersionBase):
    """Wind creates an Wind element used by the Weather element of openscenario

    Parameters
    ----------
        direction (float): wind direction (radians)

        speed (float): wind speed (m/s)

    Attributes
    ----------
        direction (float): wind direction (radians)

        speed (float): wind speed (m/s)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, direction, speed):
        """initalize the Wind

        Parameters
        ----------
            direction (float): wind direction (radians)

            speed (float): wind speed (m/s)

        """
        self.direction = direction
        self.speed = speed

    def __eq__(self, other):
        if isinstance(other, Wind):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Wind

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A wind element (same as generated by the class itself)

        Returns
        -------
            wind (Wind): a Wind object

        """
        direction = element.attrib["direction"]
        speed = element.attrib["speed"]

        return Wind(direction, speed)

    def get_attributes(self):
        """returns the attributes of the Wind as a dict"""
        return {"direction": str(self.direction), "speed": str(self.speed)}

    def get_element(self):
        """returns the elementTree of the Wind"""
        if self.isVersion(minor=0):
            raise OpenSCENARIOVersionError("Wind was introduced in OSC 1.1")
        element = ET.Element("Wind", attrib=self.get_attributes())

        return element


class RoadCondition(VersionBase):
    """Weather creates an Weather element of openscenario

    Parameters
    ----------
        friction_scale_factor (float): scale factor of the friction

        properties (Properties): properties of the roadcondition
            Default: None

        wetness (Wetness): wetness of the road
            Default: None

    Attributes
    ----------
        friction_scale_factor (float): scale factor of the friction

        properties (Properties): properties of the roadcondition

        wetness (Wetness): wetness of the road

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, friction_scale_factor, properties=None, wetness=None):
        """initalize the Weather

        Parameters
        ----------
            friction_scale_factor (float): scale factor of the friction

            properties (Properties): properties of the roadcondition
                Default: None

            wetness (Wetness): wetness of the road
                Default: None
        """
        self.friction_scale_factor = convert_float(friction_scale_factor)
        if properties is not None and not isinstance(properties, Properties):
            raise TypeError("properties input is not of type Properties")
        self.properties = properties
        self.wetness = convert_enum(wetness, Wetness, True)

    def __eq__(self, other):
        if isinstance(other, RoadCondition):
            if (
                self.get_attributes() == other.get_attributes()
                and self.properties == other.properties
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of RoadCondition

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A road condition element (same as generated by the class itself)

        Returns
        -------
            roadcondition (RoadCondition): a RoadCondition object

        """
        friction_scale_factor = element.attrib["frictionScaleFactor"]

        properties = None
        wetness = None
        if element.find("Properties") != None:
            properties = Properties.parse(element.find("Properties"))
        if "wetness" in element.attrib:
            wetness = convert_enum(element.attrib["wetness"], Wetness, False)
        return RoadCondition(friction_scale_factor, properties, wetness)

    def get_attributes(self):
        """returns the attributes of the RoadCondition as a dict"""
        retdict = {"frictionScaleFactor": str(self.friction_scale_factor)}
        if self.wetness:
            retdict["wetness"] = self.wetness.get_name()
        return retdict

    def get_element(self):
        """returns the elementTree of the RoadCondition"""
        element = ET.Element("RoadCondition", attrib=self.get_attributes())
        if self.properties:
            element.append(self.properties.get_element())
        return element


# TODO: add name (string)
class Environment(_BaseCatalog):
    """The Environment class creates a environment used by Environment

    Parameters
    ----------
        name (string): Name of the environment. If used in catalog name is required.

        timeofday (TimeOfDay): time of day for the environment

        weather (Weather): weather of the environment

        roadcondition (RoadCondition): road condition of the environment

        parameters (ParameterDeclarations): the parameters to be used in the scenario
            Default: None

    Attributes
    ----------
        name (string): Name of the environment. If used in catalog name is required.

        timeofday (TimeOfDay): time of day for the environment

        weather (Weather): weather of the environment

        roadcondition (RoadCondition): road condition of the environment

        parameters (ParameterDeclarations): the parameters to be used in the scenario

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        append_to_catalog(filename)
            adds the vehicle to an existing catalog

        dump_to_catalog(filename,name,description,author)
            crates a new catalog with the vehicle

        get_element()
            Returns the full ElementTree of the class

    """

    def __init__(
        self, name, timeofday=None, weather=None, roadcondition=None, parameters=None
    ):
        """initalize the Environment

        Parameters
        ----------
            name (string): Name of the environment. If used in catalog name is required.

            timeofday (TimeOfDay): time of day for the environment

            weather (Weather): weather of the environment

            roadcondition (RoadCondition): road condition of the environment

            parameters (ParameterDeclarations): the parameters to be used in the scenario
                Default: None
        """
        super().__init__()
        self.name = name
        if timeofday is not None and not isinstance(timeofday, TimeOfDay):
            raise TypeError("timeofday input is not of type TimeOfDay")
        if weather is not None and not isinstance(weather, Weather):
            raise TypeError("weather input is not of type Weather")
        if roadcondition is not None and not isinstance(roadcondition, RoadCondition):
            raise TypeError("roadcondition input is not of type RoadCondition")
        if parameters is not None and not isinstance(parameters, ParameterDeclarations):
            raise TypeError("parameters input is not of type ParameterDeclarations")
        self.timeofday = timeofday
        self.weather = weather
        self.roadcondition = roadcondition
        if parameters is not None:
            self.parameters = parameters

    def __eq__(self, other):
        if isinstance(other, Environment):
            if (
                self.get_attributes() == other.get_attributes()
                and self.timeofday == other.timeofday
                and self.weather == other.weather
                and self.roadcondition == other.roadcondition
                and self.parameters == other.parameters
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Environment

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A environment element (same as generated by the class itself)

        Returns
        -------
            environment (Environment): a Environment object

        """
        name = element.attrib["name"]
        parameters = None
        weather = None
        timeofday = None
        roadcondition = None

        if element.find("ParameterDeclarations") != None:
            parameters = ParameterAssignment.parse(element.find("ParamterDeclarations"))
        if element.find("TimeOfDay") != None:
            timeofday = TimeOfDay.parse(element.find("TimeOfDay"))
        if element.find("Weather") != None:
            weather = Weather.parse(element.find("Weather"))
        if element.find("RoadCondition") != None:
            roadcondition = RoadCondition.parse(element.find("RoadCondition"))

        return Environment(name, timeofday, weather, roadcondition, parameters)

    def get_attributes(self):
        """returns the attributes of the Environment as a dict"""
        return {"name": str(self.name)}

    def get_element(self):
        """returns the elementTree of the Environment"""
        element = ET.Element("Environment", attrib=self.get_attributes())
        if self.timeofday:
            element.append(self.timeofday.get_element())
        if self.weather:
            element.append(self.weather.get_element())
        if self.roadcondition:
            element.append(self.roadcondition.get_element())
        self.add_parameters_to_element(element)
        return element


class Controller(_BaseCatalog):
    """the Controller class creates a controller of openScenario

    Parameters
    ----------
        name (str): name of the object

        properties (Properties): properties of the controller

        controller_type (ControllerType): controller type (valid from V1.2)
            Default: None

    Attributes
    ----------
        parameters (ParameterDeclaration): Parameter declarations of the vehicle

        properties (Properties): additional properties of the vehicle

        controller_type (ControllerType): controller type
    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        add_parameter(parameter)
            adds a parameter declaration to the Controller

        append_to_catalog(filename)
            adds the vehicle to an existing catalog

        dump_to_catalog(filename,name,description,author)
            crates a new catalog with the vehicle

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, name, properties, controller_type=None):
        """initalzie the Controller Class

        Parameters
        ----------
            name (str): name of the object

            properties (Properties): properties of the Controller

            controller_type (ControllerType): controller type (valid from V1.2)
                Default: None
        """
        super().__init__()
        self.name = name

        if not isinstance(properties, Properties):
            raise TypeError("properties input is not of type Properties")
        self.properties = properties
        self.controller_type = convert_enum(controller_type, ControllerType, True)

    def __eq__(self, other):
        if isinstance(other, Controller):
            if (
                self.properties == other.properties
                and self.parameters == other.parameters
                and self.name == other.name
                and self.controller_type == other.controller_type
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Controller

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A controller element (same as generated by the class itself)

        Returns
        -------
            controller (Controller): a Controller object

        """
        name = element.attrib["name"]
        properties_element = element.find("Properties")
        properties = Properties.parse(properties_element)
        cnt_type = None
        if "controllerType" in element.attrib:
            cnt_type = convert_enum(
                element.attrib["controllerType"], ControllerType, False
            )
        controller = Controller(name, properties, cnt_type)

        parameters_element = element.find("ParameterDeclarations")
        if parameters_element:
            controller.parameters = ParameterDeclarations.parse(parameters_element)

        return controller

    def get_attributes(self):
        """returns the attributes of the Controller as a dict"""
        retdict = {"name": self.name}
        if self.controller_type:
            if self.isVersion(minor=2):
                retdict["controllerType"] = self.controller_type.get_name()
            else:
                raise OpenSCENARIOVersionError(
                    "controllerType was introduced in OSC v1.2"
                )

        return retdict

    def get_element(self):
        """returns the elementTree of the Controller"""
        element = ET.Element("Controller", attrib=self.get_attributes())
        self.add_parameters_to_element(element)
        element.append(self.properties.get_element())

        return element


class BoundingBox(VersionBase):
    """the Dimensions describes the size of an entity

    Parameters
    ----------
        width (float): the width of the entity

        length (float): the lenght of the entity

        height (float): the height of the entity

        x_center (float): x distance from back axel to center

        y_center (float): y distance from back axel to clas

        z_center (float): z distance from back axel to center


    Attributes
    ----------
        dimensions (Dimensions): the dimensions of the entity

        center (Center): the center of the object relative the the back axel

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class itself


    """

    def __init__(self, width, length, height, x_center, y_center, z_center):
        """initalzie the Dimensions

        Parameters
        ----------
            width (float): the width of the entity

            length (float): the lenght of the entity

            height (float): the height of the entity

            x_center (float): x distance from back axel to center

            y_center (float): y distance from back axel to center

            z_center (float): z distance from back axel to center

        """
        self.boundingbox = Dimensions(width, length, height)
        self.center = Center(x_center, y_center, z_center)

    def __eq__(self, other):
        if isinstance(other, BoundingBox):
            if self.boundingbox == other.boundingbox and self.center == other.center:
                return True
        return False

    def get_element(self):
        """returns the elementTree of the Dimensions"""
        element = ET.Element("BoundingBox")
        element.append(self.center.get_element())
        element.append(self.boundingbox.get_element())
        return element

    @staticmethod
    def parse(element):
        """Parses the xml element of BoundingBox

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A orientation element (same as generated by the class itself)

        Returns
        -------
            boundingBox (BoundingBox): a BoundingBox object

        """
        center = Center.parse(element.find("Center"))
        cen_dict = center.get_attributes()
        dimension = Dimensions.parse(element.find("Dimensions"))
        dim_dict = dimension.get_attributes()
        return BoundingBox(
            dim_dict["width"],
            dim_dict["length"],
            dim_dict["height"],
            cen_dict["x"],
            cen_dict["y"],
            cen_dict["z"],
        )


class Center(VersionBase):
    """the Center Class creates a centerpoint for a bounding box, reference point of a vehicle is the back axel

    Parameters
    ----------
        x (float): x distance from back axel to center

        y (float): y distance from back axel to center

        z (float): z distance from back axel to center


    Attributes
    ----------
        x (float): x distance from back axel to center

        y (float): y distance from back axel to center

        z (float): z distance from back axel to center

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class itself

    """

    def __init__(self, x, y, z):
        """initalzie the Center Class

        Parameters
        ----------
            x (float): x distance from back axel to center

            y (float): y distance from back axel to center

            z (float): z distance from back axel to center

        """
        self.x = convert_float(x)
        self.y = convert_float(y)
        self.z = convert_float(z)

    @staticmethod
    def parse(element):
        """Parses the xml element to Center

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A center element (same as generated by the class itself)

        Returns
        ------
            center (Center): a Center object

        """
        x = convert_float(element.attrib["x"])
        y = convert_float(element.attrib["y"])
        z = convert_float(element.attrib["z"])
        return Center(x, y, z)

    def __eq__(self, other):
        if isinstance(other, Center):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    def get_attributes(self):
        """returns the attributes as a dict of the Center"""
        return {"x": str(self.x), "y": str(self.y), "z": str(self.z)}

    def get_element(self):
        """returns the elementTree of the Center"""
        element = ET.Element("Center", attrib=self.get_attributes())
        return element


class Dimensions(VersionBase):
    """the Dimensions describes the size of an entity

    Parameters
    ----------
        width (float): the width of the entity

        length (float): the lenght of the entity

        height (float): the height of the entity


    Attributes
    ----------
        width (float): the width of the entity

        length (float): the lenght of the entity

        height (float): the height of the entity

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class itself

    """

    def __init__(self, width, length, height):
        """initalzie the Dimensions

        Parameters
        ----------
            width (float): the width of the entity

            length (float): the lenght of the entity

            height (float): the height of the entity

        """
        self.width = convert_float(width)
        self.length = convert_float(length)
        self.height = convert_float(height)

    @staticmethod
    def parse(element):
        """Parses the xml element to Dimensions

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A MiscObject element (same as generated by the class itself)

        Returns
        ------
            dimension (Dimensions): a Dimensions object

        """
        width = convert_float(element.attrib["width"])
        height = convert_float(element.attrib["height"])
        length = convert_float(element.attrib["length"])
        return Dimensions(width, length, height)

    def __eq__(self, other):
        if isinstance(other, Dimensions):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    def get_attributes(self):
        """returns the attributes as a dict of the Dimensions"""
        return {
            "width": str(self.width),
            "length": str(self.length),
            "height": str(self.height),
        }

    def get_element(self):
        """returns the elementTree of the Dimensions"""
        element = ET.Element("Dimensions", attrib=self.get_attributes())
        return element


class Properties(VersionBase):
    """the Properties contains are for user defined properties of an object

    Attributes
    ----------
        files (list of str): arbitrary files with properties

        properties (list of tuple(str,str)): properties in name/value pairs

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        add_file(file)
            adds a file with properties

        add_property(name,value)
            adds a property pair, with name and value

        get_element()
            Returns the full ElementTree of the class


    """

    def __init__(self):
        """initalzie the Properties"""
        self.files = []
        self.properties = []

    def __eq__(self, other):
        if isinstance(other, Properties):
            if self.files == other.files and self.properties == other.properties:
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of class Properties:


        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A position element (same as generated by the class itself)

        Returns
        -------
            properties (Properties): a Properties object

        """
        properties = Properties()
        files = element.findall("File")
        if files != None:
            for file in files:
                filepath = file.attrib["filepath"]
                properties.add_file(filepath)
        props = element.findall("Property")
        if props != None:
            for property in props:
                name = property.attrib["name"]
                value = property.attrib["value"]
                properties.add_property(name, value)

        return properties

    def add_file(self, filename):
        """adds a property file

        Parameters
        ----------
            filename (str): name of the file

        """

        self.files.append(filename)
        return self

    def add_property(self, name, value):
        """adds a property pair

        Parameters
        ----------
            name (str): name of the property

            value (str): value of the property

        """
        self.properties.append((name, value))
        return self

    def get_element(self):
        """returns the elementTree of the Properties"""
        element = ET.Element("Properties")
        for p in self.properties:
            ET.SubElement(element, "Property", attrib={"name": p[0], "value": p[1]})
        for f in self.files:
            ET.SubElement(element, "File", attrib={"filepath": f})

        return element


class AbsoluteSpeed(VersionBase):
    """
    Parameters
    ----------
        value (float): absolute speed [m/s]

        steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Final phase of constant (final) speed, start of which defined by distance or time. (Valid from OpenSCENARIO V1.1)

    Attributes
    ----------
        value (float): absolute speed [m/s]

        steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Final phase of constant (final) speed, start of which defined by distance or time. (Valid from OpenSCENARIO V1.1)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns the attributes of the class
    """

    def __init__(self, value, steadyState=None):
        """initalzie the AbsoluteSpeed

        Parameters
        ----------
            value (float): absolute speed [m/s]
            steadyState (TargetTimeSteadyState / TargetDistanceSteadyState) Final phase of constant (final) speed, start of which defined by distance or time. (Valid from OpenSCENARIO V1.1)
        """
        self.value = value
        if steadyState:
            if not (
                isinstance(steadyState, TargetTimeSteadyState)
                or isinstance(steadyState, TargetDistanceSteadyState)
            ):
                raise TypeError(
                    "steadyState input is not an TargetTimeSteadyState or TargetDistanceSteadyState input"
                )
        self.steadyState = steadyState

    def __eq__(self, other):
        if isinstance(other, AbsoluteSpeed):
            if (
                self.get_attributes() == other.get_attributes()
                and self.steadyState == other.steadyState
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of AbsoluteSpeed

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A absolute speed element (same as generated by the class itself)

        Returns
        -------
            absolutespeed (AbsoluteSpeed): a AbsoluteSpeed object

        """
        absolute_speed_element = element.find("AbsoluteSpeed")
        value = absolute_speed_element.attrib["value"]

        state = None
        if absolute_speed_element.find("TargetDistanceSteadyState") != None:
            state = TargetDistanceSteadyState.parse(
                absolute_speed_element.find("TargetDistanceSteadyState")
            )
        elif absolute_speed_element.find("TargetTimeSteadyState") != None:
            state = TargetTimeSteadyState.parse(
                absolute_speed_element.find("TargetTimeSteadyState")
            )

        return AbsoluteSpeed(value, state)

    def get_attributes(self):
        """returns the attributes of the AbsoluteSpeed"""
        return {"value": str(self.value)}

    def get_element(self):
        """returns the elementTree of the AbsoluteSpeed"""

        elementFinalSpeed = ET.Element("FinalSpeed")
        elementAbsoluteSpeed = ET.SubElement(
            elementFinalSpeed, "AbsoluteSpeed", attrib=self.get_attributes()
        )
        if self.steadyState:
            if self.isVersion(minor=0):
                raise OpenSCENARIOVersionError(
                    "steadyState was introduced in OpenSCENARIO V1.1"
                )
            ET.SubElement(
                elementAbsoluteSpeed,
                self.steadyState.__class__.__name__,
                attrib=self.steadyState.get_attributes(),
            )

        return elementFinalSpeed


class RelativeSpeedToMaster(VersionBase):
    """
    Parameters
    ----------
        value (float): Relative speed. Unit: m/s.

        speedTargetValueType (SpeedTargetValueType): The semantics of the value (delta, offset, factor).

        steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Optional final phase of constant (final) speed. (Valid from OpenSCENARIO V1.1)

    Attributes
    ----------
        value (float): Relative speed. Unit: m/s.

        speedTargetValueType (SpeedTargetValueType): The semantics of the value (delta, offset, factor).

        steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Optional final phase of constant (final) speed. (Valid from OpenSCENARIO V1.1)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class itself

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns the attributes of the class
    """

    def __init__(self, value, speedTargetValueType, steadyState=None):
        """

        Parameters
        ----------
            value (float): Relative speed. Unit: m/s.

            speedTargetValueType (SpeedTargetValueType): The semantics of the value (delta, offset, factor).

            steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Optional final phase of constant (final) speed.
        """
        self.value = value
        if steadyState:
            if not (
                isinstance(steadyState, TargetTimeSteadyState)
                or isinstance(steadyState, TargetDistanceSteadyState)
            ):
                raise TypeError(
                    "steadyState input is not an TargetTimeSteadyState or TargetDistanceSteadyState input"
                )
        self.steadyState = steadyState
        self.speedTargetValueType = convert_enum(
            speedTargetValueType, SpeedTargetValueType
        )

    def __eq__(self, other):
        if isinstance(other, RelativeSpeedToMaster):
            if (
                self.get_attributes() == other.get_attributes()
                and self.steadyState == other.steadyState
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element to RelativeSpeedToMaster

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A RelativeSpeedToMaster element (same as generated by the class itself)

        Returns
        ------
            rstm (RelativeSpeedToMaster): a RelativeSpeedToMaster object

        """
        speed_element = element.find("RelativeSpeedToMaster")

        value = speed_element.attrib["value"]
        speedTargetValueType = convert_enum(
            speed_element.attrib["speedTargetValueType"], SpeedTargetValueType
        )
        state = None
        if speed_element.find("TargetDistanceSteadyState") != None:
            state = TargetDistanceSteadyState.parse(
                speed_element.find("TargetDistanceSteadyState")
            )
        elif speed_element.find("TargetTimeSteadyState") != None:
            state = TargetTimeSteadyState.parse(
                speed_element.find("TargetTimeSteadyState")
            )

        return RelativeSpeedToMaster(value, speedTargetValueType, state)

    def get_attributes(self):
        """returns the attributes of the RelativeSpeedToMaster"""
        return {
            "speedTargetValueType": str(self.speedTargetValueType),
            "value": str(self.value),
        }

    def get_element(self):
        """returns the elementTree of the RelativeSpeedToMaster"""
        elementFinalSpeed = ET.Element("FinalSpeed")
        elementRelativeSpeed = ET.SubElement(
            elementFinalSpeed, "RelativeSpeedToMaster", attrib=self.get_attributes()
        )
        if self.steadyState:
            if self.isVersion(minor=0):
                raise OpenSCENARIOVersionError(
                    "steadyState was introduced in OpenSCENARIO V1.1"
                )
            ET.SubElement(
                elementRelativeSpeed,
                self.steadyState.__class__.__name__,
                attrib=self.steadyState.get_attributes(),
            )
        return elementFinalSpeed


class TargetDistanceSteadyState(VersionBase):
    """the TargetDistanceSteadyState describes a SteadyState of type TargetDistanceSteadyState
    (Valid from OpenSCENARIO V1.1)

    Parameters
    ----------
        distance (float): distance to target for the steady state

    Attributes
    ----------
        distance (float): distance to target for the steady state

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

    """

    def __init__(self, distance):
        """initalzie the TargetDistanceSteadyState

        Parameters
        ----------
            distance (float): distance to target for the steady state

        """
        self.distance = distance

    def __eq__(self, other):
        if isinstance(other, TargetDistanceSteadyState):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TargetDistanceSteadyState

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A TargetDistanceSteadyState element (same as generated by the class itself)

        Returns
        -------
            tdss (TargetDistanceSteadyState): a TargetDistanceSteadyState object

        """
        distance = element.attrib["distance"]
        return TargetDistanceSteadyState(distance)

    def get_attributes(self):
        """returns the attributes of the TargetDistanceSteadyState"""
        if self.isVersion(1, 0):
            raise OpenSCENARIOVersionError(
                "TargetDistanceSteadyState was introduced in OpenSCENARIO V1.1"
            )
        return {"distance": str(self.distance)}

    def get_element(self):
        """returns the elementTree of the TargetDistanceSteadyState"""
        if self.isVersion(1, 0):
            raise OpenSCENARIOVersionError(
                "TargetDistanceSteadyState was introduced in OpenSCENARIO V1.1"
            )
        return ET.Element("TargetDistanceSteadyState", attrib=self.get_attributes())


class TargetTimeSteadyState(VersionBase):
    """the TargetTimeSteadyState describes a SteadyState of type TargetTimeSteadyState
    (Valid from OpenSCENARIO V1.1)

    Parameters
    ----------
        time_gap (float): time_gap to target for the steady state

    Attributes
    ----------
        time_gap (float): time_gap to target for the steady state

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

    """

    def __init__(self, time_gap):
        """initalzie the TargetTimeSteadyState

        Parameters
        ----------
            time_gap (float): time_gap to target for the steady state

        """
        self.time_gap = time_gap

    def __eq__(self, other):
        if isinstance(other, TargetTimeSteadyState):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TargetTimeSteadyState

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A TargetTimeSteadyState element (same as generated by the class itself)

        Returns
        -------
            ttss (TargetTimeSteadyState): a TargetTimeSteadyState object

        """
        time = element.attrib["time"]
        return TargetTimeSteadyState(time)

    def get_attributes(self):
        """returns the attributes of the TargetTimeSteadyState"""
        if self.isVersion(1, 0):
            raise OpenSCENARIOVersionError(
                "TargetTimeSteadyState was introduced in OpenSCENARIO V1.1"
            )
        return {"time": str(self.time_gap)}

    def get_element(self):
        """returns the elementTree of the TargetTimeSteadyState"""
        if self.isVersion(1, 0):
            raise OpenSCENARIOVersionError(
                "TargetTimeSteadyState was introduced in OpenSCENARIO V1.1"
            )
        return ET.Element("TargetTimeSteadyState", attrib=self.get_attributes())


def merge_dicts(*dict_args):
    """Funciton to merge dicts"""
    retdict = {}
    for d in dict_args:
        retdict.update(d)

    return retdict


def convert_bool(value):
    """Method to transform booleans to correct xml version (lower case)

    Parameter
    ---------
        value (bool): the boolean

    Return
    ------
        boolean (str)
    """
    if isinstance(value, str):
        if value == "true" or value == "1":
            return True
        elif value == "false" or value == "0":
            return False
        elif value[0] == "$":
            return value
        else:
            raise ValueError(
                value
                + "is not a valid type of boolean input to openscenario, if a string is used as a boolean value (parameter or expression), it should have a $ as the first char.."
            )

    if value:
        return True
    elif value == None:
        return None
    else:
        return False


def get_bool_string(value):
    if isinstance(value, str) and value[0] == "$":
        return value
    elif value:
        return "true"
    else:
        return "false"


def convert_enum(value, enumtype, none_ok=False):
    if isinstance(value, _OscEnum):
        if hasattr(enumtype, str(value)) or "$" == str(value)[0]:
            return value
        else:
            raise TypeError(
                value.get_name() + " is not of Enumeration type :" + str(enumtype)
            )
    elif isinstance(value, str):
        if hasattr(enumtype, value):
            return _OscEnum(enumtype.__name__, value)
        elif "$" == value[0]:
            return _OscEnum(enumtype.__name__, value)
        else:
            raise ValueError(
                value
                + " is not a valid string input for Enumeration type "
                + str(enumtype)
            )
    elif value == None:
        if none_ok:
            return None
        else:
            raise TypeError("None value not a valid option for: " + str(enumtype))

    raise TypeError(str(value) + " is not of a valid enumeration or str type.")


def convert_float(value):
    """Method to ensure floats are floats, will take care of None values aswell

    Parameter
    ---------
        value (float/str/int/None): a value to transform to float

    Return
    ------
        value (float/None)
    """
    if isinstance(value, str):
        if value[0] == "$":
            return value
        try:
            float(value)
        except ValueError:
            raise ValueError(
                value
                + "is not a valid type of float input to openscenario, if a string is used as a float value (parameter or expression), it should have a $ as the first char.."
            )

    if value is not None:
        return float(value)
    else:
        return None


def convert_int(value):
    """Method to ensure ints are ints, will take care of None values aswell

    Parameter
    ---------
        value (float/str/int/None): a value to transform to int

    Return
    ------
        value (int/None)
    """
    if isinstance(value, str):
        if value[0] == "$":
            return value
        try:
            int(value)
        except ValueError:
            raise ValueError(
                value
                + "is not a valid type of int input to openscenario, if a string is used as a int value (parameter or expression), it should have a $ as the first char."
            )

    if value is not None:
        return int(value)
    else:
        return None


class ValueConstraintGroup(VersionBase):
    """Creates the the ValueConstraintGroup file for open scenario

    Parameters
    ----------
        None

    Attributes
    ----------
        value_constraint (ValueConstraint): logical constraint, needed to evaluate to true for a defined parameter to start the simulation.


    Methods
    -------
        add_value_constraint(value_constraint)
            adds value constraint to the value constraint group

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    def __init__(self):
        self.value_constraints = []

    def __eq__(self, other):
        if isinstance(other, ValueConstraintGroup):
            if self.value_constraints == other.value_constraints:
                return True
        return False

    def add_value_constraint(self, value_constraint):
        """adds a value constraint to the value constraint group

        Parameters
        ----------
            value_constraint (ValueConstraint): the value constraint to be added

        """
        if not isinstance(value_constraint, ValueConstraint):
            raise TypeError("value_conatraint input is not of type ValueConstraint")
        self.value_constraints.append(value_constraint)
        return self

    @staticmethod
    def parse(element):
        """Parses the xml element of ValueConstraintGroup

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A ValueConstraintGroup element (same as generated by the class itself)

        Returns
        -------
            group (ValueConstraintGroup): a ValueConstraintGroup object

        """
        value_constraints = ValueConstraintGroup()
        constraints = element.findall("ValueConstraint")
        for constraint in constraints:
            value_constraint = ValueConstraint.parse(constraint)
            value_constraints.add_value_constraint(value_constraint)
        return value_constraints

    def get_element(self):
        """returns the elementTree of the ValueConstraintGroup"""
        if self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "ValueConstraintGroup was introduced in OpenSCENARIO V1.1"
            )
        element = ET.Element("ConstraintGroup")
        if not self.value_constraints:
            raise ValueError("No Value Constraints in the Value Contraint Group")
        for value_constraint in self.value_constraints:
            element.append(value_constraint.get_element())
        return element


class ValueConstraint(VersionBase):
    """Creates the the ValueConstraint file for open scenario

    Parameters
    ----------
        rule (Rule): available operators for the validation of the constraint. Note that either "equalTo" or "notEqualTo" must be used in the parameter declaration of type "string"

        value (string): a constant value, parameter or parameter expression. The value must match the enclosing parameter declaration.

    Attributes
    ----------
        rule (Rule): available operators for the validation of the constraint. Note that either "equalTo" or "notEqualTo" must be used in the parameter declaration of type "string"

        value (string): a constant value, parameter or parameter expression. The value must match the enclosing parameter declaration.


    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    # TODO: Only equalTo and notEqualTo test
    def __init__(self, rule, value):
        """initalzie the ValueConstraint Class

        Parameters
        ----------
            rule (Rule): available operators for the validation of the constraint. Note that either "equalTo" or "notEqualTo" must be used in the parameter declaration of type "string"

            value (string): a constant value, parameter or parameter expression. The value must match the enclosing parameter declaration.
        """
        self.value = value
        self.rule = convert_enum(rule, Rule)

    def __eq__(self, other):
        if isinstance(other, ValueConstraint):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of ValueConstraint

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

        Returns
        -------
            constraint (ValueConstraint): ValueConstraint object

        """
        value = element.attrib["value"]
        rule = convert_enum(element.attrib["rule"], Rule)
        return ValueConstraint(rule, value)

    def get_attributes(self):
        """returns the attributes of the ValueConstraint as a dict"""
        retdict = {}
        retdict["rule"] = self.rule.get_name()
        retdict["value"] = str(self.value)
        return retdict

    def get_element(self):
        """returns the elementTree of the ValueConstraint"""
        if self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "ValueConstraint was introduced in OpenSCENARIO V1.1"
            )
        element = ET.Element("ValueConstraint", attrib=self.get_attributes())
        return element


class _ColorDefinition(VersionBase):
    """color definition used only for inheritance"""


class ColorRGB(_ColorDefinition):
    """Creates the RGB Color element in OpenSCENARIO

    Parameters
    ----------
        red (float): red component (0..1)
            Default: 0

        green (float): green component (0..1)
            Default: 0

        blue (float): blue component (0..1)
            Default: 0


    Attributes
    ----------
        red (float): red component (0..1)

        green (float): green component (0..1)

        blue (float): blue component (0..1)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, red=0, green=0, blue=0):
        """initalzie the ColorRGB Class

        Parameters
        ----------
            red (float): red component (0..1)
                Default: 0

            green (float): green component (0..1)
                Default: 0

            blue (float): blue component (0..1)
                Default: 0
        """
        self.red = red
        self.green = green
        self.blue = blue

    def __eq__(self, other):
        if isinstance(other, ColorRGB):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of ColorRGB

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

        Returns
        -------
            color (ColorRGB): ColorRGB object

        """

        red = element.attrib["red"]
        green = element.attrib["green"]
        blue = element.attrib["blue"]
        return ColorRGB(red, green, blue)

    def get_attributes(self):
        """returns the attributes of the ValueConstraint as a dict"""
        retdict = {}
        retdict["red"] = str(self.red)
        retdict["green"] = str(self.green)
        retdict["blue"] = str(self.blue)
        return retdict

    def get_element(self):
        """returns the elementTree of the ValueConstraint"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "ColorRGB was introduced in OpenSCENARIO V1.2"
            )
        element = ET.Element("ColorRgb", attrib=self.get_attributes())
        return element


class ColorCMYK(_ColorDefinition):
    """Creates the CMYK Color element in OpenSCENARIO

    Parameters
    ----------
        cyan (float): cyan component (0..1)
            Default: 0

        magenta (float): magenta component (0..1)
            Default: 0

        yellow (float): yellow component (0..1)
            Default: 0

        key (float): black component (0..1)
            Default: 0

    Attributes
    ----------
        cyan (float): cyan component (0..1)

        magenta (float): magenta component (0..1)

        yellow (float): yellow component (0..1)

        key (float): black component (0..1)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, cyan=0, magenta=0, yellow=0, key=0):
        """initalzie the ColorCMYK Class

        Parameters
        ----------
            cyan (float): cyan component (0..1)
                Default: 0

            magenta (float): magenta component (0..1)
                Default: 0

            yellow (float): yellow component (0..1)
                Default: 0

            key (float): black component (0..1)
                Default: 0
        """
        self.cyan = cyan
        self.magenta = magenta
        self.yellow = yellow
        self.key = key

    def __eq__(self, other):
        if isinstance(other, ColorCMYK):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of ColorCMYK

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

        Returns
        -------
            color (ColorCMYK): ColorCMYK object

        """

        cyan = element.attrib["cyan"]
        magenta = element.attrib["magenta"]
        yellow = element.attrib["yellow"]
        key = element.attrib["key"]
        return ColorCMYK(cyan, magenta, yellow, key)

    def get_attributes(self):
        """returns the attributes of the ColorCMYK as a dict"""
        retdict = {}
        retdict["cyan"] = str(self.cyan)
        retdict["magenta"] = str(self.magenta)
        retdict["yellow"] = str(self.yellow)
        retdict["key"] = str(self.key)
        return retdict

    def get_element(self):
        """returns the elementTree of the ColorCMYK"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "ColorCMYK was introduced in OpenSCENARIO V1.2"
            )
        element = ET.Element("ColorCmyk", attrib=self.get_attributes())
        return element


class Color(VersionBase):
    """Creates the Color element in OpenSCENARIO

    Parameters
    ----------
        color_type (ColorType): semantic value of color

        color_definition (_ColorDefinition): the color definition

    Attributes
    ----------
        color_type (ColorType): semantic value of color

        color_definition (_ColorDefinition): the color definition

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, color_type, color_definition):
        """initalzie the Color Class

        Parameters
        ----------
            color_type (ColorType): semantic value of color

            color_definition (ColorRGB or ColorCmyk): the color definition

        """
        self.color_type = convert_enum(color_type, ColorType, False)
        if not isinstance(color_definition, _ColorDefinition):
            raise TypeError("input is not a color definition")
        self.color_definition = color_definition

    def __eq__(self, other):
        if isinstance(other, Color):
            if (
                self.get_attributes() == other.get_attributes()
                and self.color_definition == other.color_definition
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Color

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

        Returns
        -------
            color (Color): Color object

        """

        color_type = convert_enum(element.attrib["colorType"], ColorType)
        if element.find("ColorRgb") is not None:
            color_def = ColorRGB.parse(element.find("ColorRgb"))
        elif element.find("ColorCmyk") is not None:
            color_def = ColorCMYK.parse(element.find("ColorCmyk"))
        return Color(color_type, color_def)

    def get_attributes(self):
        """returns the attributes of the Color as a dict"""
        retdict = {}
        retdict["colorType"] = self.color_type.get_name()
        return retdict

    def get_element(self):
        """returns the elementTree of the Color"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError("Color was introduced in OpenSCENARIO V1.2")
        element = ET.Element("Color", attrib=self.get_attributes())
        element.append(self.color_definition.get_element())
        return element


class UserDefinedLight(VersionBase):
    """The CustomCommandAction creates a simulator defined action


    Parameters
    ----------
        user_defined_type (str): string of the user defined light

    Attributes
    ----------

        type (str): type of the custom command

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

    """

    def __init__(self, user_defined_type):
        """initalize the UserDefinedLight

        Parameters
        ----------
            user_defined_type (str): type of the custom command

        """
        self.type = user_defined_type

    def __eq__(self, other):
        if isinstance(other, UserDefinedLight):
            if other.type == self.type:
                return True
        return False

    @staticmethod
    def parse(element):
        """Parsese the xml element of a UserDefinedLight

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a UserDefinedLight element

        Returns
        -------
            UserDefinedLight (UserDefinedLight): a UserDefinedLight object

        """

        return UserDefinedLight(element.attrib["userDefinedLightType"])

    def get_element(self):
        """returns the elementTree of the UserDefinedLight"""
        if self.isVersionEqLess(minor=1):
            raise OpenSCENARIOVersionError("UserDefinedLight was introduced in OSC 1.2")
        element = ET.Element(
            "UserDefinedLight", attrib={"userDefinedLightType": self.type}
        )
        return element


class _LightState(VersionBase):
    """The _LightState creates a LightState element used by LightStateAction

    Parameters
    ----------
        mode (LightMode): the new mode of the light

        color (Color): the color of the light

        intensity (float): the luminous intensity of the light

        flashing_on_duration (float): how long the light should be on when when LightMode is set to "flashing"

        flashing_off_duration (float): how long the light should be off when LightMode is set to "flashing"

    Attributes
    ----------

        type (str): type of the custom command

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(
        self,
        mode,
        color=None,
        intensity=None,
        flashing_off_duration=None,
        flashing_on_duration=None,
    ):
        """initalize the _LightState

        Parameters
        ----------
            user_defined_type (str): type of the custom command

        """
        if color and not isinstance(color, Color):
            raise TypeError("color input is not of type Color")
        self.mode = convert_enum(mode, LightMode)
        self.color = color

        self.intensity = convert_float(intensity)
        self.flash_on_duration = convert_float(flashing_on_duration)
        self.flash_off_duration = convert_float(flashing_off_duration)

        if flashing_on_duration == None and self.mode == LightMode.flashing:
            self.flash_on_duration = 0.5

        if flashing_off_duration == None and self.mode == LightMode.flashing:
            self.flash_off_duration = 0.5

    def __eq__(self, other):
        if isinstance(other, _LightState):
            if (
                other.get_attributes() == self.get_attributes()
                and other.color == self.color
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parsese the xml element of a _LightState

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a _LightState element

        Returns
        -------
            LightState (_LightState): a _LightState object

        """
        flashing_on = None
        flashing_off = None
        intensity = None
        color = None

        if "flashingOnDuration" in element.attrib:
            flashing_on = element.attrib["flashingOnDuration"]

        if "flashingOffDuration" in element.attrib:
            flashing_off = element.attrib["flashingOffDuration"]

        if "luminousIntensity" in element.attrib:
            intensity = convert_float(element.attrib["luminousIntensity"])

        if element.find("Color") != None:
            color = Color.parse(element.find("Color"))
        mode = convert_enum(element.attrib["mode"], LightMode)
        return _LightState(mode, color, intensity, flashing_off, flashing_on)

    def get_attributes(self):
        """returns the attributes of the ValueConstraint as a dict"""
        retdict = {}

        if self.flash_on_duration is not None:
            retdict["flashingOnDuration"] = str(self.flash_on_duration)
        if self.flash_off_duration is not None:
            retdict["flashingOffDuration"] = str(self.flash_off_duration)
        if self.intensity is not None:
            retdict["luminousIntensity"] = str(self.intensity)

        retdict["mode"] = self.mode.get_name()
        return retdict

    def get_element(self):
        """returns the elementTree of the _LightState"""
        element = ET.Element("LightState", attrib=self.get_attributes())
        if self.color:
            element.append(self.color.get_element())
        return element


class AnimationFile(_AnimationType):
    """The AnimationFile creates a AnimationFile element used by AnimationType

    Parameters
    ----------
        file (string): filepath of the annimation / motion file

        timeOffset (float): time offset from beginning of animation

    Attributes
    ----------

        timeOffset (float): time offset from beginning of animation

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, file, timeOffset=None):
        """initalizes the AnimationFile

        Parameters
        ----------
        file (string): filepath of the annimation / motion file

        timeOffset (float): time offset from beginning of animation

        """
        self.file = file
        self.timeOffset = convert_float(timeOffset)

    def __eq__(self, other):
        if isinstance(other, AnimationFile):
            if (
                other.get_attributes() == self.get_attributes()
                and other.file == self.file
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of a AnimationFile

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a AnimationFile element

        Returns
        -------
            AnimationFile (AnimationFile): a AnimationFile object

        """

        timeOffset = None
        if element.find("File") is not None:
            file = element.find("File").attrib["filepath"]
        if "timeOffset" in element.attrib:
            timeOffset = convert_float(element.attrib["timeOffset"])
        return AnimationFile(file, timeOffset)

    def get_attributes(self):
        """returns the attributes of the AnimationFile as a dict"""
        retdict = {}
        if self.timeOffset is not None:
            retdict["timeOffset"] = str(self.timeOffset)
        return retdict

    def get_element(self):
        """returns the elementTree of the AnimationFile"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "AnimationFile was introduced in OpenSCENARIO V1.2"
            )

        element = ET.Element("AnimationFile", attrib=self.get_attributes())
        if self.file:
            ET.SubElement(element, "File", {"filepath": self.file})
        return element


class DirectionOfTravelDistribution(VersionBase):
    """The DirectionOfTravelDistribution is used by SwarmTraffic to define how the traffic should flow

    Parameters
    ----------
        opposite (float): weight of traffic going against the reference entity

        same (float): weight of traffic going the same way the reference entity

    Attributes
    ----------

        opposite (float): weight of traffic going against the reference entity

        same (float): weight of traffic going the same way the reference entity

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, opposite, same):
        """initalizes the DirectionOfTravelDistribution

        Parameters
        ----------
        opposite (float): weight of traffic going against the reference entity

        same (float): weight of traffic going the same way the reference entity

        """
        self.opposite = convert_float(opposite)
        self.same = convert_float(same)

    def __eq__(self, other):
        if isinstance(other, DirectionOfTravelDistribution):
            if other.get_attributes() == self.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of a DirectionOfTravelDistribution

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a DirectionOfTravelDistribution element

        Returns
        -------
            DirectionOfTravelDistribution (DirectionOfTravelDistribution): a DirectionOfTravelDistribution object

        """

        return DirectionOfTravelDistribution(
            convert_float(element.attrib["opposite"]),
            convert_float(element.attrib["same"]),
        )

    def get_attributes(self):
        """returns the attributes of the DirectionOfTravelDistribution as a dict"""
        retdict = {"opposite": str(self.opposite), "same": str(self.same)}
        return retdict

    def get_element(self):
        """returns the elementTree of the DirectionOfTravelDistribution"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "DirectionOfTravelDistribution was introduced in OpenSCENARIO V1.2"
            )

        element = ET.Element(
            "DirectionOfTravelDistribution", attrib=self.get_attributes()
        )
        return element


class UserDefinedAnimation(_AnimationType):
    """The UserDefinedAnimation creates a UserDefinedAnimation element used by AnimationType

    Parameters
    ----------
        userDefinedAnimationType (str): the available user defined animation types are subject of a contract between simulation environment provider and scenario author.

    Attributes
    ----------

        userDefinedAnimationType (str): the available user defined animation types are subject of a contract between simulation environment provider and scenario author.

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, type):
        """initalizes the UserDefinedAnimation

        Parameters
        ----------
        userDefinedAnimationType (str): the available user defined animation types are subject of a contract between simulation environment provider and scenario author.

        """
        self.type = type

    def __eq__(self, other):
        if isinstance(other, UserDefinedAnimation):
            if other.get_attributes() == self.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of a UserDefinedAnimation

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a UserDefinedAnimation element

        Returns
        -------
            UserDefinedAnimation (UserDefinedAnimation): a UserDefinedAnimation object

        """

        return UserDefinedAnimation(element.attrib["userDefinedAnimationType"])

    def get_attributes(self):
        """returns the attributes of the UserDefinedAnimation as a dict"""
        retdict = {}
        retdict["userDefinedAnimationType"] = self.type
        return retdict

    def get_element(self):
        """returns the elementTree of the UserDefinedAnimation"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "UserDefinedAnimation was introduced in OpenSCENARIO V1.2"
            )

        element = ET.Element("UserDefinedAnimation", attrib=self.get_attributes())
        return element


class UserDefinedComponent(_AnimationType):
    """The UserDefinedComponent creates a UserDefinedComponent as part of a ComponentAnimation

    Parameters
    ----------
        userDefinedComponentType (str): User defined component type.

    Attributes
    ----------

        userDefinedComponentType (str): User defined component type.

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, type):
        """initalizes the UserDefinedComponent

        Parameters
        ----------
        userDefinedComponentType (str): User defined component type.

        """
        self.type = type

    def __eq__(self, other):
        if isinstance(other, UserDefinedComponent):
            if other.get_attributes() == self.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of a UserDefinedComponent

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a UserDefinedComponent element

        Returns
        -------
            UserDefinedComponent (UserDefinedComponent): a UserDefinedComponent object

        """

        return UserDefinedComponent(element.attrib["userDefinedComponentType"])

    def get_attributes(self):
        """returns the attributes of the UserDefinedComponent as a dict"""
        retdict = {}
        retdict["userDefinedComponentType"] = self.type
        return retdict

    def get_element(self):
        """returns the elementTree of the UserDefinedComponent"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "UserDefinedComponent was introduced in OpenSCENARIO V1.2"
            )

        element = ET.Element("UserDefinedComponent", attrib=self.get_attributes())
        return element


class PedestrianAnimation(_AnimationType):
    """The PedestrianAnimation creates a PedestrianAnimation element used by AnimationType

    Parameters
    ----------
        motion (PedestrianMotionType): Motion of a pedestrian

        userDefinedPedestrianAnimation (str): User defined pedestrian animation

    Attributes
    ----------

        motion (PedestrianMotionType): Motion of a pedestrian

        userDefinedPedestrianAnimation (str): User defined pedestrian animation

        gestures (list of PedestrianGestureTpe): Gestures of a pedestrian

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        add_gesture(gesture)
            Adds a pedestrian gesture to the pedestrian animation

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, motion=None, animation=None):
        """initalizes the PedestrianAnimation

        Parameters
        ----------
        motion (PedestrianMotionType): Motion of a pedestrian

        userDefinedPedestrianAnimation (str): User defined pedestrian animation

        """
        self.motion = convert_enum(motion, PedestrianMotionType, True)
        self.animation = animation
        self.gestures = []

    def __eq__(self, other):
        if isinstance(other, PedestrianAnimation):
            if (
                other.get_attributes() == self.get_attributes()
                and other.gestures == self.gestures
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of a PedestrianAnimation

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a UserDefinedAnimation element

        Returns
        -------
            PedestrianAnimation (PedestrianAnimation): a PedestrianAnimation object

        """
        motion = convert_enum(element.attrib["motion"], PedestrianMotionType)
        animation = element.attrib["userDefinedPedestrianAnimation"]
        pa = PedestrianAnimation(motion, animation)

        for gesture in element.findall("PedestrianGesture"):
            pa.add_gesture(
                convert_enum(gesture.attrib["gesture"], PedestrianGestureType)
            )
        return pa

    def add_gesture(self, gesture):
        """adds a pedestrian gesture to the vehicle

        Parameters
        ----------
            gesture (PedestrianGestureType): A new gesture of the pedestrian

        """
        self.gestures.append(convert_enum(gesture, PedestrianGestureType))
        return self

    def get_attributes(self):
        """returns the attributes of the PedestrianAnimation as a dict"""
        retdict = {}
        retdict["motion"] = self.motion.get_name()
        retdict["userDefinedPedestrianAnimation"] = str(self.animation)
        return retdict

    def get_element(self):
        """returns the elementTree of the PedestrianAnimation"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "PedestrianAnimation was introduced in OpenSCENARIO V1.2"
            )

        element = ET.Element("PedestrianAnimation", attrib=self.get_attributes())
        for gesture in self.gestures:
            ET.SubElement(
                element, "PedestrianGesture", attrib={"gesture": gesture.get_name()}
            )
        return element


class _VehicleComponent(VersionBase):
    """The VehicleComponent creates a VehicleComponent element used by ComponentAnimation

    Parameters
    ----------
        vehicleComponenetType (VehicleComponentType): Available compopnent types attached to a vehicle.

    Attributes
    ----------

        vehicleComponenetType (VehicleComponentType): Available compopnent types attached to a vehicle.

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, type):
        """initalizes the VehicleComponent

        Parameters
        ----------
        vehicleComponenetType (VehicleComponentType): Available compopnent types attached to a vehicle.

        """
        self.type = convert_enum(type, VehicleComponentType)

    def __eq__(self, other):
        if isinstance(other, _VehicleComponent):
            if other.get_attributes() == self.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of a VehicleComponent

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a VehicleComponent element

        Returns
        -------
            VehicleComponent (VehicleComponent): a VehicleComponent object

        """
        type = convert_enum(
            element.attrib["vehicleComponentType"], VehicleComponentType
        )
        return _VehicleComponent(type)

    def get_attributes(self):
        """returns the attributes of the VehicleComponent as a dict"""
        retdict = {}
        retdict["vehicleComponentType"] = self.type.get_name()
        return retdict

    def get_element(self):
        """returns the elementTree of the VehicleComponent"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "VehicleComponent was introduced in OpenSCENARIO V1.2"
            )

        element = ET.Element("VehicleComponent", attrib=self.get_attributes())
        return element


class _ComponentAnimation(_AnimationType):
    """The VehicleComponent creates a VehicleComponent element used by ComponentAnimation

    Parameters
    ----------
        vehicleComponent (_VehicleComponent): Available components types attached to a vehicle

        userDefinedComponent (UserDefinedComponent): The component type is not covered by the above options and is therefore user defined

    Attributes
    ----------

        vehicleComponent (_VehicleComponent): Available components types attached to a vehicle

        userDefinedComponent (UserDefinedComponent): The component type is not covered by the above options and is therefore user defined

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class
    """

    def __init__(self, component):
        """initalizes the VehicleComponent

        Parameters
        ----------
        component (vehicleComponent or UserDefinedComponent): Either available components types attached to the vehicle or a user defined component
        """
        if not isinstance(component, _VehicleComponent) and not isinstance(
            component, UserDefinedComponent
        ):
            raise TypeError(
                component + " is not of type VehicleComponent or UserDefinedComponent"
            )
        self.component = component

    def __eq__(self, other):
        if isinstance(other, _ComponentAnimation):
            if other.component.get_attributes() == self.component.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of a ComponentAnimation

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a ComponentAnimation element

        Returns
        -------
            ComponentAnimation (ComponentAnimation): a ComponentAnimation object

        """
        if element.find("VehicleComponent") != None:
            component = _VehicleComponent.parse(element.find("VehicleComponent"))
        else:
            component = UserDefinedComponent.parse(element.find("UserDefinedComponent"))
        return _ComponentAnimation(component)

    def get_element(self):
        """returns the elementTree of the ComponentAnimation"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "ComponentAnimation was introduced in OpenSCENARIO V1.2"
            )

        element = ET.Element("ComponentAnimation")
        if isinstance(_VehicleComponent, type(self.component)):
            element.append(self.component.get_element())
        else:
            element.append(self.component.get_element())

        return element

Functions

def convert_bool(value)

Method to transform booleans to correct xml version (lower case)

Parameter

value (bool): the boolean

Return

boolean (str)
Expand source code
def convert_bool(value):
    """Method to transform booleans to correct xml version (lower case)

    Parameter
    ---------
        value (bool): the boolean

    Return
    ------
        boolean (str)
    """
    if isinstance(value, str):
        if value == "true" or value == "1":
            return True
        elif value == "false" or value == "0":
            return False
        elif value[0] == "$":
            return value
        else:
            raise ValueError(
                value
                + "is not a valid type of boolean input to openscenario, if a string is used as a boolean value (parameter or expression), it should have a $ as the first char.."
            )

    if value:
        return True
    elif value == None:
        return None
    else:
        return False
def convert_enum(value, enumtype, none_ok=False)
Expand source code
def convert_enum(value, enumtype, none_ok=False):
    if isinstance(value, _OscEnum):
        if hasattr(enumtype, str(value)) or "$" == str(value)[0]:
            return value
        else:
            raise TypeError(
                value.get_name() + " is not of Enumeration type :" + str(enumtype)
            )
    elif isinstance(value, str):
        if hasattr(enumtype, value):
            return _OscEnum(enumtype.__name__, value)
        elif "$" == value[0]:
            return _OscEnum(enumtype.__name__, value)
        else:
            raise ValueError(
                value
                + " is not a valid string input for Enumeration type "
                + str(enumtype)
            )
    elif value == None:
        if none_ok:
            return None
        else:
            raise TypeError("None value not a valid option for: " + str(enumtype))

    raise TypeError(str(value) + " is not of a valid enumeration or str type.")
def convert_float(value)

Method to ensure floats are floats, will take care of None values aswell

Parameter

value (float/str/int/None): a value to transform to float

Return

value (float/None)
Expand source code
def convert_float(value):
    """Method to ensure floats are floats, will take care of None values aswell

    Parameter
    ---------
        value (float/str/int/None): a value to transform to float

    Return
    ------
        value (float/None)
    """
    if isinstance(value, str):
        if value[0] == "$":
            return value
        try:
            float(value)
        except ValueError:
            raise ValueError(
                value
                + "is not a valid type of float input to openscenario, if a string is used as a float value (parameter or expression), it should have a $ as the first char.."
            )

    if value is not None:
        return float(value)
    else:
        return None
def convert_int(value)

Method to ensure ints are ints, will take care of None values aswell

Parameter

value (float/str/int/None): a value to transform to int

Return

value (int/None)
Expand source code
def convert_int(value):
    """Method to ensure ints are ints, will take care of None values aswell

    Parameter
    ---------
        value (float/str/int/None): a value to transform to int

    Return
    ------
        value (int/None)
    """
    if isinstance(value, str):
        if value[0] == "$":
            return value
        try:
            int(value)
        except ValueError:
            raise ValueError(
                value
                + "is not a valid type of int input to openscenario, if a string is used as a int value (parameter or expression), it should have a $ as the first char."
            )

    if value is not None:
        return int(value)
    else:
        return None
def get_bool_string(value)
Expand source code
def get_bool_string(value):
    if isinstance(value, str) and value[0] == "$":
        return value
    elif value:
        return "true"
    else:
        return "false"
def merge_dicts(*dict_args)

Funciton to merge dicts

Expand source code
def merge_dicts(*dict_args):
    """Funciton to merge dicts"""
    retdict = {}
    for d in dict_args:
        retdict.update(d)

    return retdict

Classes

class AbsoluteSpeed (value, steadyState=None)

Parameters

value (float): absolute speed [m/s]

steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Final phase of constant (final) speed, start of which defined by distance or time. (Valid from OpenSCENARIO V1.1)

Attributes

value (float): absolute speed [m/s]

steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Final phase of constant (final) speed, start of which defined by distance or time. (Valid from OpenSCENARIO V1.1)

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns the attributes of the class

initalzie the AbsoluteSpeed

Parameters

value (float): absolute speed [m/s]
steadyState (TargetTimeSteadyState / TargetDistanceSteadyState) Final phase of constant (final) speed, start of which defined by distance or time. (Valid from OpenSCENARIO V1.1)
Expand source code
class AbsoluteSpeed(VersionBase):
    """
    Parameters
    ----------
        value (float): absolute speed [m/s]

        steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Final phase of constant (final) speed, start of which defined by distance or time. (Valid from OpenSCENARIO V1.1)

    Attributes
    ----------
        value (float): absolute speed [m/s]

        steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Final phase of constant (final) speed, start of which defined by distance or time. (Valid from OpenSCENARIO V1.1)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns the attributes of the class
    """

    def __init__(self, value, steadyState=None):
        """initalzie the AbsoluteSpeed

        Parameters
        ----------
            value (float): absolute speed [m/s]
            steadyState (TargetTimeSteadyState / TargetDistanceSteadyState) Final phase of constant (final) speed, start of which defined by distance or time. (Valid from OpenSCENARIO V1.1)
        """
        self.value = value
        if steadyState:
            if not (
                isinstance(steadyState, TargetTimeSteadyState)
                or isinstance(steadyState, TargetDistanceSteadyState)
            ):
                raise TypeError(
                    "steadyState input is not an TargetTimeSteadyState or TargetDistanceSteadyState input"
                )
        self.steadyState = steadyState

    def __eq__(self, other):
        if isinstance(other, AbsoluteSpeed):
            if (
                self.get_attributes() == other.get_attributes()
                and self.steadyState == other.steadyState
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of AbsoluteSpeed

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A absolute speed element (same as generated by the class itself)

        Returns
        -------
            absolutespeed (AbsoluteSpeed): a AbsoluteSpeed object

        """
        absolute_speed_element = element.find("AbsoluteSpeed")
        value = absolute_speed_element.attrib["value"]

        state = None
        if absolute_speed_element.find("TargetDistanceSteadyState") != None:
            state = TargetDistanceSteadyState.parse(
                absolute_speed_element.find("TargetDistanceSteadyState")
            )
        elif absolute_speed_element.find("TargetTimeSteadyState") != None:
            state = TargetTimeSteadyState.parse(
                absolute_speed_element.find("TargetTimeSteadyState")
            )

        return AbsoluteSpeed(value, state)

    def get_attributes(self):
        """returns the attributes of the AbsoluteSpeed"""
        return {"value": str(self.value)}

    def get_element(self):
        """returns the elementTree of the AbsoluteSpeed"""

        elementFinalSpeed = ET.Element("FinalSpeed")
        elementAbsoluteSpeed = ET.SubElement(
            elementFinalSpeed, "AbsoluteSpeed", attrib=self.get_attributes()
        )
        if self.steadyState:
            if self.isVersion(minor=0):
                raise OpenSCENARIOVersionError(
                    "steadyState was introduced in OpenSCENARIO V1.1"
                )
            ET.SubElement(
                elementAbsoluteSpeed,
                self.steadyState.__class__.__name__,
                attrib=self.steadyState.get_attributes(),
            )

        return elementFinalSpeed

Ancestors

Static methods

def parse(element)

Parses the xml element of AbsoluteSpeed

Parameters

element (xml.etree.ElementTree.Element): A absolute speed element (same as generated by the class itself)

Returns

absolutespeed (AbsoluteSpeed): a AbsoluteSpeed object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of AbsoluteSpeed

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A absolute speed element (same as generated by the class itself)

    Returns
    -------
        absolutespeed (AbsoluteSpeed): a AbsoluteSpeed object

    """
    absolute_speed_element = element.find("AbsoluteSpeed")
    value = absolute_speed_element.attrib["value"]

    state = None
    if absolute_speed_element.find("TargetDistanceSteadyState") != None:
        state = TargetDistanceSteadyState.parse(
            absolute_speed_element.find("TargetDistanceSteadyState")
        )
    elif absolute_speed_element.find("TargetTimeSteadyState") != None:
        state = TargetTimeSteadyState.parse(
            absolute_speed_element.find("TargetTimeSteadyState")
        )

    return AbsoluteSpeed(value, state)

Methods

def get_attributes(self)

returns the attributes of the AbsoluteSpeed

Expand source code
def get_attributes(self):
    """returns the attributes of the AbsoluteSpeed"""
    return {"value": str(self.value)}
def get_element(self)

returns the elementTree of the AbsoluteSpeed

Expand source code
def get_element(self):
    """returns the elementTree of the AbsoluteSpeed"""

    elementFinalSpeed = ET.Element("FinalSpeed")
    elementAbsoluteSpeed = ET.SubElement(
        elementFinalSpeed, "AbsoluteSpeed", attrib=self.get_attributes()
    )
    if self.steadyState:
        if self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "steadyState was introduced in OpenSCENARIO V1.1"
            )
        ET.SubElement(
            elementAbsoluteSpeed,
            self.steadyState.__class__.__name__,
            attrib=self.steadyState.get_attributes(),
        )

    return elementFinalSpeed
class AnimationFile (file, timeOffset=None)

The AnimationFile creates a AnimationFile element used by AnimationType

Parameters

file (string): filepath of the annimation / motion file

timeOffset (float): time offset from beginning of animation

Attributes

timeOffset (float): time offset from beginning of animation

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element(elementname)
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalizes the AnimationFile

Parameters

file (string): filepath of the annimation / motion file

timeOffset (float): time offset from beginning of animation

Expand source code
class AnimationFile(_AnimationType):
    """The AnimationFile creates a AnimationFile element used by AnimationType

    Parameters
    ----------
        file (string): filepath of the annimation / motion file

        timeOffset (float): time offset from beginning of animation

    Attributes
    ----------

        timeOffset (float): time offset from beginning of animation

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, file, timeOffset=None):
        """initalizes the AnimationFile

        Parameters
        ----------
        file (string): filepath of the annimation / motion file

        timeOffset (float): time offset from beginning of animation

        """
        self.file = file
        self.timeOffset = convert_float(timeOffset)

    def __eq__(self, other):
        if isinstance(other, AnimationFile):
            if (
                other.get_attributes() == self.get_attributes()
                and other.file == self.file
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of a AnimationFile

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a AnimationFile element

        Returns
        -------
            AnimationFile (AnimationFile): a AnimationFile object

        """

        timeOffset = None
        if element.find("File") is not None:
            file = element.find("File").attrib["filepath"]
        if "timeOffset" in element.attrib:
            timeOffset = convert_float(element.attrib["timeOffset"])
        return AnimationFile(file, timeOffset)

    def get_attributes(self):
        """returns the attributes of the AnimationFile as a dict"""
        retdict = {}
        if self.timeOffset is not None:
            retdict["timeOffset"] = str(self.timeOffset)
        return retdict

    def get_element(self):
        """returns the elementTree of the AnimationFile"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "AnimationFile was introduced in OpenSCENARIO V1.2"
            )

        element = ET.Element("AnimationFile", attrib=self.get_attributes())
        if self.file:
            ET.SubElement(element, "File", {"filepath": self.file})
        return element

Ancestors

  • scenariogeneration.xosc.utils._AnimationType
  • VersionBase

Static methods

def parse(element)

Parses the xml element of a AnimationFile

Parameters

element (xml.etree.ElementTree.Element): a AnimationFile element

Returns

AnimationFile (AnimationFile): a AnimationFile object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of a AnimationFile

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): a AnimationFile element

    Returns
    -------
        AnimationFile (AnimationFile): a AnimationFile object

    """

    timeOffset = None
    if element.find("File") is not None:
        file = element.find("File").attrib["filepath"]
    if "timeOffset" in element.attrib:
        timeOffset = convert_float(element.attrib["timeOffset"])
    return AnimationFile(file, timeOffset)

Methods

def get_attributes(self)

returns the attributes of the AnimationFile as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the AnimationFile as a dict"""
    retdict = {}
    if self.timeOffset is not None:
        retdict["timeOffset"] = str(self.timeOffset)
    return retdict
def get_element(self)

returns the elementTree of the AnimationFile

Expand source code
def get_element(self):
    """returns the elementTree of the AnimationFile"""
    if not self.isVersion(minor=2):
        raise OpenSCENARIOVersionError(
            "AnimationFile was introduced in OpenSCENARIO V1.2"
        )

    element = ET.Element("AnimationFile", attrib=self.get_attributes())
    if self.file:
        ET.SubElement(element, "File", {"filepath": self.file})
    return element
class BoundingBox (width, length, height, x_center, y_center, z_center)

the Dimensions describes the size of an entity

Parameters

width (float): the width of the entity

length (float): the lenght of the entity

height (float): the height of the entity

x_center (float): x distance from back axel to center

y_center (float): y distance from back axel to clas

z_center (float): z distance from back axel to center

Attributes

dimensions (Dimensions): the dimensions of the entity

center (Center): the center of the object relative the the back axel

Methods

get_element()
    Returns the full ElementTree of the class

parse(element)
    parses a ElementTree created by the class and returns an instance of the class itself

initalzie the Dimensions

Parameters

width (float): the width of the entity

length (float): the lenght of the entity

height (float): the height of the entity

x_center (float): x distance from back axel to center

y_center (float): y distance from back axel to center

z_center (float): z distance from back axel to center
Expand source code
class BoundingBox(VersionBase):
    """the Dimensions describes the size of an entity

    Parameters
    ----------
        width (float): the width of the entity

        length (float): the lenght of the entity

        height (float): the height of the entity

        x_center (float): x distance from back axel to center

        y_center (float): y distance from back axel to clas

        z_center (float): z distance from back axel to center


    Attributes
    ----------
        dimensions (Dimensions): the dimensions of the entity

        center (Center): the center of the object relative the the back axel

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class itself


    """

    def __init__(self, width, length, height, x_center, y_center, z_center):
        """initalzie the Dimensions

        Parameters
        ----------
            width (float): the width of the entity

            length (float): the lenght of the entity

            height (float): the height of the entity

            x_center (float): x distance from back axel to center

            y_center (float): y distance from back axel to center

            z_center (float): z distance from back axel to center

        """
        self.boundingbox = Dimensions(width, length, height)
        self.center = Center(x_center, y_center, z_center)

    def __eq__(self, other):
        if isinstance(other, BoundingBox):
            if self.boundingbox == other.boundingbox and self.center == other.center:
                return True
        return False

    def get_element(self):
        """returns the elementTree of the Dimensions"""
        element = ET.Element("BoundingBox")
        element.append(self.center.get_element())
        element.append(self.boundingbox.get_element())
        return element

    @staticmethod
    def parse(element):
        """Parses the xml element of BoundingBox

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A orientation element (same as generated by the class itself)

        Returns
        -------
            boundingBox (BoundingBox): a BoundingBox object

        """
        center = Center.parse(element.find("Center"))
        cen_dict = center.get_attributes()
        dimension = Dimensions.parse(element.find("Dimensions"))
        dim_dict = dimension.get_attributes()
        return BoundingBox(
            dim_dict["width"],
            dim_dict["length"],
            dim_dict["height"],
            cen_dict["x"],
            cen_dict["y"],
            cen_dict["z"],
        )

Ancestors

Static methods

def parse(element)

Parses the xml element of BoundingBox

Parameters

element (xml.etree.ElementTree.Element): A orientation element (same as generated by the class itself)

Returns

boundingBox (BoundingBox): a BoundingBox object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of BoundingBox

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A orientation element (same as generated by the class itself)

    Returns
    -------
        boundingBox (BoundingBox): a BoundingBox object

    """
    center = Center.parse(element.find("Center"))
    cen_dict = center.get_attributes()
    dimension = Dimensions.parse(element.find("Dimensions"))
    dim_dict = dimension.get_attributes()
    return BoundingBox(
        dim_dict["width"],
        dim_dict["length"],
        dim_dict["height"],
        cen_dict["x"],
        cen_dict["y"],
        cen_dict["z"],
    )

Methods

def get_element(self)

returns the elementTree of the Dimensions

Expand source code
def get_element(self):
    """returns the elementTree of the Dimensions"""
    element = ET.Element("BoundingBox")
    element.append(self.center.get_element())
    element.append(self.boundingbox.get_element())
    return element
class Catalog

The Catalog class creates the CatalogLocation of the OpenScenario input

Parameters

Attributes

catalogs: dict of catalogs to add, and their path

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

add_catalog(catalogname, path)
    Adds a new catalog

initalize the Catalog class

Expand source code
class Catalog(VersionBase):
    """The Catalog class creates the CatalogLocation of the OpenScenario input

    Parameters
    ----------

    Attributes
    ----------
        catalogs: dict of catalogs to add, and their path
    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        add_catalog(catalogname, path)
            Adds a new catalog
    """

    _CATALOGS = [
        "VehicleCatalog",
        "ControllerCatalog",
        "PedestrianCatalog",
        "MiscObjectCatalog",
        "EnvironmentCatalog",
        "ManeuverCatalog",
        "TrajectoryCatalog",
        "RouteCatalog",
    ]

    def __init__(self):
        """initalize the Catalog class"""
        self.catalogs = {}

    def __eq__(self, other):
        if isinstance(other, Catalog):
            if self.catalogs == other.catalogs:
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Catalog

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A Catalog element (same as generated by the class itself)

        Returns
        -------
            catalog (Catalog): a Catalog object

        """
        catalog = Catalog()

        vc_element = element.find("VehicleCatalog")
        if vc_element is not None:
            path = vc_element.find("Directory").attrib["path"]
            catalog.add_catalog("VehicleCatalog", path)

        cc_element = element.find("ControllerCatalog")
        if cc_element is not None:
            path = cc_element.find("Directory").attrib["path"]
            catalog.add_catalog("ControllerCatalog", path)

        pc_element = element.find("PedestrianCatalog")
        if pc_element is not None:
            path = pc_element.find("Directory").attrib["path"]
            catalog.add_catalog("PedestrianCatalog", path)

        moc_element = element.find("MiscObjectCatalog")
        if moc_element is not None:
            path = moc_element.find("Directory").attrib["path"]
            catalog.add_catalog("MiscObjectCatalog", path)

        ec_element = element.find("EnvironmentCatalog")
        if ec_element is not None:
            path = ec_element.find("Directory").attrib["path"]
            catalog.add_catalog("EnvironmentCatalog", path)

        mc_element = element.find("ManeuverCatalog")
        if mc_element is not None:
            path = mc_element.find("Directory").attrib["path"]
            catalog.add_catalog("ManeuverCatalog", path)

        tc_element = element.find("TrajectoryCatalog")
        if tc_element is not None:
            path = tc_element.find("Directory").attrib["path"]
            catalog.add_catalog("TrajectoryCatalog", path)

        rc_element = element.find("RouteCatalog")
        if rc_element is not None:
            path = rc_element.find("Directory").attrib["path"]
            catalog.add_catalog("RouteCatalog", path)

        return catalog

    def add_catalog(self, catalogname, path):
        """add new catalog to be used

        Parameters
        ----------
            catalogname (str): name of the catalog

            path (str): path to the catalog

        """

        if catalogname not in self._CATALOGS:
            raise ValueError(
                f"Not a correct catalog, approved catalogs are: {', '.join(self._CATALOGS)}."
            )

        self.catalogs[catalogname] = path
        return self

    def get_element(self):
        """returns the elementTree of the Catalog"""

        catloc = ET.Element("CatalogLocations")

        for i in self.catalogs:
            tmpel = ET.SubElement(catloc, i)
            ET.SubElement(tmpel, "Directory", {"path": self.catalogs[i]})
        return catloc

Ancestors

Static methods

def parse(element)

Parses the xml element of Catalog

Parameters

element (xml.etree.ElementTree.Element): A Catalog element (same as generated by the class itself)

Returns

catalog (Catalog): a Catalog object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Catalog

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A Catalog element (same as generated by the class itself)

    Returns
    -------
        catalog (Catalog): a Catalog object

    """
    catalog = Catalog()

    vc_element = element.find("VehicleCatalog")
    if vc_element is not None:
        path = vc_element.find("Directory").attrib["path"]
        catalog.add_catalog("VehicleCatalog", path)

    cc_element = element.find("ControllerCatalog")
    if cc_element is not None:
        path = cc_element.find("Directory").attrib["path"]
        catalog.add_catalog("ControllerCatalog", path)

    pc_element = element.find("PedestrianCatalog")
    if pc_element is not None:
        path = pc_element.find("Directory").attrib["path"]
        catalog.add_catalog("PedestrianCatalog", path)

    moc_element = element.find("MiscObjectCatalog")
    if moc_element is not None:
        path = moc_element.find("Directory").attrib["path"]
        catalog.add_catalog("MiscObjectCatalog", path)

    ec_element = element.find("EnvironmentCatalog")
    if ec_element is not None:
        path = ec_element.find("Directory").attrib["path"]
        catalog.add_catalog("EnvironmentCatalog", path)

    mc_element = element.find("ManeuverCatalog")
    if mc_element is not None:
        path = mc_element.find("Directory").attrib["path"]
        catalog.add_catalog("ManeuverCatalog", path)

    tc_element = element.find("TrajectoryCatalog")
    if tc_element is not None:
        path = tc_element.find("Directory").attrib["path"]
        catalog.add_catalog("TrajectoryCatalog", path)

    rc_element = element.find("RouteCatalog")
    if rc_element is not None:
        path = rc_element.find("Directory").attrib["path"]
        catalog.add_catalog("RouteCatalog", path)

    return catalog

Methods

def add_catalog(self, catalogname, path)

add new catalog to be used

Parameters

catalogname (str): name of the catalog

path (str): path to the catalog
Expand source code
def add_catalog(self, catalogname, path):
    """add new catalog to be used

    Parameters
    ----------
        catalogname (str): name of the catalog

        path (str): path to the catalog

    """

    if catalogname not in self._CATALOGS:
        raise ValueError(
            f"Not a correct catalog, approved catalogs are: {', '.join(self._CATALOGS)}."
        )

    self.catalogs[catalogname] = path
    return self
def get_element(self)

returns the elementTree of the Catalog

Expand source code
def get_element(self):
    """returns the elementTree of the Catalog"""

    catloc = ET.Element("CatalogLocations")

    for i in self.catalogs:
        tmpel = ET.SubElement(catloc, i)
        ET.SubElement(tmpel, "Directory", {"path": self.catalogs[i]})
    return catloc
class CatalogFile (prettyprint=True, encoding='utf-8')

The CatalogFile class handles any catalogs in open scenario, such as writing, and updating them

Parameters

prettyprint (boolean): if the final file should have prettyprint or not
    Default: True

Attributes

prettyprint: if the final file should have prettyprint or not

catalog_element (Element): the element that is worked with

filename (str): path to the file to be written to

Methods

get_element()
    Returns the full ElementTree of the class

add_catalog(catalogname, path)
    Adds a new catalog

initalize the CatalogFile class

Parameters

prettyprint (boolean): if the final file should have prettyprint or not
    Default: True
Expand source code
class CatalogFile(VersionBase):
    """The CatalogFile class handles any catalogs in open scenario, such as writing, and updating them

    Parameters
    ----------
        prettyprint (boolean): if the final file should have prettyprint or not
            Default: True

    Attributes
    ----------
        prettyprint: if the final file should have prettyprint or not

        catalog_element (Element): the element that is worked with

        filename (str): path to the file to be written to

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

        add_catalog(catalogname, path)
            Adds a new catalog
    """

    def __init__(self, prettyprint=True, encoding="utf-8"):
        """initalize the CatalogFile class

        Parameters
        ----------
            prettyprint (boolean): if the final file should have prettyprint or not
                Default: True
        """
        self.prettyprint = prettyprint
        self.catalog_element = None
        self.filename = ""
        self.encoding = encoding

    def add_to_catalog(self, obj, osc_minor_version=_MINOR_VERSION):
        """add_to_catalog adds an element to the catalog

        Parameters
        ----------
            obj (*pyoscx): any pyoscx object (should be matching with the catalog)

            osc_minor_version (int): the minor version of OpenSCENARIO to write to the catalog
                Default: same as package
        """
        if self.catalog_element == None:
            OSError("No file has been created or opened")
        fileheader = self.catalog_element.find("FileHeader")
        self.version_minor = osc_minor_version
        if fileheader.attrib["revMinor"] != osc_minor_version:
            Warning(
                "The Catalog and the added object does not have the same OpenSCENARIO version."
            )
        catalogs = self.catalog_element.find("Catalog")
        catalogs.append(obj.get_element())
        return self

    def open_catalog(self, filename):
        """open_catalog reads an existing catalog file

        Parameters
        ----------
            filename (str): path to the catalog file

        """
        self.filename = filename
        tree = ET.parse(self.filename)
        self.catalog_element = tree.getroot()

    def create_catalog(self, filename, catalogtype, description, author):
        """create_catalog_element creates an empty catalog of a desiered type,

        Parameters
        ----------
            filename (str): path of the new catalog file

            catalogtype (str): name of the catalog

            description (str): description of the catalog

            author (str): author of the catalog

        """
        self.filename = filename
        self.catalog_element = self.create_catalog_element(
            catalogtype, description, author
        )

    def create_catalog_element(self, catalogtype, description, author):
        """create_catalog_element creates an empty catalog of a desiered type,

        Parameters
        ----------
            catalogtype (str): name of the catalog

            description (str): description of the catalog

            author (str): author of the catalog

        """
        element = ET.Element(
            "OpenSCENARIO",
            attrib={
                "xmlns:xsi": XMLNS,
                "xsi:noNamespaceSchemaLocation": "../../" + XSI,
            },
        )
        #         header = FileHeader(description, author)
        header = FileHeader(author, description)
        element.append(header.get_element())
        ET.SubElement(element, "Catalog", attrib={"name": catalogtype})

        return element

    def dump(self):
        """writes the new/updated catalog file"""
        printToFile(
            self.catalog_element, self.filename, self.prettyprint, self.encoding
        )

Ancestors

Methods

def add_to_catalog(self, obj, osc_minor_version=2)

add_to_catalog adds an element to the catalog

Parameters

obj (*pyoscx): any pyoscx object (should be matching with the catalog)

osc_minor_version (int): the minor version of OpenSCENARIO to write to the catalog
    Default: same as package
Expand source code
def add_to_catalog(self, obj, osc_minor_version=_MINOR_VERSION):
    """add_to_catalog adds an element to the catalog

    Parameters
    ----------
        obj (*pyoscx): any pyoscx object (should be matching with the catalog)

        osc_minor_version (int): the minor version of OpenSCENARIO to write to the catalog
            Default: same as package
    """
    if self.catalog_element == None:
        OSError("No file has been created or opened")
    fileheader = self.catalog_element.find("FileHeader")
    self.version_minor = osc_minor_version
    if fileheader.attrib["revMinor"] != osc_minor_version:
        Warning(
            "The Catalog and the added object does not have the same OpenSCENARIO version."
        )
    catalogs = self.catalog_element.find("Catalog")
    catalogs.append(obj.get_element())
    return self
def create_catalog(self, filename, catalogtype, description, author)

create_catalog_element creates an empty catalog of a desiered type,

Parameters

filename (str): path of the new catalog file

catalogtype (str): name of the catalog

description (str): description of the catalog

author (str): author of the catalog
Expand source code
def create_catalog(self, filename, catalogtype, description, author):
    """create_catalog_element creates an empty catalog of a desiered type,

    Parameters
    ----------
        filename (str): path of the new catalog file

        catalogtype (str): name of the catalog

        description (str): description of the catalog

        author (str): author of the catalog

    """
    self.filename = filename
    self.catalog_element = self.create_catalog_element(
        catalogtype, description, author
    )
def create_catalog_element(self, catalogtype, description, author)

create_catalog_element creates an empty catalog of a desiered type,

Parameters

catalogtype (str): name of the catalog

description (str): description of the catalog

author (str): author of the catalog
Expand source code
def create_catalog_element(self, catalogtype, description, author):
    """create_catalog_element creates an empty catalog of a desiered type,

    Parameters
    ----------
        catalogtype (str): name of the catalog

        description (str): description of the catalog

        author (str): author of the catalog

    """
    element = ET.Element(
        "OpenSCENARIO",
        attrib={
            "xmlns:xsi": XMLNS,
            "xsi:noNamespaceSchemaLocation": "../../" + XSI,
        },
    )
    #         header = FileHeader(description, author)
    header = FileHeader(author, description)
    element.append(header.get_element())
    ET.SubElement(element, "Catalog", attrib={"name": catalogtype})

    return element
def dump(self)

writes the new/updated catalog file

Expand source code
def dump(self):
    """writes the new/updated catalog file"""
    printToFile(
        self.catalog_element, self.filename, self.prettyprint, self.encoding
    )
def open_catalog(self, filename)

open_catalog reads an existing catalog file

Parameters

filename (str): path to the catalog file
Expand source code
def open_catalog(self, filename):
    """open_catalog reads an existing catalog file

    Parameters
    ----------
        filename (str): path to the catalog file

    """
    self.filename = filename
    tree = ET.parse(self.filename)
    self.catalog_element = tree.getroot()
class CatalogReference (catalogname, entryname)

CatalogReference creates an CatalogReference element of openscenario

Parameters

catalogname (str): name of the catalog

entryname (str): name of the entry in the catalog

Attributes

catalogname (str): name of the catalog

entryname (str): name of the entry in the catalog

parameterassignments (list of ParameterAssignment): the parameter assignments for the given catalogreference

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

add_parameter_assignment(parameterref,value)
    Assigns a parameter with a value

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the CatalogReference

Parameters

catalogname (str): name of the catalog

entryname (str): name of the entry in the catalog
Expand source code
class CatalogReference(VersionBase):
    """CatalogReference creates an CatalogReference element of openscenario

    Parameters
    ----------
        catalogname (str): name of the catalog

        entryname (str): name of the entry in the catalog

    Attributes
    ----------
        catalogname (str): name of the catalog

        entryname (str): name of the entry in the catalog

        parameterassignments (list of ParameterAssignment): the parameter assignments for the given catalogreference

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        add_parameter_assignment(parameterref,value)
            Assigns a parameter with a value

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, catalogname, entryname):
        """initalize the CatalogReference

        Parameters
        ----------
            catalogname (str): name of the catalog

            entryname (str): name of the entry in the catalog

        """
        self.catalogname = catalogname
        self.entryname = entryname
        self.parameterassignments = []

    def __eq__(self, other):
        if isinstance(other, CatalogReference):
            if (
                self.get_attributes() == other.get_attributes()
                and self.parameterassignments == other.parameterassignments
            ):
                return True
        return False

    # TODO: CatalogElement???

    @staticmethod
    def parse(element):
        """Parses the xml element of CatalogReference

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A catalog reference element (same as generated by the class itself)

        Returns
        -------
            reference (CatalogReference): a catalog reference object

        """
        catalogname = element.attrib["catalogName"]
        entryname = element.attrib["entryName"]
        reference = CatalogReference(catalogname, entryname)

        parameter_assignments = element.find("ParameterAssignments")
        if parameter_assignments != None:
            parameters = parameter_assignments.findall("ParameterAssignment")
            for parameter in parameters:
                parameter_assignment = ParameterAssignment.parse(parameter)
                reference.parameterassignments.append(parameter_assignment)

        return reference

    def add_parameter_assignment(self, parameterref, value):
        """add_parameter_assignment adds a parameter and value to the catalog reference

        Parameters
        ----------
            parameterref (str): name of the parameter

            value (str): assigned value of the parameter
        """
        self.parameterassignments.append(ParameterAssignment(parameterref, value))
        return self

    def get_attributes(self):
        """returns the attributes of the CatalogReference as a dict"""
        return {"catalogName": self.catalogname, "entryName": self.entryname}

    def get_element(self):
        """returns the elementTree of the CatalogReference"""
        element = ET.Element("CatalogReference", attrib=self.get_attributes())
        if self.parameterassignments:
            parameterassigns = ET.SubElement(element, "ParameterAssignments")
        for parass in self.parameterassignments:
            parameterassigns.append(parass.get_element())
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of CatalogReference

Parameters

element (xml.etree.ElementTree.Element): A catalog reference element (same as generated by the class itself)

Returns

reference (CatalogReference): a catalog reference object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of CatalogReference

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A catalog reference element (same as generated by the class itself)

    Returns
    -------
        reference (CatalogReference): a catalog reference object

    """
    catalogname = element.attrib["catalogName"]
    entryname = element.attrib["entryName"]
    reference = CatalogReference(catalogname, entryname)

    parameter_assignments = element.find("ParameterAssignments")
    if parameter_assignments != None:
        parameters = parameter_assignments.findall("ParameterAssignment")
        for parameter in parameters:
            parameter_assignment = ParameterAssignment.parse(parameter)
            reference.parameterassignments.append(parameter_assignment)

    return reference

Methods

def add_parameter_assignment(self, parameterref, value)

add_parameter_assignment adds a parameter and value to the catalog reference

Parameters

parameterref (str): name of the parameter

value (str): assigned value of the parameter
Expand source code
def add_parameter_assignment(self, parameterref, value):
    """add_parameter_assignment adds a parameter and value to the catalog reference

    Parameters
    ----------
        parameterref (str): name of the parameter

        value (str): assigned value of the parameter
    """
    self.parameterassignments.append(ParameterAssignment(parameterref, value))
    return self
def get_attributes(self)

returns the attributes of the CatalogReference as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the CatalogReference as a dict"""
    return {"catalogName": self.catalogname, "entryName": self.entryname}
def get_element(self)

returns the elementTree of the CatalogReference

Expand source code
def get_element(self):
    """returns the elementTree of the CatalogReference"""
    element = ET.Element("CatalogReference", attrib=self.get_attributes())
    if self.parameterassignments:
        parameterassigns = ET.SubElement(element, "ParameterAssignments")
    for parass in self.parameterassignments:
        parameterassigns.append(parass.get_element())
    return element
class Center (x, y, z)

the Center Class creates a centerpoint for a bounding box, reference point of a vehicle is the back axel

Parameters

x (float): x distance from back axel to center

y (float): y distance from back axel to center

z (float): z distance from back axel to center

Attributes

x (float): x distance from back axel to center

y (float): y distance from back axel to center

z (float): z distance from back axel to center

Methods

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

parse(element)
    parses a ElementTree created by the class and returns an instance of the class itself

initalzie the Center Class

Parameters

x (float): x distance from back axel to center

y (float): y distance from back axel to center

z (float): z distance from back axel to center
Expand source code
class Center(VersionBase):
    """the Center Class creates a centerpoint for a bounding box, reference point of a vehicle is the back axel

    Parameters
    ----------
        x (float): x distance from back axel to center

        y (float): y distance from back axel to center

        z (float): z distance from back axel to center


    Attributes
    ----------
        x (float): x distance from back axel to center

        y (float): y distance from back axel to center

        z (float): z distance from back axel to center

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class itself

    """

    def __init__(self, x, y, z):
        """initalzie the Center Class

        Parameters
        ----------
            x (float): x distance from back axel to center

            y (float): y distance from back axel to center

            z (float): z distance from back axel to center

        """
        self.x = convert_float(x)
        self.y = convert_float(y)
        self.z = convert_float(z)

    @staticmethod
    def parse(element):
        """Parses the xml element to Center

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A center element (same as generated by the class itself)

        Returns
        ------
            center (Center): a Center object

        """
        x = convert_float(element.attrib["x"])
        y = convert_float(element.attrib["y"])
        z = convert_float(element.attrib["z"])
        return Center(x, y, z)

    def __eq__(self, other):
        if isinstance(other, Center):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    def get_attributes(self):
        """returns the attributes as a dict of the Center"""
        return {"x": str(self.x), "y": str(self.y), "z": str(self.z)}

    def get_element(self):
        """returns the elementTree of the Center"""
        element = ET.Element("Center", attrib=self.get_attributes())
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element to Center

Parameters

element (xml.etree.ElementTree.Element): A center element (same as generated by the class itself)

Returns

center (Center): a Center object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element to Center

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A center element (same as generated by the class itself)

    Returns
    ------
        center (Center): a Center object

    """
    x = convert_float(element.attrib["x"])
    y = convert_float(element.attrib["y"])
    z = convert_float(element.attrib["z"])
    return Center(x, y, z)

Methods

def get_attributes(self)

returns the attributes as a dict of the Center

Expand source code
def get_attributes(self):
    """returns the attributes as a dict of the Center"""
    return {"x": str(self.x), "y": str(self.y), "z": str(self.z)}
def get_element(self)

returns the elementTree of the Center

Expand source code
def get_element(self):
    """returns the elementTree of the Center"""
    element = ET.Element("Center", attrib=self.get_attributes())
    return element
class Color (color_type, color_definition)

Creates the Color element in OpenSCENARIO

Parameters

color_type (ColorType): semantic value of color

color_definition (_ColorDefinition): the color definition

Attributes

color_type (ColorType): semantic value of color

color_definition (_ColorDefinition): the color definition

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element(elementname)
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalzie the Color Class

Parameters

color_type (ColorType): semantic value of color

color_definition (ColorRGB or ColorCmyk): the color definition
Expand source code
class Color(VersionBase):
    """Creates the Color element in OpenSCENARIO

    Parameters
    ----------
        color_type (ColorType): semantic value of color

        color_definition (_ColorDefinition): the color definition

    Attributes
    ----------
        color_type (ColorType): semantic value of color

        color_definition (_ColorDefinition): the color definition

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, color_type, color_definition):
        """initalzie the Color Class

        Parameters
        ----------
            color_type (ColorType): semantic value of color

            color_definition (ColorRGB or ColorCmyk): the color definition

        """
        self.color_type = convert_enum(color_type, ColorType, False)
        if not isinstance(color_definition, _ColorDefinition):
            raise TypeError("input is not a color definition")
        self.color_definition = color_definition

    def __eq__(self, other):
        if isinstance(other, Color):
            if (
                self.get_attributes() == other.get_attributes()
                and self.color_definition == other.color_definition
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Color

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

        Returns
        -------
            color (Color): Color object

        """

        color_type = convert_enum(element.attrib["colorType"], ColorType)
        if element.find("ColorRgb") is not None:
            color_def = ColorRGB.parse(element.find("ColorRgb"))
        elif element.find("ColorCmyk") is not None:
            color_def = ColorCMYK.parse(element.find("ColorCmyk"))
        return Color(color_type, color_def)

    def get_attributes(self):
        """returns the attributes of the Color as a dict"""
        retdict = {}
        retdict["colorType"] = self.color_type.get_name()
        return retdict

    def get_element(self):
        """returns the elementTree of the Color"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError("Color was introduced in OpenSCENARIO V1.2")
        element = ET.Element("Color", attrib=self.get_attributes())
        element.append(self.color_definition.get_element())
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of Color

Parameters

element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

Returns

color (Color): Color object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Color

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

    Returns
    -------
        color (Color): Color object

    """

    color_type = convert_enum(element.attrib["colorType"], ColorType)
    if element.find("ColorRgb") is not None:
        color_def = ColorRGB.parse(element.find("ColorRgb"))
    elif element.find("ColorCmyk") is not None:
        color_def = ColorCMYK.parse(element.find("ColorCmyk"))
    return Color(color_type, color_def)

Methods

def get_attributes(self)

returns the attributes of the Color as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Color as a dict"""
    retdict = {}
    retdict["colorType"] = self.color_type.get_name()
    return retdict
def get_element(self)

returns the elementTree of the Color

Expand source code
def get_element(self):
    """returns the elementTree of the Color"""
    if not self.isVersion(minor=2):
        raise OpenSCENARIOVersionError("Color was introduced in OpenSCENARIO V1.2")
    element = ET.Element("Color", attrib=self.get_attributes())
    element.append(self.color_definition.get_element())
    return element
class ColorCMYK (cyan=0, magenta=0, yellow=0, key=0)

Creates the CMYK Color element in OpenSCENARIO

Parameters

cyan (float): cyan component (0..1)
    Default: 0

magenta (float): magenta component (0..1)
    Default: 0

yellow (float): yellow component (0..1)
    Default: 0

key (float): black component (0..1)
    Default: 0

Attributes

cyan (float): cyan component (0..1)

magenta (float): magenta component (0..1)

yellow (float): yellow component (0..1)

key (float): black component (0..1)

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element(elementname)
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalzie the ColorCMYK Class

Parameters

cyan (float): cyan component (0..1)
    Default: 0

magenta (float): magenta component (0..1)
    Default: 0

yellow (float): yellow component (0..1)
    Default: 0

key (float): black component (0..1)
    Default: 0
Expand source code
class ColorCMYK(_ColorDefinition):
    """Creates the CMYK Color element in OpenSCENARIO

    Parameters
    ----------
        cyan (float): cyan component (0..1)
            Default: 0

        magenta (float): magenta component (0..1)
            Default: 0

        yellow (float): yellow component (0..1)
            Default: 0

        key (float): black component (0..1)
            Default: 0

    Attributes
    ----------
        cyan (float): cyan component (0..1)

        magenta (float): magenta component (0..1)

        yellow (float): yellow component (0..1)

        key (float): black component (0..1)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, cyan=0, magenta=0, yellow=0, key=0):
        """initalzie the ColorCMYK Class

        Parameters
        ----------
            cyan (float): cyan component (0..1)
                Default: 0

            magenta (float): magenta component (0..1)
                Default: 0

            yellow (float): yellow component (0..1)
                Default: 0

            key (float): black component (0..1)
                Default: 0
        """
        self.cyan = cyan
        self.magenta = magenta
        self.yellow = yellow
        self.key = key

    def __eq__(self, other):
        if isinstance(other, ColorCMYK):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of ColorCMYK

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

        Returns
        -------
            color (ColorCMYK): ColorCMYK object

        """

        cyan = element.attrib["cyan"]
        magenta = element.attrib["magenta"]
        yellow = element.attrib["yellow"]
        key = element.attrib["key"]
        return ColorCMYK(cyan, magenta, yellow, key)

    def get_attributes(self):
        """returns the attributes of the ColorCMYK as a dict"""
        retdict = {}
        retdict["cyan"] = str(self.cyan)
        retdict["magenta"] = str(self.magenta)
        retdict["yellow"] = str(self.yellow)
        retdict["key"] = str(self.key)
        return retdict

    def get_element(self):
        """returns the elementTree of the ColorCMYK"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "ColorCMYK was introduced in OpenSCENARIO V1.2"
            )
        element = ET.Element("ColorCmyk", attrib=self.get_attributes())
        return element

Ancestors

  • scenariogeneration.xosc.utils._ColorDefinition
  • VersionBase

Static methods

def parse(element)

Parses the xml element of ColorCMYK

Parameters

element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

Returns

color (ColorCMYK): ColorCMYK object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of ColorCMYK

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

    Returns
    -------
        color (ColorCMYK): ColorCMYK object

    """

    cyan = element.attrib["cyan"]
    magenta = element.attrib["magenta"]
    yellow = element.attrib["yellow"]
    key = element.attrib["key"]
    return ColorCMYK(cyan, magenta, yellow, key)

Methods

def get_attributes(self)

returns the attributes of the ColorCMYK as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the ColorCMYK as a dict"""
    retdict = {}
    retdict["cyan"] = str(self.cyan)
    retdict["magenta"] = str(self.magenta)
    retdict["yellow"] = str(self.yellow)
    retdict["key"] = str(self.key)
    return retdict
def get_element(self)

returns the elementTree of the ColorCMYK

Expand source code
def get_element(self):
    """returns the elementTree of the ColorCMYK"""
    if not self.isVersion(minor=2):
        raise OpenSCENARIOVersionError(
            "ColorCMYK was introduced in OpenSCENARIO V1.2"
        )
    element = ET.Element("ColorCmyk", attrib=self.get_attributes())
    return element
class ColorRGB (red=0, green=0, blue=0)

Creates the RGB Color element in OpenSCENARIO

Parameters

red (float): red component (0..1)
    Default: 0

green (float): green component (0..1)
    Default: 0

blue (float): blue component (0..1)
    Default: 0

Attributes

red (float): red component (0..1)

green (float): green component (0..1)

blue (float): blue component (0..1)

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element(elementname)
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalzie the ColorRGB Class

Parameters

red (float): red component (0..1)
    Default: 0

green (float): green component (0..1)
    Default: 0

blue (float): blue component (0..1)
    Default: 0
Expand source code
class ColorRGB(_ColorDefinition):
    """Creates the RGB Color element in OpenSCENARIO

    Parameters
    ----------
        red (float): red component (0..1)
            Default: 0

        green (float): green component (0..1)
            Default: 0

        blue (float): blue component (0..1)
            Default: 0


    Attributes
    ----------
        red (float): red component (0..1)

        green (float): green component (0..1)

        blue (float): blue component (0..1)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, red=0, green=0, blue=0):
        """initalzie the ColorRGB Class

        Parameters
        ----------
            red (float): red component (0..1)
                Default: 0

            green (float): green component (0..1)
                Default: 0

            blue (float): blue component (0..1)
                Default: 0
        """
        self.red = red
        self.green = green
        self.blue = blue

    def __eq__(self, other):
        if isinstance(other, ColorRGB):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of ColorRGB

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

        Returns
        -------
            color (ColorRGB): ColorRGB object

        """

        red = element.attrib["red"]
        green = element.attrib["green"]
        blue = element.attrib["blue"]
        return ColorRGB(red, green, blue)

    def get_attributes(self):
        """returns the attributes of the ValueConstraint as a dict"""
        retdict = {}
        retdict["red"] = str(self.red)
        retdict["green"] = str(self.green)
        retdict["blue"] = str(self.blue)
        return retdict

    def get_element(self):
        """returns the elementTree of the ValueConstraint"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "ColorRGB was introduced in OpenSCENARIO V1.2"
            )
        element = ET.Element("ColorRgb", attrib=self.get_attributes())
        return element

Ancestors

  • scenariogeneration.xosc.utils._ColorDefinition
  • VersionBase

Static methods

def parse(element)

Parses the xml element of ColorRGB

Parameters

element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

Returns

color (ColorRGB): ColorRGB object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of ColorRGB

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

    Returns
    -------
        color (ColorRGB): ColorRGB object

    """

    red = element.attrib["red"]
    green = element.attrib["green"]
    blue = element.attrib["blue"]
    return ColorRGB(red, green, blue)

Methods

def get_attributes(self)

returns the attributes of the ValueConstraint as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the ValueConstraint as a dict"""
    retdict = {}
    retdict["red"] = str(self.red)
    retdict["green"] = str(self.green)
    retdict["blue"] = str(self.blue)
    return retdict
def get_element(self)

returns the elementTree of the ValueConstraint

Expand source code
def get_element(self):
    """returns the elementTree of the ValueConstraint"""
    if not self.isVersion(minor=2):
        raise OpenSCENARIOVersionError(
            "ColorRGB was introduced in OpenSCENARIO V1.2"
        )
    element = ET.Element("ColorRgb", attrib=self.get_attributes())
    return element
class Controller (name, properties, controller_type=None)

the Controller class creates a controller of openScenario

Parameters

name (str): name of the object

properties (Properties): properties of the controller

controller_type (ControllerType): controller type (valid from V1.2)
    Default: None

Attributes

parameters (ParameterDeclaration): Parameter declarations of the vehicle

properties (Properties): additional properties of the vehicle

controller_type (ControllerType): controller type

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

add_parameter(parameter)
    adds a parameter declaration to the Controller

append_to_catalog(filename)
    adds the vehicle to an existing catalog

dump_to_catalog(filename,name,description,author)
    crates a new catalog with the vehicle

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalzie the Controller Class

Parameters

name (str): name of the object

properties (Properties): properties of the Controller

controller_type (ControllerType): controller type (valid from V1.2)
    Default: None
Expand source code
class Controller(_BaseCatalog):
    """the Controller class creates a controller of openScenario

    Parameters
    ----------
        name (str): name of the object

        properties (Properties): properties of the controller

        controller_type (ControllerType): controller type (valid from V1.2)
            Default: None

    Attributes
    ----------
        parameters (ParameterDeclaration): Parameter declarations of the vehicle

        properties (Properties): additional properties of the vehicle

        controller_type (ControllerType): controller type
    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        add_parameter(parameter)
            adds a parameter declaration to the Controller

        append_to_catalog(filename)
            adds the vehicle to an existing catalog

        dump_to_catalog(filename,name,description,author)
            crates a new catalog with the vehicle

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, name, properties, controller_type=None):
        """initalzie the Controller Class

        Parameters
        ----------
            name (str): name of the object

            properties (Properties): properties of the Controller

            controller_type (ControllerType): controller type (valid from V1.2)
                Default: None
        """
        super().__init__()
        self.name = name

        if not isinstance(properties, Properties):
            raise TypeError("properties input is not of type Properties")
        self.properties = properties
        self.controller_type = convert_enum(controller_type, ControllerType, True)

    def __eq__(self, other):
        if isinstance(other, Controller):
            if (
                self.properties == other.properties
                and self.parameters == other.parameters
                and self.name == other.name
                and self.controller_type == other.controller_type
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Controller

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A controller element (same as generated by the class itself)

        Returns
        -------
            controller (Controller): a Controller object

        """
        name = element.attrib["name"]
        properties_element = element.find("Properties")
        properties = Properties.parse(properties_element)
        cnt_type = None
        if "controllerType" in element.attrib:
            cnt_type = convert_enum(
                element.attrib["controllerType"], ControllerType, False
            )
        controller = Controller(name, properties, cnt_type)

        parameters_element = element.find("ParameterDeclarations")
        if parameters_element:
            controller.parameters = ParameterDeclarations.parse(parameters_element)

        return controller

    def get_attributes(self):
        """returns the attributes of the Controller as a dict"""
        retdict = {"name": self.name}
        if self.controller_type:
            if self.isVersion(minor=2):
                retdict["controllerType"] = self.controller_type.get_name()
            else:
                raise OpenSCENARIOVersionError(
                    "controllerType was introduced in OSC v1.2"
                )

        return retdict

    def get_element(self):
        """returns the elementTree of the Controller"""
        element = ET.Element("Controller", attrib=self.get_attributes())
        self.add_parameters_to_element(element)
        element.append(self.properties.get_element())

        return element

Ancestors

  • scenariogeneration.xosc.utils._BaseCatalog
  • VersionBase

Static methods

def parse(element)

Parses the xml element of Controller

Parameters

element (xml.etree.ElementTree.Element): A controller element (same as generated by the class itself)

Returns

controller (Controller): a Controller object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Controller

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A controller element (same as generated by the class itself)

    Returns
    -------
        controller (Controller): a Controller object

    """
    name = element.attrib["name"]
    properties_element = element.find("Properties")
    properties = Properties.parse(properties_element)
    cnt_type = None
    if "controllerType" in element.attrib:
        cnt_type = convert_enum(
            element.attrib["controllerType"], ControllerType, False
        )
    controller = Controller(name, properties, cnt_type)

    parameters_element = element.find("ParameterDeclarations")
    if parameters_element:
        controller.parameters = ParameterDeclarations.parse(parameters_element)

    return controller

Methods

def get_attributes(self)

returns the attributes of the Controller as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Controller as a dict"""
    retdict = {"name": self.name}
    if self.controller_type:
        if self.isVersion(minor=2):
            retdict["controllerType"] = self.controller_type.get_name()
        else:
            raise OpenSCENARIOVersionError(
                "controllerType was introduced in OSC v1.2"
            )

    return retdict
def get_element(self)

returns the elementTree of the Controller

Expand source code
def get_element(self):
    """returns the elementTree of the Controller"""
    element = ET.Element("Controller", attrib=self.get_attributes())
    self.add_parameters_to_element(element)
    element.append(self.properties.get_element())

    return element
class Dimensions (width, length, height)

the Dimensions describes the size of an entity

Parameters

width (float): the width of the entity

length (float): the lenght of the entity

height (float): the height of the entity

Attributes

width (float): the width of the entity

length (float): the lenght of the entity

height (float): the height of the entity

Methods

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

parse(element)
    parses a ElementTree created by the class and returns an instance of the class itself

initalzie the Dimensions

Parameters

width (float): the width of the entity

length (float): the lenght of the entity

height (float): the height of the entity
Expand source code
class Dimensions(VersionBase):
    """the Dimensions describes the size of an entity

    Parameters
    ----------
        width (float): the width of the entity

        length (float): the lenght of the entity

        height (float): the height of the entity


    Attributes
    ----------
        width (float): the width of the entity

        length (float): the lenght of the entity

        height (float): the height of the entity

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class itself

    """

    def __init__(self, width, length, height):
        """initalzie the Dimensions

        Parameters
        ----------
            width (float): the width of the entity

            length (float): the lenght of the entity

            height (float): the height of the entity

        """
        self.width = convert_float(width)
        self.length = convert_float(length)
        self.height = convert_float(height)

    @staticmethod
    def parse(element):
        """Parses the xml element to Dimensions

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A MiscObject element (same as generated by the class itself)

        Returns
        ------
            dimension (Dimensions): a Dimensions object

        """
        width = convert_float(element.attrib["width"])
        height = convert_float(element.attrib["height"])
        length = convert_float(element.attrib["length"])
        return Dimensions(width, length, height)

    def __eq__(self, other):
        if isinstance(other, Dimensions):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    def get_attributes(self):
        """returns the attributes as a dict of the Dimensions"""
        return {
            "width": str(self.width),
            "length": str(self.length),
            "height": str(self.height),
        }

    def get_element(self):
        """returns the elementTree of the Dimensions"""
        element = ET.Element("Dimensions", attrib=self.get_attributes())
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element to Dimensions

Parameters

element (xml.etree.ElementTree.Element): A MiscObject element (same as generated by the class itself)

Returns

dimension (Dimensions): a Dimensions object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element to Dimensions

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A MiscObject element (same as generated by the class itself)

    Returns
    ------
        dimension (Dimensions): a Dimensions object

    """
    width = convert_float(element.attrib["width"])
    height = convert_float(element.attrib["height"])
    length = convert_float(element.attrib["length"])
    return Dimensions(width, length, height)

Methods

def get_attributes(self)

returns the attributes as a dict of the Dimensions

Expand source code
def get_attributes(self):
    """returns the attributes as a dict of the Dimensions"""
    return {
        "width": str(self.width),
        "length": str(self.length),
        "height": str(self.height),
    }
def get_element(self)

returns the elementTree of the Dimensions

Expand source code
def get_element(self):
    """returns the elementTree of the Dimensions"""
    element = ET.Element("Dimensions", attrib=self.get_attributes())
    return element
class DirectionOfTravelDistribution (opposite, same)

The DirectionOfTravelDistribution is used by SwarmTraffic to define how the traffic should flow

Parameters

opposite (float): weight of traffic going against the reference entity

same (float): weight of traffic going the same way the reference entity

Attributes

opposite (float): weight of traffic going against the reference entity

same (float): weight of traffic going the same way the reference entity

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element(elementname)
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalizes the DirectionOfTravelDistribution

Parameters

opposite (float): weight of traffic going against the reference entity

same (float): weight of traffic going the same way the reference entity

Expand source code
class DirectionOfTravelDistribution(VersionBase):
    """The DirectionOfTravelDistribution is used by SwarmTraffic to define how the traffic should flow

    Parameters
    ----------
        opposite (float): weight of traffic going against the reference entity

        same (float): weight of traffic going the same way the reference entity

    Attributes
    ----------

        opposite (float): weight of traffic going against the reference entity

        same (float): weight of traffic going the same way the reference entity

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, opposite, same):
        """initalizes the DirectionOfTravelDistribution

        Parameters
        ----------
        opposite (float): weight of traffic going against the reference entity

        same (float): weight of traffic going the same way the reference entity

        """
        self.opposite = convert_float(opposite)
        self.same = convert_float(same)

    def __eq__(self, other):
        if isinstance(other, DirectionOfTravelDistribution):
            if other.get_attributes() == self.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of a DirectionOfTravelDistribution

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a DirectionOfTravelDistribution element

        Returns
        -------
            DirectionOfTravelDistribution (DirectionOfTravelDistribution): a DirectionOfTravelDistribution object

        """

        return DirectionOfTravelDistribution(
            convert_float(element.attrib["opposite"]),
            convert_float(element.attrib["same"]),
        )

    def get_attributes(self):
        """returns the attributes of the DirectionOfTravelDistribution as a dict"""
        retdict = {"opposite": str(self.opposite), "same": str(self.same)}
        return retdict

    def get_element(self):
        """returns the elementTree of the DirectionOfTravelDistribution"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "DirectionOfTravelDistribution was introduced in OpenSCENARIO V1.2"
            )

        element = ET.Element(
            "DirectionOfTravelDistribution", attrib=self.get_attributes()
        )
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of a DirectionOfTravelDistribution

Parameters

element (xml.etree.ElementTree.Element): a DirectionOfTravelDistribution element

Returns

DirectionOfTravelDistribution (DirectionOfTravelDistribution): a DirectionOfTravelDistribution object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of a DirectionOfTravelDistribution

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): a DirectionOfTravelDistribution element

    Returns
    -------
        DirectionOfTravelDistribution (DirectionOfTravelDistribution): a DirectionOfTravelDistribution object

    """

    return DirectionOfTravelDistribution(
        convert_float(element.attrib["opposite"]),
        convert_float(element.attrib["same"]),
    )

Methods

def get_attributes(self)

returns the attributes of the DirectionOfTravelDistribution as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the DirectionOfTravelDistribution as a dict"""
    retdict = {"opposite": str(self.opposite), "same": str(self.same)}
    return retdict
def get_element(self)

returns the elementTree of the DirectionOfTravelDistribution

Expand source code
def get_element(self):
    """returns the elementTree of the DirectionOfTravelDistribution"""
    if not self.isVersion(minor=2):
        raise OpenSCENARIOVersionError(
            "DirectionOfTravelDistribution was introduced in OpenSCENARIO V1.2"
        )

    element = ET.Element(
        "DirectionOfTravelDistribution", attrib=self.get_attributes()
    )
    return element
class DynamicsConstraints (max_acceleration=None, max_deceleration=None, max_speed=None, max_acceleration_rate=None, max_deceleration_rate=None)

DynamicsConstraints is used by triggers

Parameters

max_acceleration (float): maximum acceleration allowed

max_deceleration (float): maximum deceleration allowed

max_speed (float): maximum speed allowed

max_acceleration_rate (float): maximum acceleration rate allowed

max_deceleration_rate (float): maximum deceleration rate allowed

Attributes

max_acceleration (float): maximum acceleration allowed

max_deceleration (float): maximum deceleration allowed

max_speed (float): maximum speed allowed

max_acceleration_rate (float): maximum acceleration rate allowed

max_deceleration_rate (float): maximum deceleration rate allowed

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

is_filled()
    check is any constraints are set

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize DynamicsConstrains

Expand source code
class DynamicsConstraints(VersionBase):
    """DynamicsConstraints is used by triggers

    Parameters
    ----------
        max_acceleration (float): maximum acceleration allowed

        max_deceleration (float): maximum deceleration allowed

        max_speed (float): maximum speed allowed

        max_acceleration_rate (float): maximum acceleration rate allowed

        max_deceleration_rate (float): maximum deceleration rate allowed

    Attributes
    ----------
        max_acceleration (float): maximum acceleration allowed

        max_deceleration (float): maximum deceleration allowed

        max_speed (float): maximum speed allowed

        max_acceleration_rate (float): maximum acceleration rate allowed

        max_deceleration_rate (float): maximum deceleration rate allowed

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        is_filled()
            check is any constraints are set

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(
        self,
        max_acceleration=None,
        max_deceleration=None,
        max_speed=None,
        max_acceleration_rate=None,
        max_deceleration_rate=None,
    ):
        """initalize DynamicsConstrains"""

        self.max_acceleration = convert_float(max_acceleration)
        self.max_deceleration = convert_float(max_deceleration)
        self.max_speed = convert_float(max_speed)
        self.max_acceleration_rate = convert_float(max_acceleration_rate)
        self.max_deceleration_rate = convert_float(max_deceleration_rate)

    @staticmethod
    def parse(element):
        """Parses the xml element of DynamicsConstraints

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A dynamics constraint element (same as generated by the class itself)

        Returns
        -------
            constrains (DynamicsConstrains): a DynamicsConstrains object

        """
        max_acceleration = None
        max_deceleration = None
        max_speed = None
        max_acceleration_rate = None
        max_deceleration_rate = None

        if "maxAcceleration" in element.attrib:
            max_acceleration = convert_float(element.attrib["maxAcceleration"])
        if "maxDeceleration" in element.attrib:
            max_deceleration = convert_float(element.attrib["maxDeceleration"])
        if "maxSpeed" in element.attrib:
            max_speed = convert_float(element.attrib["maxSpeed"])
        if "maxAccelerationRate" in element.attrib:
            max_acceleration_rate = convert_float(element.attrib["maxAccelerationRate"])
        if "maxDecelerationRate" in element.attrib:
            max_deceleration_rate = convert_float(element.attrib["maxDecelerationRate"])

        return DynamicsConstraints(
            max_acceleration,
            max_deceleration,
            max_speed,
            max_acceleration_rate,
            max_deceleration_rate,
        )

    def __eq__(self, other):
        if isinstance(other, DynamicsConstraints):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    def is_filled(self):
        """is_filled check is any constraints are set

        Returns: boolean

        """

        if self.max_acceleration or self.max_deceleration or self.max_speed:
            return True
        else:
            return False

    def get_attributes(self):
        """returns the attributes of the DynamicsConstrains as a dict"""
        retdict = {}
        if self.max_speed is not None:
            retdict["maxSpeed"] = str(self.max_speed)
        if self.max_deceleration is not None:
            retdict["maxDeceleration"] = str(self.max_deceleration)
        if self.max_acceleration is not None:
            retdict["maxAcceleration"] = str(self.max_acceleration)
        if self.max_acceleration_rate is not None:
            if not self.isVersion(minor=2):
                raise OpenSCENARIOVersionError(
                    "maxAccelerationRate was introduced in OpenSCENARIO V1.2"
                )
            retdict["maxAccelerationRate"] = str(self.max_acceleration_rate)
        if self.max_deceleration_rate is not None:
            if not self.isVersion(minor=2):
                raise OpenSCENARIOVersionError(
                    "maxDecelerationRate was introduced in OpenSCENARIO V1.2"
                )
            retdict["maxDecelerationRate"] = str(self.max_deceleration_rate)
        return retdict

    def get_element(self, name="DynamicConstraints"):
        """returns the elementTree of the DynamicsConstrains"""
        return ET.Element(name, attrib=self.get_attributes())

Ancestors

Static methods

def parse(element)

Parses the xml element of DynamicsConstraints

Parameters

element (xml.etree.ElementTree.Element): A dynamics constraint element (same as generated by the class itself)

Returns

constrains (DynamicsConstrains): a DynamicsConstrains object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of DynamicsConstraints

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A dynamics constraint element (same as generated by the class itself)

    Returns
    -------
        constrains (DynamicsConstrains): a DynamicsConstrains object

    """
    max_acceleration = None
    max_deceleration = None
    max_speed = None
    max_acceleration_rate = None
    max_deceleration_rate = None

    if "maxAcceleration" in element.attrib:
        max_acceleration = convert_float(element.attrib["maxAcceleration"])
    if "maxDeceleration" in element.attrib:
        max_deceleration = convert_float(element.attrib["maxDeceleration"])
    if "maxSpeed" in element.attrib:
        max_speed = convert_float(element.attrib["maxSpeed"])
    if "maxAccelerationRate" in element.attrib:
        max_acceleration_rate = convert_float(element.attrib["maxAccelerationRate"])
    if "maxDecelerationRate" in element.attrib:
        max_deceleration_rate = convert_float(element.attrib["maxDecelerationRate"])

    return DynamicsConstraints(
        max_acceleration,
        max_deceleration,
        max_speed,
        max_acceleration_rate,
        max_deceleration_rate,
    )

Methods

def get_attributes(self)

returns the attributes of the DynamicsConstrains as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the DynamicsConstrains as a dict"""
    retdict = {}
    if self.max_speed is not None:
        retdict["maxSpeed"] = str(self.max_speed)
    if self.max_deceleration is not None:
        retdict["maxDeceleration"] = str(self.max_deceleration)
    if self.max_acceleration is not None:
        retdict["maxAcceleration"] = str(self.max_acceleration)
    if self.max_acceleration_rate is not None:
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "maxAccelerationRate was introduced in OpenSCENARIO V1.2"
            )
        retdict["maxAccelerationRate"] = str(self.max_acceleration_rate)
    if self.max_deceleration_rate is not None:
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "maxDecelerationRate was introduced in OpenSCENARIO V1.2"
            )
        retdict["maxDecelerationRate"] = str(self.max_deceleration_rate)
    return retdict
def get_element(self, name='DynamicConstraints')

returns the elementTree of the DynamicsConstrains

Expand source code
def get_element(self, name="DynamicConstraints"):
    """returns the elementTree of the DynamicsConstrains"""
    return ET.Element(name, attrib=self.get_attributes())
def is_filled(self)

is_filled check is any constraints are set

Returns: boolean

Expand source code
def is_filled(self):
    """is_filled check is any constraints are set

    Returns: boolean

    """

    if self.max_acceleration or self.max_deceleration or self.max_speed:
        return True
    else:
        return False
class EntityRef (entity)

EntityRef creates an EntityRef element of openscenario

Parameters

entity (str): name of the entity

Attributes

entity (str): name of the entity

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the EntityRef

Parameters

entity (str): name of the entity
Expand source code
class EntityRef(VersionBase):
    """EntityRef creates an EntityRef element of openscenario

    Parameters
    ----------
        entity (str): name of the entity

    Attributes
    ----------
        entity (str): name of the entity

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, entity):
        """initalize the EntityRef

        Parameters
        ----------
            entity (str): name of the entity

        """
        self.entity = entity

    @staticmethod
    def parse(element):
        """Parses the xml element of EntityRef

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A entityref element (same as generated by the class itself)

        Returns
        -------
            entityref (EntityRef): a EntityRef object

        """
        entity = element.attrib["entityRef"]
        return EntityRef(entity)

    def __eq__(self, other):
        if isinstance(other, EntityRef):
            if self.entity == other.entity:
                return True
        return False

    def get_attributes(self):
        """returns the attributes of the EntityRef as a dict"""
        return {"entityRef": self.entity}

    def get_element(self):
        """returns the elementTree of the EntityRef"""
        return ET.Element("EntityRef", attrib=self.get_attributes())

Ancestors

Static methods

def parse(element)

Parses the xml element of EntityRef

Parameters

element (xml.etree.ElementTree.Element): A entityref element (same as generated by the class itself)

Returns

entityref (EntityRef): a EntityRef object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of EntityRef

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A entityref element (same as generated by the class itself)

    Returns
    -------
        entityref (EntityRef): a EntityRef object

    """
    entity = element.attrib["entityRef"]
    return EntityRef(entity)

Methods

def get_attributes(self)

returns the attributes of the EntityRef as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the EntityRef as a dict"""
    return {"entityRef": self.entity}
def get_element(self)

returns the elementTree of the EntityRef

Expand source code
def get_element(self):
    """returns the elementTree of the EntityRef"""
    return ET.Element("EntityRef", attrib=self.get_attributes())
class Environment (name, timeofday=None, weather=None, roadcondition=None, parameters=None)

The Environment class creates a environment used by Environment

Parameters

name (string): Name of the environment. If used in catalog name is required.

timeofday (TimeOfDay): time of day for the environment

weather (Weather): weather of the environment

roadcondition (RoadCondition): road condition of the environment

parameters (ParameterDeclarations): the parameters to be used in the scenario
    Default: None

Attributes

name (string): Name of the environment. If used in catalog name is required.

timeofday (TimeOfDay): time of day for the environment

weather (Weather): weather of the environment

roadcondition (RoadCondition): road condition of the environment

parameters (ParameterDeclarations): the parameters to be used in the scenario

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

append_to_catalog(filename)
    adds the vehicle to an existing catalog

dump_to_catalog(filename,name,description,author)
    crates a new catalog with the vehicle

get_element()
    Returns the full ElementTree of the class

initalize the Environment

Parameters

name (string): Name of the environment. If used in catalog name is required.

timeofday (TimeOfDay): time of day for the environment

weather (Weather): weather of the environment

roadcondition (RoadCondition): road condition of the environment

parameters (ParameterDeclarations): the parameters to be used in the scenario
    Default: None
Expand source code
class Environment(_BaseCatalog):
    """The Environment class creates a environment used by Environment

    Parameters
    ----------
        name (string): Name of the environment. If used in catalog name is required.

        timeofday (TimeOfDay): time of day for the environment

        weather (Weather): weather of the environment

        roadcondition (RoadCondition): road condition of the environment

        parameters (ParameterDeclarations): the parameters to be used in the scenario
            Default: None

    Attributes
    ----------
        name (string): Name of the environment. If used in catalog name is required.

        timeofday (TimeOfDay): time of day for the environment

        weather (Weather): weather of the environment

        roadcondition (RoadCondition): road condition of the environment

        parameters (ParameterDeclarations): the parameters to be used in the scenario

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        append_to_catalog(filename)
            adds the vehicle to an existing catalog

        dump_to_catalog(filename,name,description,author)
            crates a new catalog with the vehicle

        get_element()
            Returns the full ElementTree of the class

    """

    def __init__(
        self, name, timeofday=None, weather=None, roadcondition=None, parameters=None
    ):
        """initalize the Environment

        Parameters
        ----------
            name (string): Name of the environment. If used in catalog name is required.

            timeofday (TimeOfDay): time of day for the environment

            weather (Weather): weather of the environment

            roadcondition (RoadCondition): road condition of the environment

            parameters (ParameterDeclarations): the parameters to be used in the scenario
                Default: None
        """
        super().__init__()
        self.name = name
        if timeofday is not None and not isinstance(timeofday, TimeOfDay):
            raise TypeError("timeofday input is not of type TimeOfDay")
        if weather is not None and not isinstance(weather, Weather):
            raise TypeError("weather input is not of type Weather")
        if roadcondition is not None and not isinstance(roadcondition, RoadCondition):
            raise TypeError("roadcondition input is not of type RoadCondition")
        if parameters is not None and not isinstance(parameters, ParameterDeclarations):
            raise TypeError("parameters input is not of type ParameterDeclarations")
        self.timeofday = timeofday
        self.weather = weather
        self.roadcondition = roadcondition
        if parameters is not None:
            self.parameters = parameters

    def __eq__(self, other):
        if isinstance(other, Environment):
            if (
                self.get_attributes() == other.get_attributes()
                and self.timeofday == other.timeofday
                and self.weather == other.weather
                and self.roadcondition == other.roadcondition
                and self.parameters == other.parameters
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Environment

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A environment element (same as generated by the class itself)

        Returns
        -------
            environment (Environment): a Environment object

        """
        name = element.attrib["name"]
        parameters = None
        weather = None
        timeofday = None
        roadcondition = None

        if element.find("ParameterDeclarations") != None:
            parameters = ParameterAssignment.parse(element.find("ParamterDeclarations"))
        if element.find("TimeOfDay") != None:
            timeofday = TimeOfDay.parse(element.find("TimeOfDay"))
        if element.find("Weather") != None:
            weather = Weather.parse(element.find("Weather"))
        if element.find("RoadCondition") != None:
            roadcondition = RoadCondition.parse(element.find("RoadCondition"))

        return Environment(name, timeofday, weather, roadcondition, parameters)

    def get_attributes(self):
        """returns the attributes of the Environment as a dict"""
        return {"name": str(self.name)}

    def get_element(self):
        """returns the elementTree of the Environment"""
        element = ET.Element("Environment", attrib=self.get_attributes())
        if self.timeofday:
            element.append(self.timeofday.get_element())
        if self.weather:
            element.append(self.weather.get_element())
        if self.roadcondition:
            element.append(self.roadcondition.get_element())
        self.add_parameters_to_element(element)
        return element

Ancestors

  • scenariogeneration.xosc.utils._BaseCatalog
  • VersionBase

Static methods

def parse(element)

Parses the xml element of Environment

Parameters

element (xml.etree.ElementTree.Element): A environment element (same as generated by the class itself)

Returns

environment (Environment): a Environment object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Environment

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A environment element (same as generated by the class itself)

    Returns
    -------
        environment (Environment): a Environment object

    """
    name = element.attrib["name"]
    parameters = None
    weather = None
    timeofday = None
    roadcondition = None

    if element.find("ParameterDeclarations") != None:
        parameters = ParameterAssignment.parse(element.find("ParamterDeclarations"))
    if element.find("TimeOfDay") != None:
        timeofday = TimeOfDay.parse(element.find("TimeOfDay"))
    if element.find("Weather") != None:
        weather = Weather.parse(element.find("Weather"))
    if element.find("RoadCondition") != None:
        roadcondition = RoadCondition.parse(element.find("RoadCondition"))

    return Environment(name, timeofday, weather, roadcondition, parameters)

Methods

def get_attributes(self)

returns the attributes of the Environment as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Environment as a dict"""
    return {"name": str(self.name)}
def get_element(self)

returns the elementTree of the Environment

Expand source code
def get_element(self):
    """returns the elementTree of the Environment"""
    element = ET.Element("Environment", attrib=self.get_attributes())
    if self.timeofday:
        element.append(self.timeofday.get_element())
    if self.weather:
        element.append(self.weather.get_element())
    if self.roadcondition:
        element.append(self.roadcondition.get_element())
    self.add_parameters_to_element(element)
    return element
class FileHeader (author, description, revMinor=2, license=None, creation_date=None, properties=None)

FileHeader creates the header of the OpenScenario file1

Parameters

name (str): name of the scenario

author (str): the author of the scenario

revMinor (int): the minor revision of the standard
    Default: 2

license (License): license (valid from OpenSCENARIO V1.1)
    Default: None

creation_date (datetime.datetime): optional hardcoded creation date
    Default: datetime.datetime.now() (when actually generating the xml)

properties (Properties): additional info about the scenario
    Default: None

Attributes

name (str): name of the scenario

author (str): the author of the scenario

license (License): license (valid from OpenSCENARIO V1.1)

creation_date (datetime.datetime): optional hardcoded creation date

properties (Properties): additional info about the scenarios

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of FileHeader

get_attributes()
    Returns a dictionary of all attributes of FileHeader

FileHeader creates the header of the OpenScenario file1

Parameters

name (str): name of the scenario

author (str): the author of the scenario

revMinor (int): the minor revision of the standard
    Default: 1

license (License): license (valid from OpenSCENARIO V1.1)
    Default: None

creation_date (datetime.datetime): optional hardcoded creation date
    Default: datetime.datetime.now() (when actually generating the xml)
properties (Properties): additional info about the scenario
    Default: None
Expand source code
class FileHeader(VersionBase):
    """FileHeader creates the header of the OpenScenario file1

    Parameters
    ----------
        name (str): name of the scenario

        author (str): the author of the scenario

        revMinor (int): the minor revision of the standard
            Default: 2

        license (License): license (valid from OpenSCENARIO V1.1)
            Default: None

        creation_date (datetime.datetime): optional hardcoded creation date
            Default: datetime.datetime.now() (when actually generating the xml)

        properties (Properties): additional info about the scenario
            Default: None
    Attributes
    ----------
        name (str): name of the scenario

        author (str): the author of the scenario

        license (License): license (valid from OpenSCENARIO V1.1)

        creation_date (datetime.datetime): optional hardcoded creation date

        properties (Properties): additional info about the scenarios
    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of FileHeader

        get_attributes()
            Returns a dictionary of all attributes of FileHeader

    """

    def __init__(
        self,
        author,
        description,
        revMinor=_MINOR_VERSION,
        license=None,
        creation_date=None,
        properties=None,
    ):
        """FileHeader creates the header of the OpenScenario file1

        Parameters
        ----------
            name (str): name of the scenario

            author (str): the author of the scenario

            revMinor (int): the minor revision of the standard
                Default: 1

            license (License): license (valid from OpenSCENARIO V1.1)
                Default: None

            creation_date (datetime.datetime): optional hardcoded creation date
                Default: datetime.datetime.now() (when actually generating the xml)
            properties (Properties): additional info about the scenario
                Default: None
        """
        self.description = description
        self.author = author
        self._revMajor = 1
        self._revMinor = revMinor
        self.creation_date = creation_date
        self.setVersion(minor=revMinor)
        if license and not isinstance(license, License):
            raise TypeError("license is not of type License")
        self.license = license
        if properties and not isinstance(properties, Properties):
            raise TypeError("properties is not of type Properties")
        self.properties = properties

    def __eq__(self, other):
        if isinstance(other, FileHeader):
            if (
                self.description == other.description
                and self.author == other.author
                and self._revMajor == other._revMajor
                and self._revMinor == other._revMinor
                and self.properties == other.properties
            ):
                # will not compare date, since this will never be the same
                return True
        return False

    # TODO: License handling add_license ???

    @staticmethod
    def parse(element):
        """Parses the xml element of FileHeader

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A file header element (same as generated by the class itself)

        Returns
        -------
            header (FileHeader): a FileHeader object

        """
        author = element.attrib["author"]
        description = element.attrib["description"]
        # revMinor = element.attrib['revMinor']
        # revMajor = element.attrib['revMajor']
        license = None
        if element.find("license") != None:
            license = License.parse(element.find("license"))

        return FileHeader(author=author, description=description, license=license)

    def get_attributes(self):
        """returns the attributes as a dict of the FileHeader"""
        retdict = {
            "description": self.description,
            "author": self.author,
            "revMajor": str(self.version_major),
            "revMinor": str(self.version_minor),
        }
        if self.creation_date != None:
            retdict["date"] = self.creation_date.isoformat()
        else:
            retdict["date"] = dt.datetime.now().isoformat()
        return retdict

    def get_element(self):
        """returns the elementTree of the FileHeader"""
        element = ET.Element("FileHeader", attrib=self.get_attributes())
        if self.license:
            if self.isVersionEqLarger(minor=1):
                element.append(self.license.get_element())
            else:
                raise OpenSCENARIOVersionError(
                    "License in FileHeader was introduced in OSC 1.1"
                )
        if self.properties:
            if self.isVersionEqLarger(minor=2):
                element.append(self.properties.get_element())
            else:
                raise OpenSCENARIOVersionError(
                    "Properties in FileHeader was introduced in OSC 1.2"
                )

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of FileHeader

Parameters

element (xml.etree.ElementTree.Element): A file header element (same as generated by the class itself)

Returns

header (FileHeader): a FileHeader object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of FileHeader

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A file header element (same as generated by the class itself)

    Returns
    -------
        header (FileHeader): a FileHeader object

    """
    author = element.attrib["author"]
    description = element.attrib["description"]
    # revMinor = element.attrib['revMinor']
    # revMajor = element.attrib['revMajor']
    license = None
    if element.find("license") != None:
        license = License.parse(element.find("license"))

    return FileHeader(author=author, description=description, license=license)

Methods

def get_attributes(self)

returns the attributes as a dict of the FileHeader

Expand source code
def get_attributes(self):
    """returns the attributes as a dict of the FileHeader"""
    retdict = {
        "description": self.description,
        "author": self.author,
        "revMajor": str(self.version_major),
        "revMinor": str(self.version_minor),
    }
    if self.creation_date != None:
        retdict["date"] = self.creation_date.isoformat()
    else:
        retdict["date"] = dt.datetime.now().isoformat()
    return retdict
def get_element(self)

returns the elementTree of the FileHeader

Expand source code
def get_element(self):
    """returns the elementTree of the FileHeader"""
    element = ET.Element("FileHeader", attrib=self.get_attributes())
    if self.license:
        if self.isVersionEqLarger(minor=1):
            element.append(self.license.get_element())
        else:
            raise OpenSCENARIOVersionError(
                "License in FileHeader was introduced in OSC 1.1"
            )
    if self.properties:
        if self.isVersionEqLarger(minor=2):
            element.append(self.properties.get_element())
        else:
            raise OpenSCENARIOVersionError(
                "Properties in FileHeader was introduced in OSC 1.2"
            )

    return element
class Fog (visual_range, bounding_box=None)

Fog creates an Fog element used by the Weather element of openscenario

Parameters

visual_range (int): visual range of fog

bounding_box (BoundingBox): bounding box of fog
    Default: None

Attributes

visual_range (int): visual range of fog

bounding_box (BoundingBox): bounding box of fog

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the Fog

Parameters

visual_range (int): visual range of fog

bounding_box (BoundingBox): bounding box of fog
    Default: None
Expand source code
class Fog(VersionBase):
    """Fog creates an Fog element used by the Weather element of openscenario

    Parameters
    ----------
        visual_range (int): visual range of fog

        bounding_box (BoundingBox): bounding box of fog
            Default: None

    Attributes
    ----------
        visual_range (int): visual range of fog

        bounding_box (BoundingBox): bounding box of fog

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, visual_range, bounding_box=None):
        """initalize the Fog

        Parameters
        ----------
            visual_range (int): visual range of fog

            bounding_box (BoundingBox): bounding box of fog
                Default: None

        """

        self.visual_range = visual_range
        if bounding_box and not isinstance(bounding_box, BoundingBox):
            raise TypeError("bounding_box not of type BoundingBox")
        self.bounding_box = bounding_box

    def __eq__(self, other):
        if isinstance(other, Fog):
            if (
                self.get_attributes() == other.get_attributes()
                and self.bounding_box == other.bounding_box
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Fog

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A fog element (same as generated by the class itself)

        Returns
        -------
            fog (Fog): a Fog object

        """

        visual_range = element.attrib["visualRange"]
        bounding_box = None
        if element.find("BoundingBox") != None:
            bounding_box = BoundingBox.parse(element.find("BoundingBox"))

        return Fog(visual_range, bounding_box)

    def get_attributes(self):
        """returns the attributes of the Precipitation as a dict"""
        retdict = {}
        retdict["visualRange"] = str(self.visual_range)

        return retdict

    def get_element(self):
        """returns the elementTree of the Fog"""
        element = ET.Element("Fog", attrib=self.get_attributes())
        if self.bounding_box is not None:
            element.append(self.bounding_box.get_element())

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of Fog

Parameters

element (xml.etree.ElementTree.Element): A fog element (same as generated by the class itself)

Returns

fog (Fog): a Fog object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Fog

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A fog element (same as generated by the class itself)

    Returns
    -------
        fog (Fog): a Fog object

    """

    visual_range = element.attrib["visualRange"]
    bounding_box = None
    if element.find("BoundingBox") != None:
        bounding_box = BoundingBox.parse(element.find("BoundingBox"))

    return Fog(visual_range, bounding_box)

Methods

def get_attributes(self)

returns the attributes of the Precipitation as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Precipitation as a dict"""
    retdict = {}
    retdict["visualRange"] = str(self.visual_range)

    return retdict
def get_element(self)

returns the elementTree of the Fog

Expand source code
def get_element(self):
    """returns the elementTree of the Fog"""
    element = ET.Element("Fog", attrib=self.get_attributes())
    if self.bounding_box is not None:
        element.append(self.bounding_box.get_element())

    return element
class License (name, resource=None, spdxId=None)

License creates the License used by FileHeader in the OpenScenario file (valid from OpenSCENARIO V1.1)

Parameters

name (str): name of the License

resource (str): link to URL
    Default: None

spdxId (str): license identifier
    Default: None

Attributes

name (str): name of the License

resource (str): link to URL

spdxId (str): license identifier

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of FileHeader

get_attributes()
    Returns a dictionary of all attributes of FileHeader

init the License

Parameters

name (str): name of the License

resource (str): link to URL
    Default: None

spdxId (str): license identifier
    Default: None
Expand source code
class License(VersionBase):
    """License creates the License used by FileHeader in the OpenScenario file
    (valid from OpenSCENARIO V1.1)

    Parameters
    ----------
        name (str): name of the License

        resource (str): link to URL
            Default: None

        spdxId (str): license identifier
            Default: None

    Attributes
    ----------
        name (str): name of the License

        resource (str): link to URL

        spdxId (str): license identifier

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of FileHeader

        get_attributes()
            Returns a dictionary of all attributes of FileHeader

    """

    def __init__(self, name, resource=None, spdxId=None):
        """init the License

        Parameters
        ----------
            name (str): name of the License

            resource (str): link to URL
                Default: None

            spdxId (str): license identifier
                Default: None
        """
        self.name = name
        self.resource = resource
        self.spdxId = spdxId

    def __eq__(self, other):
        if isinstance(other, License):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    # TODO: Check Class License test string 0..1 The full license

    @staticmethod
    def parse(element):
        """Parses the xml element of License

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A license element (same as generated by the class itself)

        Returns
        -------
            license (License): a License object

        """
        name = element.attrib["name"]
        resource = None
        if "resource" in element.attrib:
            resource = element.attrib["resource"]
        spdxId = None
        if "spdxId" in element.attrib:
            spdxId = element.attrib["spdxId"]

        return License(name, resource, spdxId)

    def get_attributes(self):
        """returns the attributes as a dict of the License"""
        retdict = {}
        retdict["name"] = self.name
        if self.resource:
            retdict["resource"] = self.resource
        if self.spdxId:
            retdict["spdxId"] = self.spdxId
        return retdict

    def get_element(self):
        """returns the elementTree of the License"""
        if self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "License was introduced in OpenSCENARIO V1.1"
            )
        element = ET.Element("License", attrib=self.get_attributes())

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of License

Parameters

element (xml.etree.ElementTree.Element): A license element (same as generated by the class itself)

Returns

license (License): a License object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of License

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A license element (same as generated by the class itself)

    Returns
    -------
        license (License): a License object

    """
    name = element.attrib["name"]
    resource = None
    if "resource" in element.attrib:
        resource = element.attrib["resource"]
    spdxId = None
    if "spdxId" in element.attrib:
        spdxId = element.attrib["spdxId"]

    return License(name, resource, spdxId)

Methods

def get_attributes(self)

returns the attributes as a dict of the License

Expand source code
def get_attributes(self):
    """returns the attributes as a dict of the License"""
    retdict = {}
    retdict["name"] = self.name
    if self.resource:
        retdict["resource"] = self.resource
    if self.spdxId:
        retdict["spdxId"] = self.spdxId
    return retdict
def get_element(self)

returns the elementTree of the License

Expand source code
def get_element(self):
    """returns the elementTree of the License"""
    if self.isVersion(minor=0):
        raise OpenSCENARIOVersionError(
            "License was introduced in OpenSCENARIO V1.1"
        )
    element = ET.Element("License", attrib=self.get_attributes())

    return element
class Orientation (h=None, p=None, r=None, reference=None)

Orientation describes the angular orientation of an entity

Parameters

h (float): header

p (float): pitch

r (float): roll

reference (ReferenceContext): absolute or relative

Attributes

h (float): header

p (float): pitch

r (float): roll

reference (ReferenceContext): absolute or relative

Methods

is_filled()
    check is any orientations are set

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize Orientation

Parameters

h (float): header

p (float): pitch

r (float): roll

reference (ReferenceContext): absolute or relative
Expand source code
class Orientation(VersionBase):
    """Orientation describes the angular orientation of an entity

    Parameters
    ----------
        h (float): header

        p (float): pitch

        r (float): roll

        reference (ReferenceContext): absolute or relative

    Attributes
    ----------
        h (float): header

        p (float): pitch

        r (float): roll

        reference (ReferenceContext): absolute or relative

    Methods
    -------
        is_filled()
            check is any orientations are set

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, h=None, p=None, r=None, reference=None):
        """initalize Orientation

        Parameters
        ----------
            h (float): header

            p (float): pitch

            r (float): roll

            reference (ReferenceContext): absolute or relative
        """
        self.h = convert_float(h)
        self.p = convert_float(p)
        self.r = convert_float(r)
        self.ref = convert_enum(reference, ReferenceContext, True)

    def __eq__(self, other):
        if isinstance(other, Orientation):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Orientation

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A orientation element (same as generated by the class itself)

        Returns
        -------
            orientation (Orientation): a Orientation object

        """
        h = None
        p = None
        r = None
        reference = None
        if "h" in element.attrib:
            h = convert_float(element.attrib["h"])
        if "p" in element.attrib:
            p = convert_float(element.attrib["p"])
        if "r" in element.attrib:
            r = convert_float(element.attrib["r"])
        if "type" in element.attrib:
            reference_str = element.attrib["type"]
            reference = convert_enum(reference_str, ReferenceContext, False)

        return Orientation(h, p, r, reference)

    def is_filled(self):
        """is_filled check is any orientations are  set

        Returns: boolean

        """
        if (
            self.h is not None
            or self.p is not None
            or self.r is not None
            or self.ref is not None
        ):
            return True
        else:
            return False

    def get_attributes(self):
        """returns the attributes of the Orientation as a dict"""
        retdict = {}
        if self.h is not None:
            retdict["h"] = str(self.h)

        if self.p is not None:
            retdict["p"] = str(self.p)

        if self.r is not None:
            retdict["r"] = str(self.r)

        if self.ref is not None:
            retdict["type"] = self.ref.get_name()

        return retdict

    def get_element(self):
        """returns the elementTree of the Orientation"""
        return ET.Element("Orientation", attrib=self.get_attributes())

Ancestors

Static methods

def parse(element)

Parses the xml element of Orientation

Parameters

element (xml.etree.ElementTree.Element): A orientation element (same as generated by the class itself)

Returns

orientation (Orientation): a Orientation object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Orientation

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A orientation element (same as generated by the class itself)

    Returns
    -------
        orientation (Orientation): a Orientation object

    """
    h = None
    p = None
    r = None
    reference = None
    if "h" in element.attrib:
        h = convert_float(element.attrib["h"])
    if "p" in element.attrib:
        p = convert_float(element.attrib["p"])
    if "r" in element.attrib:
        r = convert_float(element.attrib["r"])
    if "type" in element.attrib:
        reference_str = element.attrib["type"]
        reference = convert_enum(reference_str, ReferenceContext, False)

    return Orientation(h, p, r, reference)

Methods

def get_attributes(self)

returns the attributes of the Orientation as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Orientation as a dict"""
    retdict = {}
    if self.h is not None:
        retdict["h"] = str(self.h)

    if self.p is not None:
        retdict["p"] = str(self.p)

    if self.r is not None:
        retdict["r"] = str(self.r)

    if self.ref is not None:
        retdict["type"] = self.ref.get_name()

    return retdict
def get_element(self)

returns the elementTree of the Orientation

Expand source code
def get_element(self):
    """returns the elementTree of the Orientation"""
    return ET.Element("Orientation", attrib=self.get_attributes())
def is_filled(self)

is_filled check is any orientations are set

Returns: boolean

Expand source code
def is_filled(self):
    """is_filled check is any orientations are  set

    Returns: boolean

    """
    if (
        self.h is not None
        or self.p is not None
        or self.r is not None
        or self.ref is not None
    ):
        return True
    else:
        return False
class Parameter (name, parameter_type, value)

Parameter is a declaration of a ParameterDeclaration for declarations

Parameters

name (str): name of parameter

parameter_type (ParameterType): type of the parameter

value (str): value of the parameter

Attributes

name (str): name of parameter

parameter_type (ParameterType): type of the parameter

value (str): value of the parameter

constraint_group (ValueConstraintGroup) constraint groups to the parameter value

Methods

add_parameter ???

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

add_value_constraint_group(constraint_group)
    adds a value constraint group to the Parameter

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the Parameter

Parameters

name (str): name of parameter

parameter_type (ParameterType): type of the parameter

value (str): value of the parameter
Expand source code
class Parameter(VersionBase):
    """Parameter is a declaration of a ParameterDeclaration for declarations

    Parameters
    ----------
        name (str): name of parameter

        parameter_type (ParameterType): type of the parameter

        value (str): value of the parameter

    Attributes
    ----------
        name (str): name of parameter

        parameter_type (ParameterType): type of the parameter

        value (str): value of the parameter

        constraint_group (ValueConstraintGroup) constraint groups to the parameter value

    Methods
    -------
        add_parameter ???

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        add_value_constraint_group(constraint_group)
            adds a value constraint group to the Parameter

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, name, parameter_type, value):
        """initalize the Parameter

        Parameters
        ----------
            name (str): name of parameter

            parameter_type (ParameterType): type of the parameter

            value (str): value of the parameter

        """
        self.name = name
        self.parameter_type = convert_enum(parameter_type, ParameterType, False)
        if isinstance(value, bool):
            value = get_bool_string(value)
        self.value = value
        self.constraint_groups = []

    def __eq__(self, other):
        if isinstance(other, Parameter):
            if (
                self.get_attributes() == other.get_attributes()
                and self.constraint_groups == other.constraint_groups
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Parameter

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A parameter element (same as generated by the class itself)

        Returns
        -------
            parameter (Parameter): Parameter object

        """
        name = element.attrib["name"]
        value = element.attrib["value"]
        parameter_type = convert_enum(
            element.attrib["parameterType"], ParameterType, False
        )
        parameter = Parameter(name, parameter_type, value)
        constraint_groups = element.findall("ConstraintGroup")
        for constraint_group in constraint_groups:
            parameter.add_value_constraint_group(
                ValueConstraintGroup.parse(constraint_group)
            )
        return parameter

    def add_value_constraint_group(self, constraint_group):
        """adds a value constraint to the value constraint group

        Parameters
        ----------
            constraint_group (ValueConstraintGroup): the value constraint group to be added

        """
        if not isinstance(constraint_group, ValueConstraintGroup):
            raise TypeError(
                "value_conatraint input is not of type ValueConstraintGroup"
            )
        self.constraint_groups.append(constraint_group)
        return self

    def get_attributes(self):
        """returns the attributes of the Parameter as a dict"""
        return {
            "name": self.name,
            "parameterType": self.parameter_type.get_name(),
            "value": str(self.value),
        }

    def get_element(self):
        """returns the elementTree of the Parameter"""
        element = ET.Element("ParameterDeclaration", attrib=self.get_attributes())
        if self.constraint_groups:
            for constraint_group in self.constraint_groups:
                element.append(constraint_group.get_element())
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of Parameter

Parameters

element (xml.etree.ElementTree.Element): A parameter element (same as generated by the class itself)

Returns

parameter (Parameter): Parameter object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Parameter

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A parameter element (same as generated by the class itself)

    Returns
    -------
        parameter (Parameter): Parameter object

    """
    name = element.attrib["name"]
    value = element.attrib["value"]
    parameter_type = convert_enum(
        element.attrib["parameterType"], ParameterType, False
    )
    parameter = Parameter(name, parameter_type, value)
    constraint_groups = element.findall("ConstraintGroup")
    for constraint_group in constraint_groups:
        parameter.add_value_constraint_group(
            ValueConstraintGroup.parse(constraint_group)
        )
    return parameter

Methods

def add_value_constraint_group(self, constraint_group)

adds a value constraint to the value constraint group

Parameters

constraint_group (ValueConstraintGroup): the value constraint group to be added
Expand source code
def add_value_constraint_group(self, constraint_group):
    """adds a value constraint to the value constraint group

    Parameters
    ----------
        constraint_group (ValueConstraintGroup): the value constraint group to be added

    """
    if not isinstance(constraint_group, ValueConstraintGroup):
        raise TypeError(
            "value_conatraint input is not of type ValueConstraintGroup"
        )
    self.constraint_groups.append(constraint_group)
    return self
def get_attributes(self)

returns the attributes of the Parameter as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Parameter as a dict"""
    return {
        "name": self.name,
        "parameterType": self.parameter_type.get_name(),
        "value": str(self.value),
    }
def get_element(self)

returns the elementTree of the Parameter

Expand source code
def get_element(self):
    """returns the elementTree of the Parameter"""
    element = ET.Element("ParameterDeclaration", attrib=self.get_attributes())
    if self.constraint_groups:
        for constraint_group in self.constraint_groups:
            element.append(constraint_group.get_element())
    return element
class ParameterAssignment (parameterref, value)

ParameterAssignment creates an ParameterAssignment element of openscenario

Parameters

parameterref (str): name of the parameter

value (str): assigned value of the parameter

Attributes

parameterref (str): name of the parameter

value (str): assigned value of the parameter

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the ParameterAssignment

Parameters

parameterref (str): name of the parameter

value (str): assigned value of the parameter
Expand source code
class ParameterAssignment(VersionBase):
    """ParameterAssignment creates an ParameterAssignment element of openscenario

    Parameters
    ----------
        parameterref (str): name of the parameter

        value (str): assigned value of the parameter


    Attributes
    ----------
        parameterref (str): name of the parameter

        value (str): assigned value of the parameter

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, parameterref, value):
        """initalize the ParameterAssignment

        Parameters
        ----------
            parameterref (str): name of the parameter

            value (str): assigned value of the parameter

        """
        self.parameterref = parameterref
        self.value = value

    def __eq__(self, other):
        if isinstance(other, ParameterAssignment):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of ParameterAssignment

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A parameter assignment element (same as generated by the class itself)

        Returns
        -------
            parameterassignment (ParameterAssignment): a ParameterAssignment object

        """

        value = element.attrib["value"]
        parameterref = element.attrib["parameterRef"]

        return ParameterAssignment(parameterref, value)

    def get_attributes(self):
        """returns the attributes of the ParameterAssignment as a dict"""
        retdict = {}
        retdict["parameterRef"] = self.parameterref
        retdict["value"] = str(self.value)
        return retdict

    def get_element(self):
        """returns the elementTree of the ParameterAssignment"""
        return ET.Element("ParameterAssignment", attrib=self.get_attributes())

Ancestors

Static methods

def parse(element)

Parses the xml element of ParameterAssignment

Parameters

element (xml.etree.ElementTree.Element): A parameter assignment element (same as generated by the class itself)

Returns

parameterassignment (ParameterAssignment): a ParameterAssignment object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of ParameterAssignment

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A parameter assignment element (same as generated by the class itself)

    Returns
    -------
        parameterassignment (ParameterAssignment): a ParameterAssignment object

    """

    value = element.attrib["value"]
    parameterref = element.attrib["parameterRef"]

    return ParameterAssignment(parameterref, value)

Methods

def get_attributes(self)

returns the attributes of the ParameterAssignment as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the ParameterAssignment as a dict"""
    retdict = {}
    retdict["parameterRef"] = self.parameterref
    retdict["value"] = str(self.value)
    return retdict
def get_element(self)

returns the elementTree of the ParameterAssignment

Expand source code
def get_element(self):
    """returns the elementTree of the ParameterAssignment"""
    return ET.Element("ParameterAssignment", attrib=self.get_attributes())
class ParameterDeclarations

The ParameterDeclarations class creates the ParameterDeclaration of OpenScenario

Attributes

parameters: list of Parameter objects

Methods

get_element()
    Returns the full ElementTree of the class

add_parameter(Parameter)
    adds a Parameter to the ParameterDeclarations

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

initalizes the ParameterDeclarations

Expand source code
class ParameterDeclarations(VersionBase):
    """The ParameterDeclarations class creates the ParameterDeclaration of OpenScenario

    Attributes
    ----------
        parameters: list of Parameter objects

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

        add_parameter(Parameter)
            adds a Parameter to the ParameterDeclarations

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

    """

    def __init__(self):
        """initalizes the ParameterDeclarations"""
        self.parameters = []

    @staticmethod
    def parse(element):
        """Parses the xml element of ParameterDeclarations

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A parameterdeclarations element (same as generated by the class itself)

        Returns
        -------
            parameterdeclaration (ParameterDeclaration): a ParameterDeclarationn object

        """
        parameter_declarations = ParameterDeclarations()
        declarations = element.findall("ParameterDeclaration")
        for declaration in declarations:
            parameter_declaration = Parameter.parse(declaration)
            parameter_declarations.add_parameter(parameter_declaration)
        return parameter_declarations

    def __eq__(self, other):
        if isinstance(other, ParameterDeclarations):
            if self.parameters == other.parameters:
                return True
        return False

    def add_parameter(self, parameter):
        """add_parameter adds a Parameter to the ParameterDeclarations

        Parameters
        ----------
            parameter (Parameter): a new parameter


        """
        if not isinstance(parameter, Parameter):
            raise TypeError("parameter input is not of type Parameter")
        self.parameters.append(parameter)
        return self

    def get_element(self):
        """returns the elementTree of the ParameterDeclarations"""
        if self.parameters:
            element = ET.Element("ParameterDeclarations")
            for p in self.parameters:
                element.append(p.get_element())
            return element

Ancestors

Static methods

def parse(element)

Parses the xml element of ParameterDeclarations

Parameters

element (xml.etree.ElementTree.Element): A parameterdeclarations element (same as generated by the class itself)

Returns

parameterdeclaration (ParameterDeclaration): a ParameterDeclarationn object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of ParameterDeclarations

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A parameterdeclarations element (same as generated by the class itself)

    Returns
    -------
        parameterdeclaration (ParameterDeclaration): a ParameterDeclarationn object

    """
    parameter_declarations = ParameterDeclarations()
    declarations = element.findall("ParameterDeclaration")
    for declaration in declarations:
        parameter_declaration = Parameter.parse(declaration)
        parameter_declarations.add_parameter(parameter_declaration)
    return parameter_declarations

Methods

def add_parameter(self, parameter)

add_parameter adds a Parameter to the ParameterDeclarations

Parameters

parameter (Parameter): a new parameter
Expand source code
def add_parameter(self, parameter):
    """add_parameter adds a Parameter to the ParameterDeclarations

    Parameters
    ----------
        parameter (Parameter): a new parameter


    """
    if not isinstance(parameter, Parameter):
        raise TypeError("parameter input is not of type Parameter")
    self.parameters.append(parameter)
    return self
def get_element(self)

returns the elementTree of the ParameterDeclarations

Expand source code
def get_element(self):
    """returns the elementTree of the ParameterDeclarations"""
    if self.parameters:
        element = ET.Element("ParameterDeclarations")
        for p in self.parameters:
            element.append(p.get_element())
        return element
class PedestrianAnimation (motion=None, animation=None)

The PedestrianAnimation creates a PedestrianAnimation element used by AnimationType

Parameters

motion (PedestrianMotionType): Motion of a pedestrian

userDefinedPedestrianAnimation (str): User defined pedestrian animation

Attributes

motion (PedestrianMotionType): Motion of a pedestrian

userDefinedPedestrianAnimation (str): User defined pedestrian animation

gestures (list of PedestrianGestureTpe): Gestures of a pedestrian

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

add_gesture(gesture)
    Adds a pedestrian gesture to the pedestrian animation

get_element(elementname)
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalizes the PedestrianAnimation

Parameters

motion (PedestrianMotionType): Motion of a pedestrian

userDefinedPedestrianAnimation (str): User defined pedestrian animation

Expand source code
class PedestrianAnimation(_AnimationType):
    """The PedestrianAnimation creates a PedestrianAnimation element used by AnimationType

    Parameters
    ----------
        motion (PedestrianMotionType): Motion of a pedestrian

        userDefinedPedestrianAnimation (str): User defined pedestrian animation

    Attributes
    ----------

        motion (PedestrianMotionType): Motion of a pedestrian

        userDefinedPedestrianAnimation (str): User defined pedestrian animation

        gestures (list of PedestrianGestureTpe): Gestures of a pedestrian

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        add_gesture(gesture)
            Adds a pedestrian gesture to the pedestrian animation

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, motion=None, animation=None):
        """initalizes the PedestrianAnimation

        Parameters
        ----------
        motion (PedestrianMotionType): Motion of a pedestrian

        userDefinedPedestrianAnimation (str): User defined pedestrian animation

        """
        self.motion = convert_enum(motion, PedestrianMotionType, True)
        self.animation = animation
        self.gestures = []

    def __eq__(self, other):
        if isinstance(other, PedestrianAnimation):
            if (
                other.get_attributes() == self.get_attributes()
                and other.gestures == self.gestures
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of a PedestrianAnimation

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a UserDefinedAnimation element

        Returns
        -------
            PedestrianAnimation (PedestrianAnimation): a PedestrianAnimation object

        """
        motion = convert_enum(element.attrib["motion"], PedestrianMotionType)
        animation = element.attrib["userDefinedPedestrianAnimation"]
        pa = PedestrianAnimation(motion, animation)

        for gesture in element.findall("PedestrianGesture"):
            pa.add_gesture(
                convert_enum(gesture.attrib["gesture"], PedestrianGestureType)
            )
        return pa

    def add_gesture(self, gesture):
        """adds a pedestrian gesture to the vehicle

        Parameters
        ----------
            gesture (PedestrianGestureType): A new gesture of the pedestrian

        """
        self.gestures.append(convert_enum(gesture, PedestrianGestureType))
        return self

    def get_attributes(self):
        """returns the attributes of the PedestrianAnimation as a dict"""
        retdict = {}
        retdict["motion"] = self.motion.get_name()
        retdict["userDefinedPedestrianAnimation"] = str(self.animation)
        return retdict

    def get_element(self):
        """returns the elementTree of the PedestrianAnimation"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "PedestrianAnimation was introduced in OpenSCENARIO V1.2"
            )

        element = ET.Element("PedestrianAnimation", attrib=self.get_attributes())
        for gesture in self.gestures:
            ET.SubElement(
                element, "PedestrianGesture", attrib={"gesture": gesture.get_name()}
            )
        return element

Ancestors

  • scenariogeneration.xosc.utils._AnimationType
  • VersionBase

Static methods

def parse(element)

Parses the xml element of a PedestrianAnimation

Parameters

element (xml.etree.ElementTree.Element): a UserDefinedAnimation element

Returns

PedestrianAnimation (PedestrianAnimation): a PedestrianAnimation object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of a PedestrianAnimation

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): a UserDefinedAnimation element

    Returns
    -------
        PedestrianAnimation (PedestrianAnimation): a PedestrianAnimation object

    """
    motion = convert_enum(element.attrib["motion"], PedestrianMotionType)
    animation = element.attrib["userDefinedPedestrianAnimation"]
    pa = PedestrianAnimation(motion, animation)

    for gesture in element.findall("PedestrianGesture"):
        pa.add_gesture(
            convert_enum(gesture.attrib["gesture"], PedestrianGestureType)
        )
    return pa

Methods

def add_gesture(self, gesture)

adds a pedestrian gesture to the vehicle

Parameters

gesture (PedestrianGestureType): A new gesture of the pedestrian
Expand source code
def add_gesture(self, gesture):
    """adds a pedestrian gesture to the vehicle

    Parameters
    ----------
        gesture (PedestrianGestureType): A new gesture of the pedestrian

    """
    self.gestures.append(convert_enum(gesture, PedestrianGestureType))
    return self
def get_attributes(self)

returns the attributes of the PedestrianAnimation as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the PedestrianAnimation as a dict"""
    retdict = {}
    retdict["motion"] = self.motion.get_name()
    retdict["userDefinedPedestrianAnimation"] = str(self.animation)
    return retdict
def get_element(self)

returns the elementTree of the PedestrianAnimation

Expand source code
def get_element(self):
    """returns the elementTree of the PedestrianAnimation"""
    if not self.isVersion(minor=2):
        raise OpenSCENARIOVersionError(
            "PedestrianAnimation was introduced in OpenSCENARIO V1.2"
        )

    element = ET.Element("PedestrianAnimation", attrib=self.get_attributes())
    for gesture in self.gestures:
        ET.SubElement(
            element, "PedestrianGesture", attrib={"gesture": gesture.get_name()}
        )
    return element
class Phase (name, duration, traffic_group_state=None)

crates a Traffic light phase

Parameters

name (str): if of the phase

duration (float): duration of the phase

traffic_group_state (str): state for a group of signals (valid since V1.2)
    Default: None

Attributes

name (str): if of the phase

duration (float): duration of the phase

signalstates (list of _TrafficSignalState): traffic signal states

traffic_group_state (str): state for a group of signals (valid since V1.2)

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

add_stignal_state(signal_id,state)
    add a traffic signal state

initalize the Phase

Parameters

name (str): if of the phase

duration (float): duration of the phase

traffic_group_state (str): state for a group of signals (valid since V1.2)
    Default: None
Expand source code
class Phase(VersionBase):
    """crates a Traffic light phase

    Parameters
    ----------
        name (str): if of the phase

        duration (float): duration of the phase

        traffic_group_state (str): state for a group of signals (valid since V1.2)
            Default: None

    Attributes
    ----------
        name (str): if of the phase

        duration (float): duration of the phase

        signalstates (list of _TrafficSignalState): traffic signal states

        traffic_group_state (str): state for a group of signals (valid since V1.2)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

        add_stignal_state(signal_id,state)
            add a traffic signal state
    """

    def __init__(self, name, duration, traffic_group_state=None):
        """initalize the Phase

        Parameters
        ----------
            name (str): if of the phase

            duration (float): duration of the phase

            traffic_group_state (str): state for a group of signals (valid since V1.2)
                Default: None

        """

        self.name = name
        self.duration = convert_float(duration)
        self.signalstates = []
        self.traffic_group_state = traffic_group_state

    def __eq__(self, other):
        if isinstance(other, Phase):
            if (
                self.get_attributes() == other.get_attributes()
                and self.signalstates == other.signalstates
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Phase

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A phase element (same as generated by the class itself)

        Returns
        -------
            phase (Phase): a Phase object

        """
        duration = convert_float(element.attrib["duration"])
        name = element.attrib["name"]
        group = None
        # NOTE: Misspelling according to standard...
        if element.find("TrafficeSignalGroupState") is not None:
            group = element.find("TrafficeSignalGroupState").attrib["state"]
        phase = Phase(name, duration, group)
        signalstates = element.findall("TrafficSignalState")
        if signalstates != None:
            for signalstate in signalstates:
                traffic_signal_state = _TrafficSignalState.parse(signalstate)
                phase.signalstates.append(traffic_signal_state)
        return phase

    def add_signal_state(self, signal_id, state):
        """Adds a phase of the traffic signal

        Parameters
        ----------
            signal_id (str): id of the traffic signal in the road network

            state (str): state of the signal defined in the road network

        """
        self.signalstates.append(_TrafficSignalState(signal_id, state))
        return self

    def get_attributes(self):
        """returns the attributes of the TrafficSignalController"""
        retdict = {}
        retdict["name"] = self.name
        retdict["duration"] = str(self.duration)
        return retdict

    def get_element(self):
        """returns the elementTree of the Polyline"""
        element = ET.Element("Phase", attrib=self.get_attributes())
        for s in self.signalstates:
            element.append(s.get_element())
        if self.traffic_group_state is not None:
            # NOTE: Misspelling according to standard...
            if self.isVersionEqLess(minor=1):
                raise OpenSCENARIOVersionError(
                    "TrafficSignalGroupStage was added in OSC 1.2."
                )
            ET.SubElement(
                element,
                "TrafficeSignalGroupState",
                attrib={"state": self.traffic_group_state},
            )
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of Phase

Parameters

element (xml.etree.ElementTree.Element): A phase element (same as generated by the class itself)

Returns

phase (Phase): a Phase object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Phase

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A phase element (same as generated by the class itself)

    Returns
    -------
        phase (Phase): a Phase object

    """
    duration = convert_float(element.attrib["duration"])
    name = element.attrib["name"]
    group = None
    # NOTE: Misspelling according to standard...
    if element.find("TrafficeSignalGroupState") is not None:
        group = element.find("TrafficeSignalGroupState").attrib["state"]
    phase = Phase(name, duration, group)
    signalstates = element.findall("TrafficSignalState")
    if signalstates != None:
        for signalstate in signalstates:
            traffic_signal_state = _TrafficSignalState.parse(signalstate)
            phase.signalstates.append(traffic_signal_state)
    return phase

Methods

def add_signal_state(self, signal_id, state)

Adds a phase of the traffic signal

Parameters

signal_id (str): id of the traffic signal in the road network

state (str): state of the signal defined in the road network
Expand source code
def add_signal_state(self, signal_id, state):
    """Adds a phase of the traffic signal

    Parameters
    ----------
        signal_id (str): id of the traffic signal in the road network

        state (str): state of the signal defined in the road network

    """
    self.signalstates.append(_TrafficSignalState(signal_id, state))
    return self
def get_attributes(self)

returns the attributes of the TrafficSignalController

Expand source code
def get_attributes(self):
    """returns the attributes of the TrafficSignalController"""
    retdict = {}
    retdict["name"] = self.name
    retdict["duration"] = str(self.duration)
    return retdict
def get_element(self)

returns the elementTree of the Polyline

Expand source code
def get_element(self):
    """returns the elementTree of the Polyline"""
    element = ET.Element("Phase", attrib=self.get_attributes())
    for s in self.signalstates:
        element.append(s.get_element())
    if self.traffic_group_state is not None:
        # NOTE: Misspelling according to standard...
        if self.isVersionEqLess(minor=1):
            raise OpenSCENARIOVersionError(
                "TrafficSignalGroupStage was added in OSC 1.2."
            )
        ET.SubElement(
            element,
            "TrafficeSignalGroupState",
            attrib={"state": self.traffic_group_state},
        )
    return element
class Precipitation (precipitation, intensity)

Precipitation creates an Precipitation element used by the Weather element of openscenario

Parameters

precipitation (PrecipitationType): dry, rain or snow

intensity (float): intensity of precipitation (0...1)

Attributes

precipitation (PrecipitationType): dry, rain or snow

intensity (float): intensity of precipitation (0...1)

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the Precipitation

Parameters

precipitation (PrecipitationType): dry, rain or snow

intensity (float): intensity of precipitation (0...1)
Expand source code
class Precipitation(VersionBase):
    """Precipitation creates an Precipitation element used by the Weather element of openscenario

    Parameters
    ----------
        precipitation (PrecipitationType): dry, rain or snow

        intensity (float): intensity of precipitation (0...1)

    Attributes
    ----------
        precipitation (PrecipitationType): dry, rain or snow

        intensity (float): intensity of precipitation (0...1)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, precipitation, intensity):
        """initalize the Precipitation

        Parameters
        ----------
            precipitation (PrecipitationType): dry, rain or snow

            intensity (float): intensity of precipitation (0...1)

        """
        self.precipitation = convert_enum(precipitation, PrecipitationType, False)
        self.intensity = convert_float(intensity)

    def __eq__(self, other):
        if isinstance(other, Precipitation):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Precipitation

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A precipitation element (same as generated by the class itself)

        Returns
        -------
            precipitation (Precipitation): a Precipitation object

        """
        intesity = None
        if "precipitationIntensity" in element.attrib:
            intesity = element.attrib["precipitationIntensity"]
        elif "intensity" in element.attrib:
            intesity = element.attrib["intensity"]
        precipitation = convert_enum(
            element.attrib["precipitationType"], PrecipitationType, False
        )

        return Precipitation(precipitation, intesity)

    def get_attributes(self):
        """returns the attributes of the Precipitation as a dict"""
        retdict = {}
        retdict["precipitationType"] = self.precipitation.get_name()
        if self.isVersion(minor=0):
            retdict["intensity"] = str(self.intensity)
        else:
            retdict["precipitationIntensity"] = str(self.intensity)
        return retdict

    def get_element(self):
        """returns the elementTree of the Precipitation"""
        element = ET.Element("Precipitation", attrib=self.get_attributes())

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of Precipitation

Parameters

element (xml.etree.ElementTree.Element): A precipitation element (same as generated by the class itself)

Returns

precipitation (Precipitation): a Precipitation object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Precipitation

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A precipitation element (same as generated by the class itself)

    Returns
    -------
        precipitation (Precipitation): a Precipitation object

    """
    intesity = None
    if "precipitationIntensity" in element.attrib:
        intesity = element.attrib["precipitationIntensity"]
    elif "intensity" in element.attrib:
        intesity = element.attrib["intensity"]
    precipitation = convert_enum(
        element.attrib["precipitationType"], PrecipitationType, False
    )

    return Precipitation(precipitation, intesity)

Methods

def get_attributes(self)

returns the attributes of the Precipitation as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Precipitation as a dict"""
    retdict = {}
    retdict["precipitationType"] = self.precipitation.get_name()
    if self.isVersion(minor=0):
        retdict["intensity"] = str(self.intensity)
    else:
        retdict["precipitationIntensity"] = str(self.intensity)
    return retdict
def get_element(self)

returns the elementTree of the Precipitation

Expand source code
def get_element(self):
    """returns the elementTree of the Precipitation"""
    element = ET.Element("Precipitation", attrib=self.get_attributes())

    return element
class Properties

the Properties contains are for user defined properties of an object

Attributes

files (list of str): arbitrary files with properties

properties (list of tuple(str,str)): properties in name/value pairs

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

add_file(file)
    adds a file with properties

add_property(name,value)
    adds a property pair, with name and value

get_element()
    Returns the full ElementTree of the class

initalzie the Properties

Expand source code
class Properties(VersionBase):
    """the Properties contains are for user defined properties of an object

    Attributes
    ----------
        files (list of str): arbitrary files with properties

        properties (list of tuple(str,str)): properties in name/value pairs

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        add_file(file)
            adds a file with properties

        add_property(name,value)
            adds a property pair, with name and value

        get_element()
            Returns the full ElementTree of the class


    """

    def __init__(self):
        """initalzie the Properties"""
        self.files = []
        self.properties = []

    def __eq__(self, other):
        if isinstance(other, Properties):
            if self.files == other.files and self.properties == other.properties:
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of class Properties:


        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A position element (same as generated by the class itself)

        Returns
        -------
            properties (Properties): a Properties object

        """
        properties = Properties()
        files = element.findall("File")
        if files != None:
            for file in files:
                filepath = file.attrib["filepath"]
                properties.add_file(filepath)
        props = element.findall("Property")
        if props != None:
            for property in props:
                name = property.attrib["name"]
                value = property.attrib["value"]
                properties.add_property(name, value)

        return properties

    def add_file(self, filename):
        """adds a property file

        Parameters
        ----------
            filename (str): name of the file

        """

        self.files.append(filename)
        return self

    def add_property(self, name, value):
        """adds a property pair

        Parameters
        ----------
            name (str): name of the property

            value (str): value of the property

        """
        self.properties.append((name, value))
        return self

    def get_element(self):
        """returns the elementTree of the Properties"""
        element = ET.Element("Properties")
        for p in self.properties:
            ET.SubElement(element, "Property", attrib={"name": p[0], "value": p[1]})
        for f in self.files:
            ET.SubElement(element, "File", attrib={"filepath": f})

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of class Properties:

Parameters

element (xml.etree.ElementTree.Element): A position element (same as generated by the class itself)

Returns

properties (Properties): a Properties object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of class Properties:


    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A position element (same as generated by the class itself)

    Returns
    -------
        properties (Properties): a Properties object

    """
    properties = Properties()
    files = element.findall("File")
    if files != None:
        for file in files:
            filepath = file.attrib["filepath"]
            properties.add_file(filepath)
    props = element.findall("Property")
    if props != None:
        for property in props:
            name = property.attrib["name"]
            value = property.attrib["value"]
            properties.add_property(name, value)

    return properties

Methods

def add_file(self, filename)

adds a property file

Parameters

filename (str): name of the file
Expand source code
def add_file(self, filename):
    """adds a property file

    Parameters
    ----------
        filename (str): name of the file

    """

    self.files.append(filename)
    return self
def add_property(self, name, value)

adds a property pair

Parameters

name (str): name of the property

value (str): value of the property
Expand source code
def add_property(self, name, value):
    """adds a property pair

    Parameters
    ----------
        name (str): name of the property

        value (str): value of the property

    """
    self.properties.append((name, value))
    return self
def get_element(self)

returns the elementTree of the Properties

Expand source code
def get_element(self):
    """returns the elementTree of the Properties"""
    element = ET.Element("Properties")
    for p in self.properties:
        ET.SubElement(element, "Property", attrib={"name": p[0], "value": p[1]})
    for f in self.files:
        ET.SubElement(element, "File", attrib={"filepath": f})

    return element
class RelativeSpeedToMaster (value, speedTargetValueType, steadyState=None)

Parameters

value (float): Relative speed. Unit: m/s.

speedTargetValueType (SpeedTargetValueType): The semantics of the value (delta, offset, factor).

steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Optional final phase of constant (final) speed. (Valid from OpenSCENARIO V1.1)

Attributes

value (float): Relative speed. Unit: m/s.

speedTargetValueType (SpeedTargetValueType): The semantics of the value (delta, offset, factor).

steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Optional final phase of constant (final) speed. (Valid from OpenSCENARIO V1.1)

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class itself

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns the attributes of the class

Parameters

value (float): Relative speed. Unit: m/s.

speedTargetValueType (SpeedTargetValueType): The semantics of the value (delta, offset, factor).

steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Optional final phase of constant (final) speed.
Expand source code
class RelativeSpeedToMaster(VersionBase):
    """
    Parameters
    ----------
        value (float): Relative speed. Unit: m/s.

        speedTargetValueType (SpeedTargetValueType): The semantics of the value (delta, offset, factor).

        steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Optional final phase of constant (final) speed. (Valid from OpenSCENARIO V1.1)

    Attributes
    ----------
        value (float): Relative speed. Unit: m/s.

        speedTargetValueType (SpeedTargetValueType): The semantics of the value (delta, offset, factor).

        steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Optional final phase of constant (final) speed. (Valid from OpenSCENARIO V1.1)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class itself

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns the attributes of the class
    """

    def __init__(self, value, speedTargetValueType, steadyState=None):
        """

        Parameters
        ----------
            value (float): Relative speed. Unit: m/s.

            speedTargetValueType (SpeedTargetValueType): The semantics of the value (delta, offset, factor).

            steadyState (TargetTimeSteadyState / TargetDistanceSteadyState): Optional final phase of constant (final) speed.
        """
        self.value = value
        if steadyState:
            if not (
                isinstance(steadyState, TargetTimeSteadyState)
                or isinstance(steadyState, TargetDistanceSteadyState)
            ):
                raise TypeError(
                    "steadyState input is not an TargetTimeSteadyState or TargetDistanceSteadyState input"
                )
        self.steadyState = steadyState
        self.speedTargetValueType = convert_enum(
            speedTargetValueType, SpeedTargetValueType
        )

    def __eq__(self, other):
        if isinstance(other, RelativeSpeedToMaster):
            if (
                self.get_attributes() == other.get_attributes()
                and self.steadyState == other.steadyState
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element to RelativeSpeedToMaster

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A RelativeSpeedToMaster element (same as generated by the class itself)

        Returns
        ------
            rstm (RelativeSpeedToMaster): a RelativeSpeedToMaster object

        """
        speed_element = element.find("RelativeSpeedToMaster")

        value = speed_element.attrib["value"]
        speedTargetValueType = convert_enum(
            speed_element.attrib["speedTargetValueType"], SpeedTargetValueType
        )
        state = None
        if speed_element.find("TargetDistanceSteadyState") != None:
            state = TargetDistanceSteadyState.parse(
                speed_element.find("TargetDistanceSteadyState")
            )
        elif speed_element.find("TargetTimeSteadyState") != None:
            state = TargetTimeSteadyState.parse(
                speed_element.find("TargetTimeSteadyState")
            )

        return RelativeSpeedToMaster(value, speedTargetValueType, state)

    def get_attributes(self):
        """returns the attributes of the RelativeSpeedToMaster"""
        return {
            "speedTargetValueType": str(self.speedTargetValueType),
            "value": str(self.value),
        }

    def get_element(self):
        """returns the elementTree of the RelativeSpeedToMaster"""
        elementFinalSpeed = ET.Element("FinalSpeed")
        elementRelativeSpeed = ET.SubElement(
            elementFinalSpeed, "RelativeSpeedToMaster", attrib=self.get_attributes()
        )
        if self.steadyState:
            if self.isVersion(minor=0):
                raise OpenSCENARIOVersionError(
                    "steadyState was introduced in OpenSCENARIO V1.1"
                )
            ET.SubElement(
                elementRelativeSpeed,
                self.steadyState.__class__.__name__,
                attrib=self.steadyState.get_attributes(),
            )
        return elementFinalSpeed

Ancestors

Static methods

def parse(element)

Parses the xml element to RelativeSpeedToMaster

Parameters

element (xml.etree.ElementTree.Element): A RelativeSpeedToMaster element (same as generated by the class itself)

Returns

rstm (RelativeSpeedToMaster): a RelativeSpeedToMaster object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element to RelativeSpeedToMaster

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A RelativeSpeedToMaster element (same as generated by the class itself)

    Returns
    ------
        rstm (RelativeSpeedToMaster): a RelativeSpeedToMaster object

    """
    speed_element = element.find("RelativeSpeedToMaster")

    value = speed_element.attrib["value"]
    speedTargetValueType = convert_enum(
        speed_element.attrib["speedTargetValueType"], SpeedTargetValueType
    )
    state = None
    if speed_element.find("TargetDistanceSteadyState") != None:
        state = TargetDistanceSteadyState.parse(
            speed_element.find("TargetDistanceSteadyState")
        )
    elif speed_element.find("TargetTimeSteadyState") != None:
        state = TargetTimeSteadyState.parse(
            speed_element.find("TargetTimeSteadyState")
        )

    return RelativeSpeedToMaster(value, speedTargetValueType, state)

Methods

def get_attributes(self)

returns the attributes of the RelativeSpeedToMaster

Expand source code
def get_attributes(self):
    """returns the attributes of the RelativeSpeedToMaster"""
    return {
        "speedTargetValueType": str(self.speedTargetValueType),
        "value": str(self.value),
    }
def get_element(self)

returns the elementTree of the RelativeSpeedToMaster

Expand source code
def get_element(self):
    """returns the elementTree of the RelativeSpeedToMaster"""
    elementFinalSpeed = ET.Element("FinalSpeed")
    elementRelativeSpeed = ET.SubElement(
        elementFinalSpeed, "RelativeSpeedToMaster", attrib=self.get_attributes()
    )
    if self.steadyState:
        if self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "steadyState was introduced in OpenSCENARIO V1.1"
            )
        ET.SubElement(
            elementRelativeSpeed,
            self.steadyState.__class__.__name__,
            attrib=self.steadyState.get_attributes(),
        )
    return elementFinalSpeed
class RoadCondition (friction_scale_factor, properties=None, wetness=None)

Weather creates an Weather element of openscenario

Parameters

friction_scale_factor (float): scale factor of the friction

properties (Properties): properties of the roadcondition
    Default: None

wetness (Wetness): wetness of the road
    Default: None

Attributes

friction_scale_factor (float): scale factor of the friction

properties (Properties): properties of the roadcondition

wetness (Wetness): wetness of the road

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the Weather

Parameters

friction_scale_factor (float): scale factor of the friction

properties (Properties): properties of the roadcondition
    Default: None

wetness (Wetness): wetness of the road
    Default: None
Expand source code
class RoadCondition(VersionBase):
    """Weather creates an Weather element of openscenario

    Parameters
    ----------
        friction_scale_factor (float): scale factor of the friction

        properties (Properties): properties of the roadcondition
            Default: None

        wetness (Wetness): wetness of the road
            Default: None

    Attributes
    ----------
        friction_scale_factor (float): scale factor of the friction

        properties (Properties): properties of the roadcondition

        wetness (Wetness): wetness of the road

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, friction_scale_factor, properties=None, wetness=None):
        """initalize the Weather

        Parameters
        ----------
            friction_scale_factor (float): scale factor of the friction

            properties (Properties): properties of the roadcondition
                Default: None

            wetness (Wetness): wetness of the road
                Default: None
        """
        self.friction_scale_factor = convert_float(friction_scale_factor)
        if properties is not None and not isinstance(properties, Properties):
            raise TypeError("properties input is not of type Properties")
        self.properties = properties
        self.wetness = convert_enum(wetness, Wetness, True)

    def __eq__(self, other):
        if isinstance(other, RoadCondition):
            if (
                self.get_attributes() == other.get_attributes()
                and self.properties == other.properties
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of RoadCondition

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A road condition element (same as generated by the class itself)

        Returns
        -------
            roadcondition (RoadCondition): a RoadCondition object

        """
        friction_scale_factor = element.attrib["frictionScaleFactor"]

        properties = None
        wetness = None
        if element.find("Properties") != None:
            properties = Properties.parse(element.find("Properties"))
        if "wetness" in element.attrib:
            wetness = convert_enum(element.attrib["wetness"], Wetness, False)
        return RoadCondition(friction_scale_factor, properties, wetness)

    def get_attributes(self):
        """returns the attributes of the RoadCondition as a dict"""
        retdict = {"frictionScaleFactor": str(self.friction_scale_factor)}
        if self.wetness:
            retdict["wetness"] = self.wetness.get_name()
        return retdict

    def get_element(self):
        """returns the elementTree of the RoadCondition"""
        element = ET.Element("RoadCondition", attrib=self.get_attributes())
        if self.properties:
            element.append(self.properties.get_element())
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of RoadCondition

Parameters

element (xml.etree.ElementTree.Element): A road condition element (same as generated by the class itself)

Returns

roadcondition (RoadCondition): a RoadCondition object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of RoadCondition

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A road condition element (same as generated by the class itself)

    Returns
    -------
        roadcondition (RoadCondition): a RoadCondition object

    """
    friction_scale_factor = element.attrib["frictionScaleFactor"]

    properties = None
    wetness = None
    if element.find("Properties") != None:
        properties = Properties.parse(element.find("Properties"))
    if "wetness" in element.attrib:
        wetness = convert_enum(element.attrib["wetness"], Wetness, False)
    return RoadCondition(friction_scale_factor, properties, wetness)

Methods

def get_attributes(self)

returns the attributes of the RoadCondition as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the RoadCondition as a dict"""
    retdict = {"frictionScaleFactor": str(self.friction_scale_factor)}
    if self.wetness:
        retdict["wetness"] = self.wetness.get_name()
    return retdict
def get_element(self)

returns the elementTree of the RoadCondition

Expand source code
def get_element(self):
    """returns the elementTree of the RoadCondition"""
    element = ET.Element("RoadCondition", attrib=self.get_attributes())
    if self.properties:
        element.append(self.properties.get_element())
    return element
class Sun (intensity, azimuth, elevation)

Sun creates an Sun element used by the Weather element of openscenario

Parameters

intensity (float): intensity of the sun (in lux)

azimuth (float): azimuth of the sun 0 north, pi/2 east, pi south, 3/2pi west

elevation (float): sun elevation angle 0 x/y plane, pi/2 zenith

Attributes

intensity (float): intensity of the sun (in lux)

azimuth (float): azimuth of the sun 0 north, pi/2 east, pi south, 3/2pi west

elevation (float): sun elevation angle 0 x/y plane, pi/2 zenith

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the Sun

Parameters

intensity (float): intensity of the sun (in lux)

azimuth (float): azimuth of the sun 0 north, pi/2 east, pi south, 3/2pi west

elevation (float): sun elevation angle 0 x/y plane, pi/2 zenith
Expand source code
class Sun(VersionBase):
    """Sun creates an Sun element used by the Weather element of openscenario

    Parameters
    ----------
        intensity (float): intensity of the sun (in lux)

        azimuth (float): azimuth of the sun 0 north, pi/2 east, pi south, 3/2pi west

        elevation (float): sun elevation angle 0 x/y plane, pi/2 zenith

    Attributes
    ----------
        intensity (float): intensity of the sun (in lux)

        azimuth (float): azimuth of the sun 0 north, pi/2 east, pi south, 3/2pi west

        elevation (float): sun elevation angle 0 x/y plane, pi/2 zenith

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, intensity, azimuth, elevation):
        """initalize the Sun

        Parameters
        ----------
            intensity (float): intensity of the sun (in lux)

            azimuth (float): azimuth of the sun 0 north, pi/2 east, pi south, 3/2pi west

            elevation (float): sun elevation angle 0 x/y plane, pi/2 zenith

        """

        self.azimuth = azimuth
        self.intensity = intensity
        self.elevation = elevation

    def __eq__(self, other):
        if isinstance(other, Sun):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Sun

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A sun element (same as generated by the class itself)

        Returns
        -------
            sun (Sun): a Sun object

        """
        azimuth = element.attrib["azimuth"]
        elevation = element.attrib["elevation"]
        if "intensity" in element.attrib:
            intensity = element.attrib["intensity"]
        else:
            intensity = element.attrib["illuminance"]

        return Sun(intensity, azimuth, elevation)

    def get_attributes(self):
        """returns the attributes of the Precipitation as a dict"""
        retdict = {}
        retdict["azimuth"] = str(self.azimuth)
        if self.isVersion(minor=2):
            retdict["illuminance"] = str(self.intensity)
        else:
            retdict["intensity"] = str(self.intensity)
        retdict["elevation"] = str(self.elevation)
        return retdict

    def get_element(self):
        """returns the elementTree of the Sun"""
        element = ET.Element("Sun", attrib=self.get_attributes())

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of Sun

Parameters

element (xml.etree.ElementTree.Element): A sun element (same as generated by the class itself)

Returns

sun (Sun): a Sun object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Sun

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A sun element (same as generated by the class itself)

    Returns
    -------
        sun (Sun): a Sun object

    """
    azimuth = element.attrib["azimuth"]
    elevation = element.attrib["elevation"]
    if "intensity" in element.attrib:
        intensity = element.attrib["intensity"]
    else:
        intensity = element.attrib["illuminance"]

    return Sun(intensity, azimuth, elevation)

Methods

def get_attributes(self)

returns the attributes of the Precipitation as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Precipitation as a dict"""
    retdict = {}
    retdict["azimuth"] = str(self.azimuth)
    if self.isVersion(minor=2):
        retdict["illuminance"] = str(self.intensity)
    else:
        retdict["intensity"] = str(self.intensity)
    retdict["elevation"] = str(self.elevation)
    return retdict
def get_element(self)

returns the elementTree of the Sun

Expand source code
def get_element(self):
    """returns the elementTree of the Sun"""
    element = ET.Element("Sun", attrib=self.get_attributes())

    return element
class TargetDistanceSteadyState (distance)

the TargetDistanceSteadyState describes a SteadyState of type TargetDistanceSteadyState (Valid from OpenSCENARIO V1.1)

Parameters

distance (float): distance to target for the steady state

Attributes

distance (float): distance to target for the steady state

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

initalzie the TargetDistanceSteadyState

Parameters

distance (float): distance to target for the steady state
Expand source code
class TargetDistanceSteadyState(VersionBase):
    """the TargetDistanceSteadyState describes a SteadyState of type TargetDistanceSteadyState
    (Valid from OpenSCENARIO V1.1)

    Parameters
    ----------
        distance (float): distance to target for the steady state

    Attributes
    ----------
        distance (float): distance to target for the steady state

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

    """

    def __init__(self, distance):
        """initalzie the TargetDistanceSteadyState

        Parameters
        ----------
            distance (float): distance to target for the steady state

        """
        self.distance = distance

    def __eq__(self, other):
        if isinstance(other, TargetDistanceSteadyState):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TargetDistanceSteadyState

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A TargetDistanceSteadyState element (same as generated by the class itself)

        Returns
        -------
            tdss (TargetDistanceSteadyState): a TargetDistanceSteadyState object

        """
        distance = element.attrib["distance"]
        return TargetDistanceSteadyState(distance)

    def get_attributes(self):
        """returns the attributes of the TargetDistanceSteadyState"""
        if self.isVersion(1, 0):
            raise OpenSCENARIOVersionError(
                "TargetDistanceSteadyState was introduced in OpenSCENARIO V1.1"
            )
        return {"distance": str(self.distance)}

    def get_element(self):
        """returns the elementTree of the TargetDistanceSteadyState"""
        if self.isVersion(1, 0):
            raise OpenSCENARIOVersionError(
                "TargetDistanceSteadyState was introduced in OpenSCENARIO V1.1"
            )
        return ET.Element("TargetDistanceSteadyState", attrib=self.get_attributes())

Ancestors

Static methods

def parse(element)

Parses the xml element of TargetDistanceSteadyState

Parameters

element (xml.etree.ElementTree.Element): A TargetDistanceSteadyState element (same as generated by the class itself)

Returns

tdss (TargetDistanceSteadyState): a TargetDistanceSteadyState object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of TargetDistanceSteadyState

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A TargetDistanceSteadyState element (same as generated by the class itself)

    Returns
    -------
        tdss (TargetDistanceSteadyState): a TargetDistanceSteadyState object

    """
    distance = element.attrib["distance"]
    return TargetDistanceSteadyState(distance)

Methods

def get_attributes(self)

returns the attributes of the TargetDistanceSteadyState

Expand source code
def get_attributes(self):
    """returns the attributes of the TargetDistanceSteadyState"""
    if self.isVersion(1, 0):
        raise OpenSCENARIOVersionError(
            "TargetDistanceSteadyState was introduced in OpenSCENARIO V1.1"
        )
    return {"distance": str(self.distance)}
def get_element(self)

returns the elementTree of the TargetDistanceSteadyState

Expand source code
def get_element(self):
    """returns the elementTree of the TargetDistanceSteadyState"""
    if self.isVersion(1, 0):
        raise OpenSCENARIOVersionError(
            "TargetDistanceSteadyState was introduced in OpenSCENARIO V1.1"
        )
    return ET.Element("TargetDistanceSteadyState", attrib=self.get_attributes())
class TargetTimeSteadyState (time_gap)

the TargetTimeSteadyState describes a SteadyState of type TargetTimeSteadyState (Valid from OpenSCENARIO V1.1)

Parameters

time_gap (float): time_gap to target for the steady state

Attributes

time_gap (float): time_gap to target for the steady state

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

initalzie the TargetTimeSteadyState

Parameters

time_gap (float): time_gap to target for the steady state
Expand source code
class TargetTimeSteadyState(VersionBase):
    """the TargetTimeSteadyState describes a SteadyState of type TargetTimeSteadyState
    (Valid from OpenSCENARIO V1.1)

    Parameters
    ----------
        time_gap (float): time_gap to target for the steady state

    Attributes
    ----------
        time_gap (float): time_gap to target for the steady state

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

    """

    def __init__(self, time_gap):
        """initalzie the TargetTimeSteadyState

        Parameters
        ----------
            time_gap (float): time_gap to target for the steady state

        """
        self.time_gap = time_gap

    def __eq__(self, other):
        if isinstance(other, TargetTimeSteadyState):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TargetTimeSteadyState

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A TargetTimeSteadyState element (same as generated by the class itself)

        Returns
        -------
            ttss (TargetTimeSteadyState): a TargetTimeSteadyState object

        """
        time = element.attrib["time"]
        return TargetTimeSteadyState(time)

    def get_attributes(self):
        """returns the attributes of the TargetTimeSteadyState"""
        if self.isVersion(1, 0):
            raise OpenSCENARIOVersionError(
                "TargetTimeSteadyState was introduced in OpenSCENARIO V1.1"
            )
        return {"time": str(self.time_gap)}

    def get_element(self):
        """returns the elementTree of the TargetTimeSteadyState"""
        if self.isVersion(1, 0):
            raise OpenSCENARIOVersionError(
                "TargetTimeSteadyState was introduced in OpenSCENARIO V1.1"
            )
        return ET.Element("TargetTimeSteadyState", attrib=self.get_attributes())

Ancestors

Static methods

def parse(element)

Parses the xml element of TargetTimeSteadyState

Parameters

element (xml.etree.ElementTree.Element): A TargetTimeSteadyState element (same as generated by the class itself)

Returns

ttss (TargetTimeSteadyState): a TargetTimeSteadyState object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of TargetTimeSteadyState

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A TargetTimeSteadyState element (same as generated by the class itself)

    Returns
    -------
        ttss (TargetTimeSteadyState): a TargetTimeSteadyState object

    """
    time = element.attrib["time"]
    return TargetTimeSteadyState(time)

Methods

def get_attributes(self)

returns the attributes of the TargetTimeSteadyState

Expand source code
def get_attributes(self):
    """returns the attributes of the TargetTimeSteadyState"""
    if self.isVersion(1, 0):
        raise OpenSCENARIOVersionError(
            "TargetTimeSteadyState was introduced in OpenSCENARIO V1.1"
        )
    return {"time": str(self.time_gap)}
def get_element(self)

returns the elementTree of the TargetTimeSteadyState

Expand source code
def get_element(self):
    """returns the elementTree of the TargetTimeSteadyState"""
    if self.isVersion(1, 0):
        raise OpenSCENARIOVersionError(
            "TargetTimeSteadyState was introduced in OpenSCENARIO V1.1"
        )
    return ET.Element("TargetTimeSteadyState", attrib=self.get_attributes())
class TimeOfDay (animation, year, month, day, hour, minute, second)

TimeOfDay creates an TimeOfDay element of openscenario

Parameters

animation (bool): if animation should be used

year (int): year

month (int): month

day (int): day

hour (int): hour

minute (int): minute

second (int): second

Attributes

animation (bool): if animation should be used

year (int): year

month (int): month

day (int): day

hour (int): hour

minute (int): minute

second (int): second

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the TimeOfDay

Parameters

animation (bool): if animation should be used

year (int): year

month (int): month

day (int): day

hour (int): hour

minute (int): minute

second (int): second
Expand source code
class TimeOfDay(VersionBase):
    """TimeOfDay creates an TimeOfDay element of openscenario

    Parameters
    ----------
        animation (bool): if animation should be used

        year (int): year

        month (int): month

        day (int): day

        hour (int): hour

        minute (int): minute

        second (int): second

    Attributes
    ----------
        animation (bool): if animation should be used

        year (int): year

        month (int): month

        day (int): day

        hour (int): hour

        minute (int): minute

        second (int): second

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, animation, year, month, day, hour, minute, second):
        """initalize the TimeOfDay

        Parameters
        ----------
            animation (bool): if animation should be used

            year (int): year

            month (int): month

            day (int): day

            hour (int): hour

            minute (int): minute

            second (int): second

        """
        self.animation = convert_bool(animation)
        self.year = year
        self.month = month
        self.day = day
        self.hour = hour
        self.minute = minute
        self.second = second

    def __eq__(self, other):
        if isinstance(other, TimeOfDay):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TimeOfDay

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A time of day element (same as generated by the class itself)

        Returns
        -------
            timeofday (TimeOfDay): a TimeOfDay object
        """
        animation = convert_bool(element.attrib["animation"])
        var = element.attrib["dateTime"]
        year = convert_int(var[0:4])
        month = convert_int(var[5:7])
        day = convert_int(var[8:10])

        hour = convert_int(var[11:13])
        minute = convert_int(var[14:16])
        second = convert_int(var[17:19])

        return TimeOfDay(animation, year, month, day, hour, minute, second)

    def get_attributes(self):
        """returns the attributes of the TimeOfDay as a dict"""
        dt = (
            str(self.year)
            + "-"
            + "{:0>2}".format(self.month)
            + "-"
            + "{:0>2}".format(self.day)
            + "T"
            + "{:0>2}".format(self.hour)
            + ":"
            + "{:0>2}".format(self.minute)
            + ":"
            + "{:0>2}".format(self.second)
        )
        return {"animation": get_bool_string(self.animation), "dateTime": dt}

    def get_element(self):
        """returns the elementTree of the TimeOfDay"""
        return ET.Element("TimeOfDay", attrib=self.get_attributes())

Ancestors

Static methods

def parse(element)

Parses the xml element of TimeOfDay

Parameters

element (xml.etree.ElementTree.Element): A time of day element (same as generated by the class itself)

Returns

timeofday (TimeOfDay): a TimeOfDay object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of TimeOfDay

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A time of day element (same as generated by the class itself)

    Returns
    -------
        timeofday (TimeOfDay): a TimeOfDay object
    """
    animation = convert_bool(element.attrib["animation"])
    var = element.attrib["dateTime"]
    year = convert_int(var[0:4])
    month = convert_int(var[5:7])
    day = convert_int(var[8:10])

    hour = convert_int(var[11:13])
    minute = convert_int(var[14:16])
    second = convert_int(var[17:19])

    return TimeOfDay(animation, year, month, day, hour, minute, second)

Methods

def get_attributes(self)

returns the attributes of the TimeOfDay as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the TimeOfDay as a dict"""
    dt = (
        str(self.year)
        + "-"
        + "{:0>2}".format(self.month)
        + "-"
        + "{:0>2}".format(self.day)
        + "T"
        + "{:0>2}".format(self.hour)
        + ":"
        + "{:0>2}".format(self.minute)
        + ":"
        + "{:0>2}".format(self.second)
    )
    return {"animation": get_bool_string(self.animation), "dateTime": dt}
def get_element(self)

returns the elementTree of the TimeOfDay

Expand source code
def get_element(self):
    """returns the elementTree of the TimeOfDay"""
    return ET.Element("TimeOfDay", attrib=self.get_attributes())
class TimeReference (reference_domain=None, scale=None, offset=None)

the TimeReference class creates a TimeReference,

Parameters

referece_domain (ReferenceContext): absolute or relative time reference (must be combined with scale and offset)
    Default: None

scale (float): scalefactor of the timeings (must be combined with referece_domain and offset)
    Default: None

offset (float): offset for time values (must be combined with referece_domain and scale)
    Default: None

Attributes

referece_domain (ReferenceContext): absolute or relative time reference

scale (float): scalefactor of the timeings

offset (float): offset for time values

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the TimeReference

Parameters

referece_domain (ReferenceContext): absolute or relative time reference (must be combined with scale and offset) Default: None

scale (float): scalefactor of the timeings (must be combined with referece_domain and offset) Default: None

offset (float): offset for time values (must be combined with referece_domain and scale) Default: None

Expand source code
class TimeReference(VersionBase):
    """the TimeReference class creates a TimeReference,

    Parameters
    ----------
        referece_domain (ReferenceContext): absolute or relative time reference (must be combined with scale and offset)
            Default: None

        scale (float): scalefactor of the timeings (must be combined with referece_domain and offset)
            Default: None

        offset (float): offset for time values (must be combined with referece_domain and scale)
            Default: None

    Attributes
    ----------
        referece_domain (ReferenceContext): absolute or relative time reference

        scale (float): scalefactor of the timeings

        offset (float): offset for time values

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, reference_domain=None, scale=None, offset=None):
        """initalize the TimeReference

        Parameters
        ----------
        referece_domain (ReferenceContext): absolute or relative time reference (must be combined with scale and offset)
            Default: None

        scale (float): scalefactor of the timeings (must be combined with referece_domain and offset)
            Default: None

        offset (float): offset for time values (must be combined with referece_domain and scale)
            Default: None

        """
        nones = [reference_domain == None, scale == None, offset == None]
        if sum(nones) == 3:
            self._only_nones = True
        elif sum(nones) == 0:
            self._only_nones = False
        else:
            raise ValueError("missing inputs for time reference")
        self.reference_domain = convert_enum(reference_domain, ReferenceContext, True)
        self.scale = convert_float(scale)
        self.offset = convert_float(offset)

    def __eq__(self, other):
        if isinstance(other, TimeReference):
            if not self._only_nones and not other._only_nones:
                if self.get_attributes() == other.get_attributes():
                    return True
            elif self._only_nones == other._only_nones:
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TimeReference

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A time reference element (same as generated by the class itself)

        Returns
        -------
            timing (TimeReference): a TimeReference object

        """
        if element.find("None") != None:
            return TimeReference()

        timing_element = element.find("Timing")
        scale = None
        offset = None
        reference_domain = None

        if "offset" in timing_element.attrib:
            offset = timing_element.attrib["offset"]
        if "scale" in timing_element.attrib:
            scale = timing_element.attrib["scale"]
        if "domainAbsoluteRelative" in timing_element.attrib:
            reference_domain = convert_enum(
                timing_element.attrib["domainAbsoluteRelative"], ReferenceContext
            )

        return TimeReference(reference_domain, scale, offset)

    def get_attributes(self):
        """returns the attributes of the TimeReference as a dict"""
        retdict = {}
        retdict["domainAbsoluteRelative"] = self.reference_domain.get_name()
        retdict["scale"] = str(self.scale)
        retdict["offset"] = str(self.offset)
        return retdict

    def get_element(self):
        """returns the elementTree of the TimeReference"""

        element = ET.Element("TimeReference")
        if self._only_nones:
            ET.SubElement(element, "None")
        else:
            ET.SubElement(element, "Timing", self.get_attributes())

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of TimeReference

Parameters

element (xml.etree.ElementTree.Element): A time reference element (same as generated by the class itself)

Returns

timing (TimeReference): a TimeReference object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of TimeReference

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A time reference element (same as generated by the class itself)

    Returns
    -------
        timing (TimeReference): a TimeReference object

    """
    if element.find("None") != None:
        return TimeReference()

    timing_element = element.find("Timing")
    scale = None
    offset = None
    reference_domain = None

    if "offset" in timing_element.attrib:
        offset = timing_element.attrib["offset"]
    if "scale" in timing_element.attrib:
        scale = timing_element.attrib["scale"]
    if "domainAbsoluteRelative" in timing_element.attrib:
        reference_domain = convert_enum(
            timing_element.attrib["domainAbsoluteRelative"], ReferenceContext
        )

    return TimeReference(reference_domain, scale, offset)

Methods

def get_attributes(self)

returns the attributes of the TimeReference as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the TimeReference as a dict"""
    retdict = {}
    retdict["domainAbsoluteRelative"] = self.reference_domain.get_name()
    retdict["scale"] = str(self.scale)
    retdict["offset"] = str(self.offset)
    return retdict
def get_element(self)

returns the elementTree of the TimeReference

Expand source code
def get_element(self):
    """returns the elementTree of the TimeReference"""

    element = ET.Element("TimeReference")
    if self._only_nones:
        ET.SubElement(element, "None")
    else:
        ET.SubElement(element, "Timing", self.get_attributes())

    return element
class TrafficDefinition (name)

the TrafficDefinition class creates a TrafficDefinition used by the different TrafficActions

Parameters

name (str): name of the traffic definition

Attributes

name (str): name of the traffic definition

vehicleweights (list of floats): The weights of the vehicle categories (VehicleCategoryDistribution-weight)

vehiclecategories (list of VehicleCategory): the vehicle category ((VehicleCategoryDistribution-category))

controllerweights (list of floats): The weights of the controllers

controllers (list of Controller/CatalogReference): The controllers for the traffic

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

add_vehicle(vehiclecategory,weight)
    Adds a vehicle to the traffic definition

add_controller(controller,weight)
    Adds a controller to the traffic definition

initalize the TrafficDefinition

Parameters

name (str): name of the traffic definition
Expand source code
class TrafficDefinition(VersionBase):
    """the TrafficDefinition class creates a TrafficDefinition used by the different TrafficActions

    Parameters
    ----------
        name (str): name of the traffic definition


    Attributes
    ----------
        name (str): name of the traffic definition

        vehicleweights (list of floats): The weights of the vehicle categories (VehicleCategoryDistribution-weight)

        vehiclecategories (list of VehicleCategory): the vehicle category ((VehicleCategoryDistribution-category))

        controllerweights (list of floats): The weights of the controllers

        controllers (list of Controller/CatalogReference): The controllers for the traffic


    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

        add_vehicle(vehiclecategory,weight)
            Adds a vehicle to the traffic definition

        add_controller(controller,weight)
            Adds a controller to the traffic definition

    """

    def __init__(self, name):
        """initalize the TrafficDefinition

        Parameters
        ----------
            name (str): name of the traffic definition

        """

        self.name = name
        self.vehicleweights = []
        self.vehiclecategories = []
        self.controllerweights = []
        self.controllers = []
        self.vehicle_roles = []
        self.vehicle_roles_weights = []

    def __eq__(self, other):
        if isinstance(other, TrafficDefinition):
            if (
                self.get_attributes() == other.get_attributes()
                and self.vehicleweights == other.vehicleweights
                and self.vehiclecategories == other.vehiclecategories
                and self.controllerweights == other.controllerweights
                and self.controllers == other.controllers
                and self.vehicle_roles == other.vehicle_roles
                and self.vehicle_roles_weights == other.vehicle_roles_weights
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TrafficDefinition

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A traffic definition element (same as generated by the class itself)

        Returns
        -------
            td (TrafficDefinition): a TrafficDefinition object

        """
        name = element.attrib["name"]
        td = TrafficDefinition(name)

        vehicle_distributions = element.find("VehicleCategoryDistribution")
        vehicle_entries = vehicle_distributions.findall(
            "VehicleCategoryDistributionEntry"
        )
        for entry in vehicle_entries:
            weight = convert_float(entry.attrib["weight"])
            category = convert_enum(entry.attrib["category"], VehicleCategory)
            td.add_vehicle(category, weight)

        controller_distributions = element.find("ControllerDistribution")
        controller_entries = controller_distributions.findall(
            "ControllerDistributionEntry"
        )
        for controller_dist in controller_entries:
            weight = convert_float(controller_dist.attrib["weight"])
            if controller_dist.find("Controller"):
                controller = Controller.parse(controller_dist.find("Controller"))
                td.add_controller(controller, weight)
            else:
                catalog_reference = CatalogReference.parse(
                    controller_dist.find("CatalogReference")
                )
                td.add_controller(catalog_reference, weight)

        vehicle_role_distributions = element.find("VehicleRoleDistribution")
        if vehicle_role_distributions is not None:
            for entry in vehicle_role_distributions.findall(
                "VehicleRoleDistributionEntry"
            ):
                td.add_vehicle_role(
                    convert_enum(entry.attrib["role"], Role), entry.attrib["weight"]
                )
        return td

    def add_vehicle(self, vehiclecategory, weight):
        """Adds a vehicle to the traffic distribution

        Parameters
        ----------
            vehiclecategory (VehicleCategory): vehicle category of the entity in the traffic

            weight (float): the corresponding weight for the distribution of the vehicle category

        """
        self.vehiclecategories.append(convert_enum(vehiclecategory, VehicleCategory))
        self.vehicleweights.append(weight)
        return self

    def add_vehicle_role(self, vehicle_role, weight):
        """Adds a vehicle role to a distribution

        Parameters
        ----------
            vehicle_role (Role): add a role to the vehicle role distribution

            weight (float): the weight of that vehicle role
        """
        self.vehicle_roles_weights.append(convert_float(weight))
        self.vehicle_roles.append(convert_enum(vehicle_role, Role))

    def add_controller(self, controller, weight):
        """Adds a controller to the traffic distribution

        Parameters
        ----------
            controller (Controller or CatalogReference): a controller or catalog reference to a controller

            weight (float): the corresponding weight for the controller

        """
        if not (
            isinstance(controller, Controller)
            or isinstance(controller, CatalogReference)
        ):
            raise TypeError(
                "controller input not of type Controller or CatalogReference"
            )
        self.controllers.append(controller)
        self.controllerweights.append(weight)
        return self

    def get_attributes(self):
        """returns the attributes of the TrafficDefinition"""
        retdict = {}
        retdict["name"] = self.name
        return retdict

    def get_element(self):
        """returns the elementTree of the TrafficDefinition"""
        if not self.controllers:
            ValueError("No controllers defined for the TrafficDefinition")
        if not self.vehiclecategories:
            ValueError("No Vehicles defined for the TrafficDefinition")

        element = ET.Element("TrafficDefinition", attrib=self.get_attributes())

        veh_element = ET.SubElement(element, "VehicleCategoryDistribution")
        for i in range(len(self.vehiclecategories)):
            ET.SubElement(
                veh_element,
                "VehicleCategoryDistributionEntry",
                attrib={
                    "category": self.vehiclecategories[i].get_name(),
                    "weight": str(self.vehicleweights[i]),
                },
            )

        cnt_element = ET.SubElement(element, "ControllerDistribution")
        for i in range(len(self.controllers)):
            tmp_controller = ET.SubElement(
                cnt_element,
                "ControllerDistributionEntry",
                attrib={"weight": str(self.controllerweights[i])},
            )
            tmp_controller.append(self.controllers[i].get_element())
        if self.vehicle_roles:
            if self.version_minor < 2:
                raise OpenSCENARIOVersionError(
                    "VehicleRoleDistribution was added in OSC V1.2"
                )
            role_element = ET.SubElement(element, "VehicleRoleDistribution")
            for i in range(len(self.vehicle_roles)):
                ET.SubElement(
                    role_element,
                    "VehicleRoleDistributionEntry",
                    attrib={
                        "role": self.vehicle_roles[i].get_name(),
                        "weight": str(self.vehicle_roles_weights[i]),
                    },
                )
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of TrafficDefinition

Parameters

element (xml.etree.ElementTree.Element): A traffic definition element (same as generated by the class itself)

Returns

td (TrafficDefinition): a TrafficDefinition object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of TrafficDefinition

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A traffic definition element (same as generated by the class itself)

    Returns
    -------
        td (TrafficDefinition): a TrafficDefinition object

    """
    name = element.attrib["name"]
    td = TrafficDefinition(name)

    vehicle_distributions = element.find("VehicleCategoryDistribution")
    vehicle_entries = vehicle_distributions.findall(
        "VehicleCategoryDistributionEntry"
    )
    for entry in vehicle_entries:
        weight = convert_float(entry.attrib["weight"])
        category = convert_enum(entry.attrib["category"], VehicleCategory)
        td.add_vehicle(category, weight)

    controller_distributions = element.find("ControllerDistribution")
    controller_entries = controller_distributions.findall(
        "ControllerDistributionEntry"
    )
    for controller_dist in controller_entries:
        weight = convert_float(controller_dist.attrib["weight"])
        if controller_dist.find("Controller"):
            controller = Controller.parse(controller_dist.find("Controller"))
            td.add_controller(controller, weight)
        else:
            catalog_reference = CatalogReference.parse(
                controller_dist.find("CatalogReference")
            )
            td.add_controller(catalog_reference, weight)

    vehicle_role_distributions = element.find("VehicleRoleDistribution")
    if vehicle_role_distributions is not None:
        for entry in vehicle_role_distributions.findall(
            "VehicleRoleDistributionEntry"
        ):
            td.add_vehicle_role(
                convert_enum(entry.attrib["role"], Role), entry.attrib["weight"]
            )
    return td

Methods

def add_controller(self, controller, weight)

Adds a controller to the traffic distribution

Parameters

controller (Controller or CatalogReference): a controller or catalog reference to a controller

weight (float): the corresponding weight for the controller
Expand source code
def add_controller(self, controller, weight):
    """Adds a controller to the traffic distribution

    Parameters
    ----------
        controller (Controller or CatalogReference): a controller or catalog reference to a controller

        weight (float): the corresponding weight for the controller

    """
    if not (
        isinstance(controller, Controller)
        or isinstance(controller, CatalogReference)
    ):
        raise TypeError(
            "controller input not of type Controller or CatalogReference"
        )
    self.controllers.append(controller)
    self.controllerweights.append(weight)
    return self
def add_vehicle(self, vehiclecategory, weight)

Adds a vehicle to the traffic distribution

Parameters

vehiclecategory (VehicleCategory): vehicle category of the entity in the traffic

weight (float): the corresponding weight for the distribution of the vehicle category
Expand source code
def add_vehicle(self, vehiclecategory, weight):
    """Adds a vehicle to the traffic distribution

    Parameters
    ----------
        vehiclecategory (VehicleCategory): vehicle category of the entity in the traffic

        weight (float): the corresponding weight for the distribution of the vehicle category

    """
    self.vehiclecategories.append(convert_enum(vehiclecategory, VehicleCategory))
    self.vehicleweights.append(weight)
    return self
def add_vehicle_role(self, vehicle_role, weight)

Adds a vehicle role to a distribution

Parameters

vehicle_role (Role): add a role to the vehicle role distribution

weight (float): the weight of that vehicle role
Expand source code
def add_vehicle_role(self, vehicle_role, weight):
    """Adds a vehicle role to a distribution

    Parameters
    ----------
        vehicle_role (Role): add a role to the vehicle role distribution

        weight (float): the weight of that vehicle role
    """
    self.vehicle_roles_weights.append(convert_float(weight))
    self.vehicle_roles.append(convert_enum(vehicle_role, Role))
def get_attributes(self)

returns the attributes of the TrafficDefinition

Expand source code
def get_attributes(self):
    """returns the attributes of the TrafficDefinition"""
    retdict = {}
    retdict["name"] = self.name
    return retdict
def get_element(self)

returns the elementTree of the TrafficDefinition

Expand source code
def get_element(self):
    """returns the elementTree of the TrafficDefinition"""
    if not self.controllers:
        ValueError("No controllers defined for the TrafficDefinition")
    if not self.vehiclecategories:
        ValueError("No Vehicles defined for the TrafficDefinition")

    element = ET.Element("TrafficDefinition", attrib=self.get_attributes())

    veh_element = ET.SubElement(element, "VehicleCategoryDistribution")
    for i in range(len(self.vehiclecategories)):
        ET.SubElement(
            veh_element,
            "VehicleCategoryDistributionEntry",
            attrib={
                "category": self.vehiclecategories[i].get_name(),
                "weight": str(self.vehicleweights[i]),
            },
        )

    cnt_element = ET.SubElement(element, "ControllerDistribution")
    for i in range(len(self.controllers)):
        tmp_controller = ET.SubElement(
            cnt_element,
            "ControllerDistributionEntry",
            attrib={"weight": str(self.controllerweights[i])},
        )
        tmp_controller.append(self.controllers[i].get_element())
    if self.vehicle_roles:
        if self.version_minor < 2:
            raise OpenSCENARIOVersionError(
                "VehicleRoleDistribution was added in OSC V1.2"
            )
        role_element = ET.SubElement(element, "VehicleRoleDistribution")
        for i in range(len(self.vehicle_roles)):
            ET.SubElement(
                role_element,
                "VehicleRoleDistributionEntry",
                attrib={
                    "role": self.vehicle_roles[i].get_name(),
                    "weight": str(self.vehicle_roles_weights[i]),
                },
            )
    return element
class TrafficSignalController (name, delay=None, reference=None)

the TrafficSignalController class creates a polyline of (minimum 2) positions

Parameters

name (str): if of the trafic signal

delay (float): delay of the phase shift
    Default: None

reference (string): id to the controller in the roadnetwork
    Default: None

Attributes

name (str): if of the trafic signal

delay (float): delay of the phase shift
    Default: None
reference (string): id to the controller in the roadnetwork
    Default: None

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

add_phase(Phase)
    add a phase to the trafficsitnal controller

initalize the TrafficSignalController

Parameters

name (str): if of the trafic signal

delay (float): delay of the phase shift
    Default: None

reference (string): id to the controller in the RoadNetwork
    Default: None
Expand source code
class TrafficSignalController(VersionBase):
    """the TrafficSignalController class creates a polyline of (minimum 2) positions

    Parameters
    ----------
        name (str): if of the trafic signal

        delay (float): delay of the phase shift
            Default: None

        reference (string): id to the controller in the roadnetwork
            Default: None

    Attributes
    ----------
        name (str): if of the trafic signal

        delay (float): delay of the phase shift
            Default: None
        reference (string): id to the controller in the roadnetwork
            Default: None

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

        add_phase(Phase)
            add a phase to the trafficsitnal controller
    """

    def __init__(self, name, delay=None, reference=None):
        """initalize the TrafficSignalController

        Parameters
        ----------
            name (str): if of the trafic signal

            delay (float): delay of the phase shift
                Default: None

            reference (string): id to the controller in the RoadNetwork
                Default: None

        """

        self.name = name
        self.delay = delay
        self.reference = reference
        self.phases = []

    def __eq__(self, other):
        if isinstance(other, TrafficSignalController):
            if (
                self.get_attributes() == other.get_attributes()
                and self.phases == other.phases
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TrafficSignalController

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A traffice signal controller element (same as generated by the class itself)

        Returns
        -------
            tsc (TrafficSignalController): a TrafficSignalController object

        """
        name = element.attrib["name"]

        delay = None
        if "delay" in element.attrib:
            delay = element.attrib["delay"]

        reference = None
        if "reference" in element.attrib:
            reference = element.attrib["reference"]

        tsc = TrafficSignalController(name, delay, reference)

        phases = element.findall("Phase")
        if phases != None:
            for phase in phases:
                tsc.phases.append(Phase.parse(phase))

        return tsc

    def add_phase(self, phase):
        """Adds a phase of the traffic signal

        Parameters
        ----------
            phase (Phase): a phase of the trafficsignal

        """
        if not isinstance(phase, Phase):
            raise TypeError("phase input is not of type Phase")
        self.phases.append(phase)
        return self

    def get_attributes(self):
        """returns the attributes of the TrafficSignalController"""
        retdict = {}
        retdict["name"] = self.name
        if self.delay is not None:
            retdict["delay"] = str(self.delay)
        if self.reference:
            retdict["reference"] = self.reference
        return retdict

    def get_element(self):
        """returns the elementTree of the TrafficSignalController"""
        element = ET.Element("TrafficSignalController", attrib=self.get_attributes())
        for ph in self.phases:
            element.append(ph.get_element())
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of TrafficSignalController

Parameters

element (xml.etree.ElementTree.Element): A traffice signal controller element (same as generated by the class itself)

Returns

tsc (TrafficSignalController): a TrafficSignalController object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of TrafficSignalController

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A traffice signal controller element (same as generated by the class itself)

    Returns
    -------
        tsc (TrafficSignalController): a TrafficSignalController object

    """
    name = element.attrib["name"]

    delay = None
    if "delay" in element.attrib:
        delay = element.attrib["delay"]

    reference = None
    if "reference" in element.attrib:
        reference = element.attrib["reference"]

    tsc = TrafficSignalController(name, delay, reference)

    phases = element.findall("Phase")
    if phases != None:
        for phase in phases:
            tsc.phases.append(Phase.parse(phase))

    return tsc

Methods

def add_phase(self, phase)

Adds a phase of the traffic signal

Parameters

phase (Phase): a phase of the trafficsignal
Expand source code
def add_phase(self, phase):
    """Adds a phase of the traffic signal

    Parameters
    ----------
        phase (Phase): a phase of the trafficsignal

    """
    if not isinstance(phase, Phase):
        raise TypeError("phase input is not of type Phase")
    self.phases.append(phase)
    return self
def get_attributes(self)

returns the attributes of the TrafficSignalController

Expand source code
def get_attributes(self):
    """returns the attributes of the TrafficSignalController"""
    retdict = {}
    retdict["name"] = self.name
    if self.delay is not None:
        retdict["delay"] = str(self.delay)
    if self.reference:
        retdict["reference"] = self.reference
    return retdict
def get_element(self)

returns the elementTree of the TrafficSignalController

Expand source code
def get_element(self):
    """returns the elementTree of the TrafficSignalController"""
    element = ET.Element("TrafficSignalController", attrib=self.get_attributes())
    for ph in self.phases:
        element.append(ph.get_element())
    return element
class TransitionDynamics (shape, dimension, value: float, following_mode=None)

TransitionDynamics is used to define how the dynamics of a change

Parameters

shape (DynamicsShapes): shape of the transition

dimension (DynamicsDimension): the dimension of the transition (rate, time or distance)

value (float): the value of the dynamics (time rate or distance)

following_mode (FollowingMode): the following mode of the TransitionDynamics (valid from OSC V1.2)
    Default: None

Attributes

shape (DynamicsShapes): shape of the transition

dimension (DynamicsDimension): the dimension of the transition (rate, time or distance)

value (float): the value of the dynamics (time rate or distance)

following_mode (FollowingMode): the following mode of the TransitionDynamics (valid from OSC V1.2)

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

Parameters

shape (DynamicsShapes): shape of the transition

dimension (DynamicsDimension): the dimension of the transition (rate, time or distance)

value (float): the value of the dynamics (time rate or distance)

following_mode (FollowingMode): the following mode of the TransitionDynamics (valid from OSC V1.2)
    Default: None
Expand source code
class TransitionDynamics(VersionBase):
    """TransitionDynamics is used to define how the dynamics of a change

    Parameters
    ----------
        shape (DynamicsShapes): shape of the transition

        dimension (DynamicsDimension): the dimension of the transition (rate, time or distance)

        value (float): the value of the dynamics (time rate or distance)

        following_mode (FollowingMode): the following mode of the TransitionDynamics (valid from OSC V1.2)
            Default: None

    Attributes
    ----------
        shape (DynamicsShapes): shape of the transition

        dimension (DynamicsDimension): the dimension of the transition (rate, time or distance)

        value (float): the value of the dynamics (time rate or distance)

        following_mode (FollowingMode): the following mode of the TransitionDynamics (valid from OSC V1.2)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, shape, dimension, value: float, following_mode=None):
        """
        Parameters
        ----------
            shape (DynamicsShapes): shape of the transition

            dimension (DynamicsDimension): the dimension of the transition (rate, time or distance)

            value (float): the value of the dynamics (time rate or distance)

            following_mode (FollowingMode): the following mode of the TransitionDynamics (valid from OSC V1.2)
                Default: None
        """

        self.shape = convert_enum(shape, DynamicsShapes, False)
        self.dimension = convert_enum(dimension, DynamicsDimension, False)
        self.value = convert_float(value)
        self.following_mode = convert_enum(following_mode, FollowingMode, True)

    def __eq__(self, other):
        if isinstance(other, TransitionDynamics):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of TransitionDynamics

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A TransitionDynamics element (same as generated by the class itself)

        Returns
        -------
            transitiondynamics (TransitionDynamics): a TransitionDynamics object

        """
        shape = convert_enum(element.attrib["dynamicsShape"], DynamicsShapes)
        dimension = convert_enum(element.attrib["dynamicsDimension"], DynamicsDimension)
        value = convert_float(element.attrib["value"])
        following_mode = None
        if "followingMode" in element.attrib:
            following_mode = convert_enum(
                element.attrib["followingMode"], FollowingMode
            )
        return TransitionDynamics(shape, dimension, value, following_mode)

    def get_attributes(self):
        """returns the attributes of the TransitionDynamics as a dict"""
        retdict = {
            "dynamicsShape": self.shape.get_name(),
            "value": str(self.value),
            "dynamicsDimension": self.dimension.get_name(),
        }
        if self.following_mode is not None:
            retdict["followingMode"] = self.following_mode.get_name()
        return retdict

    def get_element(self, name="TransitionDynamics"):
        """returns the elementTree of the TransitionDynamics"""
        return ET.Element(name, self.get_attributes())

Ancestors

Static methods

def parse(element)

Parses the xml element of TransitionDynamics

Parameters

element (xml.etree.ElementTree.Element): A TransitionDynamics element (same as generated by the class itself)

Returns

transitiondynamics (TransitionDynamics): a TransitionDynamics object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of TransitionDynamics

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A TransitionDynamics element (same as generated by the class itself)

    Returns
    -------
        transitiondynamics (TransitionDynamics): a TransitionDynamics object

    """
    shape = convert_enum(element.attrib["dynamicsShape"], DynamicsShapes)
    dimension = convert_enum(element.attrib["dynamicsDimension"], DynamicsDimension)
    value = convert_float(element.attrib["value"])
    following_mode = None
    if "followingMode" in element.attrib:
        following_mode = convert_enum(
            element.attrib["followingMode"], FollowingMode
        )
    return TransitionDynamics(shape, dimension, value, following_mode)

Methods

def get_attributes(self)

returns the attributes of the TransitionDynamics as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the TransitionDynamics as a dict"""
    retdict = {
        "dynamicsShape": self.shape.get_name(),
        "value": str(self.value),
        "dynamicsDimension": self.dimension.get_name(),
    }
    if self.following_mode is not None:
        retdict["followingMode"] = self.following_mode.get_name()
    return retdict
def get_element(self, name='TransitionDynamics')

returns the elementTree of the TransitionDynamics

Expand source code
def get_element(self, name="TransitionDynamics"):
    """returns the elementTree of the TransitionDynamics"""
    return ET.Element(name, self.get_attributes())
class UserDefinedAnimation (type)

The UserDefinedAnimation creates a UserDefinedAnimation element used by AnimationType

Parameters

userDefinedAnimationType (str): the available user defined animation types are subject of a contract between simulation environment provider and scenario author.

Attributes

userDefinedAnimationType (str): the available user defined animation types are subject of a contract between simulation environment provider and scenario author.

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element(elementname)
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalizes the UserDefinedAnimation

Parameters

userDefinedAnimationType (str): the available user defined animation types are subject of a contract between simulation environment provider and scenario author.

Expand source code
class UserDefinedAnimation(_AnimationType):
    """The UserDefinedAnimation creates a UserDefinedAnimation element used by AnimationType

    Parameters
    ----------
        userDefinedAnimationType (str): the available user defined animation types are subject of a contract between simulation environment provider and scenario author.

    Attributes
    ----------

        userDefinedAnimationType (str): the available user defined animation types are subject of a contract between simulation environment provider and scenario author.

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, type):
        """initalizes the UserDefinedAnimation

        Parameters
        ----------
        userDefinedAnimationType (str): the available user defined animation types are subject of a contract between simulation environment provider and scenario author.

        """
        self.type = type

    def __eq__(self, other):
        if isinstance(other, UserDefinedAnimation):
            if other.get_attributes() == self.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of a UserDefinedAnimation

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a UserDefinedAnimation element

        Returns
        -------
            UserDefinedAnimation (UserDefinedAnimation): a UserDefinedAnimation object

        """

        return UserDefinedAnimation(element.attrib["userDefinedAnimationType"])

    def get_attributes(self):
        """returns the attributes of the UserDefinedAnimation as a dict"""
        retdict = {}
        retdict["userDefinedAnimationType"] = self.type
        return retdict

    def get_element(self):
        """returns the elementTree of the UserDefinedAnimation"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "UserDefinedAnimation was introduced in OpenSCENARIO V1.2"
            )

        element = ET.Element("UserDefinedAnimation", attrib=self.get_attributes())
        return element

Ancestors

  • scenariogeneration.xosc.utils._AnimationType
  • VersionBase

Static methods

def parse(element)

Parses the xml element of a UserDefinedAnimation

Parameters

element (xml.etree.ElementTree.Element): a UserDefinedAnimation element

Returns

UserDefinedAnimation (UserDefinedAnimation): a UserDefinedAnimation object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of a UserDefinedAnimation

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): a UserDefinedAnimation element

    Returns
    -------
        UserDefinedAnimation (UserDefinedAnimation): a UserDefinedAnimation object

    """

    return UserDefinedAnimation(element.attrib["userDefinedAnimationType"])

Methods

def get_attributes(self)

returns the attributes of the UserDefinedAnimation as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the UserDefinedAnimation as a dict"""
    retdict = {}
    retdict["userDefinedAnimationType"] = self.type
    return retdict
def get_element(self)

returns the elementTree of the UserDefinedAnimation

Expand source code
def get_element(self):
    """returns the elementTree of the UserDefinedAnimation"""
    if not self.isVersion(minor=2):
        raise OpenSCENARIOVersionError(
            "UserDefinedAnimation was introduced in OpenSCENARIO V1.2"
        )

    element = ET.Element("UserDefinedAnimation", attrib=self.get_attributes())
    return element
class UserDefinedComponent (type)

The UserDefinedComponent creates a UserDefinedComponent as part of a ComponentAnimation

Parameters

userDefinedComponentType (str): User defined component type.

Attributes

userDefinedComponentType (str): User defined component type.

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element(elementname)
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalizes the UserDefinedComponent

Parameters

userDefinedComponentType (str): User defined component type.

Expand source code
class UserDefinedComponent(_AnimationType):
    """The UserDefinedComponent creates a UserDefinedComponent as part of a ComponentAnimation

    Parameters
    ----------
        userDefinedComponentType (str): User defined component type.

    Attributes
    ----------

        userDefinedComponentType (str): User defined component type.

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class
    """

    def __init__(self, type):
        """initalizes the UserDefinedComponent

        Parameters
        ----------
        userDefinedComponentType (str): User defined component type.

        """
        self.type = type

    def __eq__(self, other):
        if isinstance(other, UserDefinedComponent):
            if other.get_attributes() == self.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of a UserDefinedComponent

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a UserDefinedComponent element

        Returns
        -------
            UserDefinedComponent (UserDefinedComponent): a UserDefinedComponent object

        """

        return UserDefinedComponent(element.attrib["userDefinedComponentType"])

    def get_attributes(self):
        """returns the attributes of the UserDefinedComponent as a dict"""
        retdict = {}
        retdict["userDefinedComponentType"] = self.type
        return retdict

    def get_element(self):
        """returns the elementTree of the UserDefinedComponent"""
        if not self.isVersion(minor=2):
            raise OpenSCENARIOVersionError(
                "UserDefinedComponent was introduced in OpenSCENARIO V1.2"
            )

        element = ET.Element("UserDefinedComponent", attrib=self.get_attributes())
        return element

Ancestors

  • scenariogeneration.xosc.utils._AnimationType
  • VersionBase

Static methods

def parse(element)

Parses the xml element of a UserDefinedComponent

Parameters

element (xml.etree.ElementTree.Element): a UserDefinedComponent element

Returns

UserDefinedComponent (UserDefinedComponent): a UserDefinedComponent object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of a UserDefinedComponent

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): a UserDefinedComponent element

    Returns
    -------
        UserDefinedComponent (UserDefinedComponent): a UserDefinedComponent object

    """

    return UserDefinedComponent(element.attrib["userDefinedComponentType"])

Methods

def get_attributes(self)

returns the attributes of the UserDefinedComponent as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the UserDefinedComponent as a dict"""
    retdict = {}
    retdict["userDefinedComponentType"] = self.type
    return retdict
def get_element(self)

returns the elementTree of the UserDefinedComponent

Expand source code
def get_element(self):
    """returns the elementTree of the UserDefinedComponent"""
    if not self.isVersion(minor=2):
        raise OpenSCENARIOVersionError(
            "UserDefinedComponent was introduced in OpenSCENARIO V1.2"
        )

    element = ET.Element("UserDefinedComponent", attrib=self.get_attributes())
    return element
class UserDefinedLight (user_defined_type)

The CustomCommandAction creates a simulator defined action

Parameters

user_defined_type (str): string of the user defined light

Attributes

type (str): type of the custom command

Methods

get_element()
    Returns the full ElementTree of the class

initalize the UserDefinedLight

Parameters

user_defined_type (str): type of the custom command
Expand source code
class UserDefinedLight(VersionBase):
    """The CustomCommandAction creates a simulator defined action


    Parameters
    ----------
        user_defined_type (str): string of the user defined light

    Attributes
    ----------

        type (str): type of the custom command

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

    """

    def __init__(self, user_defined_type):
        """initalize the UserDefinedLight

        Parameters
        ----------
            user_defined_type (str): type of the custom command

        """
        self.type = user_defined_type

    def __eq__(self, other):
        if isinstance(other, UserDefinedLight):
            if other.type == self.type:
                return True
        return False

    @staticmethod
    def parse(element):
        """Parsese the xml element of a UserDefinedLight

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): a UserDefinedLight element

        Returns
        -------
            UserDefinedLight (UserDefinedLight): a UserDefinedLight object

        """

        return UserDefinedLight(element.attrib["userDefinedLightType"])

    def get_element(self):
        """returns the elementTree of the UserDefinedLight"""
        if self.isVersionEqLess(minor=1):
            raise OpenSCENARIOVersionError("UserDefinedLight was introduced in OSC 1.2")
        element = ET.Element(
            "UserDefinedLight", attrib={"userDefinedLightType": self.type}
        )
        return element

Ancestors

Static methods

def parse(element)

Parsese the xml element of a UserDefinedLight

Parameters

element (xml.etree.ElementTree.Element): a UserDefinedLight element

Returns

UserDefinedLight (UserDefinedLight): a UserDefinedLight object
Expand source code
@staticmethod
def parse(element):
    """Parsese the xml element of a UserDefinedLight

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): a UserDefinedLight element

    Returns
    -------
        UserDefinedLight (UserDefinedLight): a UserDefinedLight object

    """

    return UserDefinedLight(element.attrib["userDefinedLightType"])

Methods

def get_element(self)

returns the elementTree of the UserDefinedLight

Expand source code
def get_element(self):
    """returns the elementTree of the UserDefinedLight"""
    if self.isVersionEqLess(minor=1):
        raise OpenSCENARIOVersionError("UserDefinedLight was introduced in OSC 1.2")
    element = ET.Element(
        "UserDefinedLight", attrib={"userDefinedLightType": self.type}
    )
    return element
class ValueConstraint (rule, value)

Creates the the ValueConstraint file for open scenario

Parameters

rule (Rule): available operators for the validation of the constraint. Note that either "equalTo" or "notEqualTo" must be used in the parameter declaration of type "string"

value (string): a constant value, parameter or parameter expression. The value must match the enclosing parameter declaration.

Attributes

rule (Rule): available operators for the validation of the constraint. Note that either "equalTo" or "notEqualTo" must be used in the parameter declaration of type "string"

value (string): a constant value, parameter or parameter expression. The value must match the enclosing parameter declaration.

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element(elementname)
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalzie the ValueConstraint Class

Parameters

rule (Rule): available operators for the validation of the constraint. Note that either "equalTo" or "notEqualTo" must be used in the parameter declaration of type "string"

value (string): a constant value, parameter or parameter expression. The value must match the enclosing parameter declaration.
Expand source code
class ValueConstraint(VersionBase):
    """Creates the the ValueConstraint file for open scenario

    Parameters
    ----------
        rule (Rule): available operators for the validation of the constraint. Note that either "equalTo" or "notEqualTo" must be used in the parameter declaration of type "string"

        value (string): a constant value, parameter or parameter expression. The value must match the enclosing parameter declaration.

    Attributes
    ----------
        rule (Rule): available operators for the validation of the constraint. Note that either "equalTo" or "notEqualTo" must be used in the parameter declaration of type "string"

        value (string): a constant value, parameter or parameter expression. The value must match the enclosing parameter declaration.


    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    # TODO: Only equalTo and notEqualTo test
    def __init__(self, rule, value):
        """initalzie the ValueConstraint Class

        Parameters
        ----------
            rule (Rule): available operators for the validation of the constraint. Note that either "equalTo" or "notEqualTo" must be used in the parameter declaration of type "string"

            value (string): a constant value, parameter or parameter expression. The value must match the enclosing parameter declaration.
        """
        self.value = value
        self.rule = convert_enum(rule, Rule)

    def __eq__(self, other):
        if isinstance(other, ValueConstraint):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of ValueConstraint

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

        Returns
        -------
            constraint (ValueConstraint): ValueConstraint object

        """
        value = element.attrib["value"]
        rule = convert_enum(element.attrib["rule"], Rule)
        return ValueConstraint(rule, value)

    def get_attributes(self):
        """returns the attributes of the ValueConstraint as a dict"""
        retdict = {}
        retdict["rule"] = self.rule.get_name()
        retdict["value"] = str(self.value)
        return retdict

    def get_element(self):
        """returns the elementTree of the ValueConstraint"""
        if self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "ValueConstraint was introduced in OpenSCENARIO V1.1"
            )
        element = ET.Element("ValueConstraint", attrib=self.get_attributes())
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of ValueConstraint

Parameters

element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

Returns

constraint (ValueConstraint): ValueConstraint object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of ValueConstraint

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A value constraint element (same as generated by the class itself)

    Returns
    -------
        constraint (ValueConstraint): ValueConstraint object

    """
    value = element.attrib["value"]
    rule = convert_enum(element.attrib["rule"], Rule)
    return ValueConstraint(rule, value)

Methods

def get_attributes(self)

returns the attributes of the ValueConstraint as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the ValueConstraint as a dict"""
    retdict = {}
    retdict["rule"] = self.rule.get_name()
    retdict["value"] = str(self.value)
    return retdict
def get_element(self)

returns the elementTree of the ValueConstraint

Expand source code
def get_element(self):
    """returns the elementTree of the ValueConstraint"""
    if self.isVersion(minor=0):
        raise OpenSCENARIOVersionError(
            "ValueConstraint was introduced in OpenSCENARIO V1.1"
        )
    element = ET.Element("ValueConstraint", attrib=self.get_attributes())
    return element
class ValueConstraintGroup

Creates the the ValueConstraintGroup file for open scenario

Parameters

None

Attributes

value_constraint (ValueConstraint): logical constraint, needed to evaluate to true for a defined parameter to start the simulation.

Methods

add_value_constraint(value_constraint)
    adds value constraint to the value constraint group

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element(elementname)
    Returns the full ElementTree of the class
Expand source code
class ValueConstraintGroup(VersionBase):
    """Creates the the ValueConstraintGroup file for open scenario

    Parameters
    ----------
        None

    Attributes
    ----------
        value_constraint (ValueConstraint): logical constraint, needed to evaluate to true for a defined parameter to start the simulation.


    Methods
    -------
        add_value_constraint(value_constraint)
            adds value constraint to the value constraint group

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    def __init__(self):
        self.value_constraints = []

    def __eq__(self, other):
        if isinstance(other, ValueConstraintGroup):
            if self.value_constraints == other.value_constraints:
                return True
        return False

    def add_value_constraint(self, value_constraint):
        """adds a value constraint to the value constraint group

        Parameters
        ----------
            value_constraint (ValueConstraint): the value constraint to be added

        """
        if not isinstance(value_constraint, ValueConstraint):
            raise TypeError("value_conatraint input is not of type ValueConstraint")
        self.value_constraints.append(value_constraint)
        return self

    @staticmethod
    def parse(element):
        """Parses the xml element of ValueConstraintGroup

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A ValueConstraintGroup element (same as generated by the class itself)

        Returns
        -------
            group (ValueConstraintGroup): a ValueConstraintGroup object

        """
        value_constraints = ValueConstraintGroup()
        constraints = element.findall("ValueConstraint")
        for constraint in constraints:
            value_constraint = ValueConstraint.parse(constraint)
            value_constraints.add_value_constraint(value_constraint)
        return value_constraints

    def get_element(self):
        """returns the elementTree of the ValueConstraintGroup"""
        if self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "ValueConstraintGroup was introduced in OpenSCENARIO V1.1"
            )
        element = ET.Element("ConstraintGroup")
        if not self.value_constraints:
            raise ValueError("No Value Constraints in the Value Contraint Group")
        for value_constraint in self.value_constraints:
            element.append(value_constraint.get_element())
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of ValueConstraintGroup

Parameters

element (xml.etree.ElementTree.Element): A ValueConstraintGroup element (same as generated by the class itself)

Returns

group (ValueConstraintGroup): a ValueConstraintGroup object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of ValueConstraintGroup

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A ValueConstraintGroup element (same as generated by the class itself)

    Returns
    -------
        group (ValueConstraintGroup): a ValueConstraintGroup object

    """
    value_constraints = ValueConstraintGroup()
    constraints = element.findall("ValueConstraint")
    for constraint in constraints:
        value_constraint = ValueConstraint.parse(constraint)
        value_constraints.add_value_constraint(value_constraint)
    return value_constraints

Methods

def add_value_constraint(self, value_constraint)

adds a value constraint to the value constraint group

Parameters

value_constraint (ValueConstraint): the value constraint to be added
Expand source code
def add_value_constraint(self, value_constraint):
    """adds a value constraint to the value constraint group

    Parameters
    ----------
        value_constraint (ValueConstraint): the value constraint to be added

    """
    if not isinstance(value_constraint, ValueConstraint):
        raise TypeError("value_conatraint input is not of type ValueConstraint")
    self.value_constraints.append(value_constraint)
    return self
def get_element(self)

returns the elementTree of the ValueConstraintGroup

Expand source code
def get_element(self):
    """returns the elementTree of the ValueConstraintGroup"""
    if self.isVersion(minor=0):
        raise OpenSCENARIOVersionError(
            "ValueConstraintGroup was introduced in OpenSCENARIO V1.1"
        )
    element = ET.Element("ConstraintGroup")
    if not self.value_constraints:
        raise ValueError("No Value Constraints in the Value Contraint Group")
    for value_constraint in self.value_constraints:
        element.append(value_constraint.get_element())
    return element
class Variable (name, variable_type, value)

Variable is a declaration of an entry in VariableDeclaration (valid from V1.2) Parameters


name (str): name of variable

variable_type (ParameterType): type of the variable

value (str): value of the variable

Attributes

name (str): name of variable

variable_type (ParameterType): type of the variable

value (str): value of the variable

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the Variable

Parameters

name (str): name of variable

variable_type (ParameterType): type of the variable

value (str): value of the variable
Expand source code
class Variable(VersionBase):
    """Variable is a declaration of an entry in VariableDeclaration
    (valid from V1.2)
    Parameters
    ----------
        name (str): name of variable

        variable_type (ParameterType): type of the variable

        value (str): value of the variable

    Attributes
    ----------
        name (str): name of variable

        variable_type (ParameterType): type of the variable

        value (str): value of the variable

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, name, variable_type, value):
        """initalize the Variable

        Parameters
        ----------
            name (str): name of variable

            variable_type (ParameterType): type of the variable

            value (str): value of the variable

        """
        self.name = name
        self.variable_type = convert_enum(variable_type, ParameterType, False)
        self.value = value
        self.constraint_groups = []

    def __eq__(self, other):
        if isinstance(other, Variable):
            if (
                self.get_attributes() == other.get_attributes()
                and self.constraint_groups == other.constraint_groups
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Variable

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A variable element (same as generated by the class itself)

        Returns
        -------
            variable (Variable): Variable object

        """
        name = element.attrib["name"]
        value = element.attrib["value"]
        variable_type = convert_enum(
            element.attrib["variableType"], ParameterType, False
        )
        variable = Variable(name, variable_type, value)
        constraint_groups = element.findall("ValueConstraintGroup")
        for constraint_group in constraint_groups:
            variable.add_value_constraint_group(
                ValueConstraintGroup.parse(constraint_group)
            )
        return variable

    def get_attributes(self):
        """returns the attributes of the Variable as a dict"""
        return {
            "name": self.name,
            "variableType": self.variable_type.get_name(),
            "value": str(self.value),
        }

    def get_element(self):
        """returns the elementTree of the Variable"""
        if self.isVersionEqLess(minor=1):
            raise OpenSCENARIOVersionError("Variables were introduced in OSC 1.2")
        element = ET.Element("VariableDeclaration", attrib=self.get_attributes())
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of Variable

Parameters

element (xml.etree.ElementTree.Element): A variable element (same as generated by the class itself)

Returns

variable (Variable): Variable object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Variable

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A variable element (same as generated by the class itself)

    Returns
    -------
        variable (Variable): Variable object

    """
    name = element.attrib["name"]
    value = element.attrib["value"]
    variable_type = convert_enum(
        element.attrib["variableType"], ParameterType, False
    )
    variable = Variable(name, variable_type, value)
    constraint_groups = element.findall("ValueConstraintGroup")
    for constraint_group in constraint_groups:
        variable.add_value_constraint_group(
            ValueConstraintGroup.parse(constraint_group)
        )
    return variable

Methods

def get_attributes(self)

returns the attributes of the Variable as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Variable as a dict"""
    return {
        "name": self.name,
        "variableType": self.variable_type.get_name(),
        "value": str(self.value),
    }
def get_element(self)

returns the elementTree of the Variable

Expand source code
def get_element(self):
    """returns the elementTree of the Variable"""
    if self.isVersionEqLess(minor=1):
        raise OpenSCENARIOVersionError("Variables were introduced in OSC 1.2")
    element = ET.Element("VariableDeclaration", attrib=self.get_attributes())
    return element
class VariableDeclarations

The VariableDeclarations class creates the VariableDeclarations of OpenScenario (Valid from V1.2) Attributes


variables: list of Variable objects

Methods

get_element()
    Returns the full ElementTree of the class

add_variable(Variable)
    adds a Variable to the VariableDeclarations

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

initalizes the VariableDeclarations

Expand source code
class VariableDeclarations(VersionBase):
    """The VariableDeclarations class creates the VariableDeclarations of OpenScenario
    (Valid from V1.2)
    Attributes
    ----------
        variables: list of Variable objects

    Methods
    -------
        get_element()
            Returns the full ElementTree of the class

        add_variable(Variable)
            adds a Variable to the VariableDeclarations

        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

    """

    def __init__(self):
        """initalizes the VariableDeclarations"""
        self.variables = []

    @staticmethod
    def parse(element):
        """Parses the xml element of VariableDeclarations

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A VariableDeclarations element (same as generated by the class itself)

        Returns
        -------
            VariableDeclarations (VariableDeclarations): a VariableDeclarations object

        """
        variable_declarations = VariableDeclarations()
        declarations = element.findall("VariableDeclaration")
        for declaration in declarations:
            variable = Variable.parse(declaration)
            variable_declarations.add_variable(variable)
        return variable_declarations

    def __eq__(self, other):
        if isinstance(other, VariableDeclarations):
            if self.variables == other.variables:
                return True
        return False

    def add_variable(self, variable):
        """add_variable adds a Variable to the VariableDeclarations

        Parameters
        ----------
            variable (Variable): a new variable


        """
        if not isinstance(variable, Variable):
            raise TypeError("variable input is not of type Variable")
        self.variables.append(variable)
        return self

    def get_element(self):
        """returns the elementTree of the VariableDeclarations"""
        if self.version_minor < 2:
            OpenSCENARIOVersionError("Variables were introduced in OSC 1.2")
        element = ET.Element("VariableDeclarations")
        for p in self.variables:
            element.append(p.get_element())
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of VariableDeclarations

Parameters

element (xml.etree.ElementTree.Element): A VariableDeclarations element (same as generated by the class itself)

Returns

VariableDeclarations (VariableDeclarations): a VariableDeclarations object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of VariableDeclarations

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A VariableDeclarations element (same as generated by the class itself)

    Returns
    -------
        VariableDeclarations (VariableDeclarations): a VariableDeclarations object

    """
    variable_declarations = VariableDeclarations()
    declarations = element.findall("VariableDeclaration")
    for declaration in declarations:
        variable = Variable.parse(declaration)
        variable_declarations.add_variable(variable)
    return variable_declarations

Methods

def add_variable(self, variable)

add_variable adds a Variable to the VariableDeclarations

Parameters

variable (Variable): a new variable
Expand source code
def add_variable(self, variable):
    """add_variable adds a Variable to the VariableDeclarations

    Parameters
    ----------
        variable (Variable): a new variable


    """
    if not isinstance(variable, Variable):
        raise TypeError("variable input is not of type Variable")
    self.variables.append(variable)
    return self
def get_element(self)

returns the elementTree of the VariableDeclarations

Expand source code
def get_element(self):
    """returns the elementTree of the VariableDeclarations"""
    if self.version_minor < 2:
        OpenSCENARIOVersionError("Variables were introduced in OSC 1.2")
    element = ET.Element("VariableDeclarations")
    for p in self.variables:
        element.append(p.get_element())
    return element
class Weather (cloudstate=None, atmosphericPressure=None, temperature=None, sun=None, fog=None, precipitation=None, wind=None, dome_image=None, dome_azimuth_offset=None)

Weather creates an Weather element of openscenario

Parameters

cloudstate (CloudState, or FractionalCloudCover): cloudstate of the weather (CloudState (V1.0-1.1), FractionalCloudCover (>V1.2 ))
    Default: None

atmosphericPressure (float): atmospheric pressure in Pa (valid from OpenSCENARIO V1.1)
    Default: None

temperature (float): outside temperature (valid from OpenSCENARIO V1.1)
    Default: None

sun (Sun): the sun position
    Default: None

fog (Fog): fot state
    Default: None

precipitation (Precipitation): the precipitation state
    Default: None

wind (Wind): the wind (valid from OpenSCENARIO V1.1)
    Default: None

dome_image (str): image file for the sky (valid from OpenSCENARIO V1.2)
    Default: None

dome_azimuth_offset (float): offset for dome image (valid from OpenSCENARIO V1.2)
    Default: None

Attributes

cloudstate (CloudState): cloudstate of the weather

atmosphericPressure (float): atmospheric pressure in Pa (valid from OpenSCENARIO V1.1)

temperature (float): outside temperature (valid from OpenSCENARIO V1.1)

sun (Sun): the sun position

fog (Fog): fot state

precipitation (Precipitation): the precipitation state

wind (Wind): the wind (valid from OpenSCENARIO V1.1)

dome_image (str): image file for the sky (valid from OpenSCENARIO V1.2)

dome_azimuth_offset (float): offset for dome image (valid from OpenSCENARIO V1.2)

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the Weather

Parameters

cloudstate (CloudState, or FractionalCloudCover): cloudstate of the weather (CloudState (V1.0-1.1), FractionalCloudCover (>V1.2 ))
    Default: None

atmosphericPressure (float): atmospheric pressure in Pa (valid from OpenSCENARIO V1.1)
    Default: None

temperature (float): outside temperature (valid from OpenSCENARIO V1.1)
    Default: None

sun (Sun): the sun position
    Default: None

fog (Fog): fot state
    Default: None

precipitation (Precipitation): the precipitation state
    Default: None

wind (Wind): the wind (valid from OpenSCENARIO V1.1)
    Default: None

dome_image (str): image file for the sky (valid from OpenSCENARIO V1.2)
    Default: None

dome_azimuth_offset (float): offset for dome image (valid from OpenSCENARIO V1.2)
    Default: None
Expand source code
class Weather(VersionBase):
    """Weather creates an Weather element of openscenario

    Parameters
    ----------
        cloudstate (CloudState, or FractionalCloudCover): cloudstate of the weather (CloudState (V1.0-1.1), FractionalCloudCover (>V1.2 ))
            Default: None

        atmosphericPressure (float): atmospheric pressure in Pa (valid from OpenSCENARIO V1.1)
            Default: None

        temperature (float): outside temperature (valid from OpenSCENARIO V1.1)
            Default: None

        sun (Sun): the sun position
            Default: None

        fog (Fog): fot state
            Default: None

        precipitation (Precipitation): the precipitation state
            Default: None

        wind (Wind): the wind (valid from OpenSCENARIO V1.1)
            Default: None

        dome_image (str): image file for the sky (valid from OpenSCENARIO V1.2)
            Default: None

        dome_azimuth_offset (float): offset for dome image (valid from OpenSCENARIO V1.2)
            Default: None
    Attributes
    ----------
        cloudstate (CloudState): cloudstate of the weather

        atmosphericPressure (float): atmospheric pressure in Pa (valid from OpenSCENARIO V1.1)

        temperature (float): outside temperature (valid from OpenSCENARIO V1.1)

        sun (Sun): the sun position

        fog (Fog): fot state

        precipitation (Precipitation): the precipitation state

        wind (Wind): the wind (valid from OpenSCENARIO V1.1)

        dome_image (str): image file for the sky (valid from OpenSCENARIO V1.2)

        dome_azimuth_offset (float): offset for dome image (valid from OpenSCENARIO V1.2)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(
        self,
        cloudstate=None,
        atmosphericPressure=None,
        temperature=None,
        sun=None,
        fog=None,
        precipitation=None,
        wind=None,
        dome_image=None,
        dome_azimuth_offset=None,
    ):
        """initalize the Weather

        Parameters
        ----------
            cloudstate (CloudState, or FractionalCloudCover): cloudstate of the weather (CloudState (V1.0-1.1), FractionalCloudCover (>V1.2 ))
                Default: None

            atmosphericPressure (float): atmospheric pressure in Pa (valid from OpenSCENARIO V1.1)
                Default: None

            temperature (float): outside temperature (valid from OpenSCENARIO V1.1)
                Default: None

            sun (Sun): the sun position
                Default: None

            fog (Fog): fot state
                Default: None

            precipitation (Precipitation): the precipitation state
                Default: None

            wind (Wind): the wind (valid from OpenSCENARIO V1.1)
                Default: None

            dome_image (str): image file for the sky (valid from OpenSCENARIO V1.2)
                Default: None

            dome_azimuth_offset (float): offset for dome image (valid from OpenSCENARIO V1.2)
                Default: None
        """
        try:
            self.cloudstate = convert_enum(cloudstate, CloudState, True)
        except Exception as e:
            self.cloudstate = convert_enum(cloudstate, FractionalCloudCover, True)

        if precipitation and not isinstance(precipitation, Precipitation):
            raise TypeError("precipitation input is not of type Precipitation")
        if fog and not isinstance(fog, Fog):
            raise TypeError("fog input is not of type Fog")
        if wind and not isinstance(wind, Wind):
            raise TypeError("wind input is not of type Wind")
        if sun and not isinstance(sun, Sun):
            raise TypeError("sun input is not of type Sun")

        # self.cloudstate = cloudstate
        self.atmosphericPressure = atmosphericPressure
        self.temperature = temperature
        self.fog = fog
        self.sun = sun
        self.wind = wind
        self.precipitation = precipitation
        self.dome_image = dome_image
        self.dome_azimuth_offset = convert_float(dome_azimuth_offset)

    def __eq__(self, other):
        if isinstance(other, Weather):
            if (
                self.get_attributes() == other.get_attributes()
                and self.fog == other.fog
                and self.wind == other.wind
                and self.sun == other.sun
                and self.precipitation == other.precipitation
                and self.dome_image == other.dome_image
                and self.dome_azimuth_offset == other.dome_azimuth_offset
            ):
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Weather

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A weather element (same as generated by the class itself)

        Returns
        -------
            weather (Weather): a Weather object

        """
        temperature = None
        atmosphericPressure = None
        cloudstate = None
        fog = None
        sun = None
        wind = None
        precipitation = None
        dome_file = None
        dome_azimuth = None

        if "temperature" in element.attrib:
            temperature = element.attrib["temperature"]
        if "atmosphericPressure" in element.attrib:
            atmosphericPressure = element.attrib["atmosphericPressure"]
        if "cloudState" in element.attrib:
            cloudstate = convert_enum(element.attrib["cloudState"], CloudState, False)
        if "fractionalCloudCover" in element.attrib:
            cloudstate = convert_enum(
                element.attrib["fractionalCloudCover"], FractionalCloudCover
            )
        if element.find("Sun") != None:
            sun = Sun.parse(element.find("Sun"))
        if element.find("Fog") != None:
            fog = Fog.parse(element.find("Fog"))
        if element.find("Precipitation") != None:
            precipitation = Precipitation.parse(element.find("Precipitation"))
        if element.find("Wind") != None:
            wind = Wind.parse(element.find("Wind"))
        if element.find("DomeImage") != None:
            dome_file = element.find("DomeImage").find("DomeFile").attrib["filepath"]

            if "azimuthOffset" in element.find("DomeImage").attrib:
                dome_azimuth = convert_float(
                    element.find("DomeImage").attrib["azimuthOffset"]
                )
        return Weather(
            cloudstate,
            atmosphericPressure,
            temperature,
            sun,
            fog,
            precipitation,
            wind,
            dome_file,
            dome_azimuth,
        )

    def get_attributes(self):
        """returns the attributes of the Weather as a dict"""
        retdict = {}
        if self.cloudstate:
            if hasattr(CloudState, str(self.cloudstate)):
                if self.isVersionEqLarger(minor=2):
                    raise OpenSCENARIOVersionError(
                        "Cloudstate is replaced with FractionalCloudCover for OSC versions > 1.1"
                    )
                retdict["cloudState"] = self.cloudstate.get_name()
            elif hasattr(FractionalCloudCover, str(self.cloudstate)):
                if self.isVersionEqLess(minor=1):
                    raise OpenSCENARIOVersionError(
                        "FractionalCloudCover was introduced in OSC 1.2"
                    )
                retdict["fractionalCloudCover"] = self.cloudstate.get_name()
            elif str(self.cloudstate)[0] == "$":
                if self.isVersionEqLarger(minor=2):
                    retdict["fractionalCloudCover"] = self.cloudstate.get_name()
                else:
                    retdict["cloudState"] = self.cloudstate.get_name()
        if self.temperature is not None and not self.isVersion(minor=0):
            retdict["temperature"] = str(self.temperature)
        elif self.temperature is not None and self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "temperature was introduced in OpenSCENARIO V1.1"
            )
        if self.atmosphericPressure is not None and not self.isVersion(minor=0):
            retdict["atmosphericPressure"] = str(self.atmosphericPressure)
        elif self.atmosphericPressure is not None and self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "atmosphericPressure was introduced in OpenSCENARIO V1.1"
            )
        return retdict

    def get_element(self):
        """returns the elementTree of the Weather"""
        if self.isVersion(minor=0):
            if self.sun == None:
                raise OpenSCENARIOVersionError("In OpenScenario 1.0, Sun is required.")
            if self.cloudstate == None:
                raise OpenSCENARIOVersionError(
                    "In OpenScenario 1.0, CloudState is required."
                )
            if self.fog == None:
                raise OpenSCENARIOVersionError("In OpenScenario 1.0, Fog is required.")
            if self.precipitation == None:
                raise OpenSCENARIOVersionError(
                    "In OpenScenario 1.0, Precipitation is required."
                )
        element = ET.Element("Weather", attrib=self.get_attributes())
        if self.sun:
            element.append(self.sun.get_element())
        if self.fog:
            element.append(self.fog.get_element())
        if self.precipitation:
            element.append(self.precipitation.get_element())
        if self.wind and not self.isVersion(minor=0):
            element.append(self.wind.get_element())
        if self.wind and self.isVersion(minor=0):
            raise OpenSCENARIOVersionError("Wind was introduced in OpenSCENARIO V1.1")
        if self.dome_image and (self.isVersion(minor=0) or self.isVersion(minor=1)):
            raise OpenSCENARIOVersionError(
                "DomeImage was introduced in OpenSCENARIO V1.2"
            )
        if self.dome_image:
            dome_attr = {}
            if self.dome_azimuth_offset:
                dome_attr["azimuthOffset"] = str(self.dome_azimuth_offset)
            dome_element = ET.SubElement(element, "DomeImage", attrib=dome_attr)
            ET.SubElement(
                dome_element, "DomeFile", attrib={"filepath": self.dome_image}
            )
        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of Weather

Parameters

element (xml.etree.ElementTree.Element): A weather element (same as generated by the class itself)

Returns

weather (Weather): a Weather object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Weather

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A weather element (same as generated by the class itself)

    Returns
    -------
        weather (Weather): a Weather object

    """
    temperature = None
    atmosphericPressure = None
    cloudstate = None
    fog = None
    sun = None
    wind = None
    precipitation = None
    dome_file = None
    dome_azimuth = None

    if "temperature" in element.attrib:
        temperature = element.attrib["temperature"]
    if "atmosphericPressure" in element.attrib:
        atmosphericPressure = element.attrib["atmosphericPressure"]
    if "cloudState" in element.attrib:
        cloudstate = convert_enum(element.attrib["cloudState"], CloudState, False)
    if "fractionalCloudCover" in element.attrib:
        cloudstate = convert_enum(
            element.attrib["fractionalCloudCover"], FractionalCloudCover
        )
    if element.find("Sun") != None:
        sun = Sun.parse(element.find("Sun"))
    if element.find("Fog") != None:
        fog = Fog.parse(element.find("Fog"))
    if element.find("Precipitation") != None:
        precipitation = Precipitation.parse(element.find("Precipitation"))
    if element.find("Wind") != None:
        wind = Wind.parse(element.find("Wind"))
    if element.find("DomeImage") != None:
        dome_file = element.find("DomeImage").find("DomeFile").attrib["filepath"]

        if "azimuthOffset" in element.find("DomeImage").attrib:
            dome_azimuth = convert_float(
                element.find("DomeImage").attrib["azimuthOffset"]
            )
    return Weather(
        cloudstate,
        atmosphericPressure,
        temperature,
        sun,
        fog,
        precipitation,
        wind,
        dome_file,
        dome_azimuth,
    )

Methods

def get_attributes(self)

returns the attributes of the Weather as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Weather as a dict"""
    retdict = {}
    if self.cloudstate:
        if hasattr(CloudState, str(self.cloudstate)):
            if self.isVersionEqLarger(minor=2):
                raise OpenSCENARIOVersionError(
                    "Cloudstate is replaced with FractionalCloudCover for OSC versions > 1.1"
                )
            retdict["cloudState"] = self.cloudstate.get_name()
        elif hasattr(FractionalCloudCover, str(self.cloudstate)):
            if self.isVersionEqLess(minor=1):
                raise OpenSCENARIOVersionError(
                    "FractionalCloudCover was introduced in OSC 1.2"
                )
            retdict["fractionalCloudCover"] = self.cloudstate.get_name()
        elif str(self.cloudstate)[0] == "$":
            if self.isVersionEqLarger(minor=2):
                retdict["fractionalCloudCover"] = self.cloudstate.get_name()
            else:
                retdict["cloudState"] = self.cloudstate.get_name()
    if self.temperature is not None and not self.isVersion(minor=0):
        retdict["temperature"] = str(self.temperature)
    elif self.temperature is not None and self.isVersion(minor=0):
        raise OpenSCENARIOVersionError(
            "temperature was introduced in OpenSCENARIO V1.1"
        )
    if self.atmosphericPressure is not None and not self.isVersion(minor=0):
        retdict["atmosphericPressure"] = str(self.atmosphericPressure)
    elif self.atmosphericPressure is not None and self.isVersion(minor=0):
        raise OpenSCENARIOVersionError(
            "atmosphericPressure was introduced in OpenSCENARIO V1.1"
        )
    return retdict
def get_element(self)

returns the elementTree of the Weather

Expand source code
def get_element(self):
    """returns the elementTree of the Weather"""
    if self.isVersion(minor=0):
        if self.sun == None:
            raise OpenSCENARIOVersionError("In OpenScenario 1.0, Sun is required.")
        if self.cloudstate == None:
            raise OpenSCENARIOVersionError(
                "In OpenScenario 1.0, CloudState is required."
            )
        if self.fog == None:
            raise OpenSCENARIOVersionError("In OpenScenario 1.0, Fog is required.")
        if self.precipitation == None:
            raise OpenSCENARIOVersionError(
                "In OpenScenario 1.0, Precipitation is required."
            )
    element = ET.Element("Weather", attrib=self.get_attributes())
    if self.sun:
        element.append(self.sun.get_element())
    if self.fog:
        element.append(self.fog.get_element())
    if self.precipitation:
        element.append(self.precipitation.get_element())
    if self.wind and not self.isVersion(minor=0):
        element.append(self.wind.get_element())
    if self.wind and self.isVersion(minor=0):
        raise OpenSCENARIOVersionError("Wind was introduced in OpenSCENARIO V1.1")
    if self.dome_image and (self.isVersion(minor=0) or self.isVersion(minor=1)):
        raise OpenSCENARIOVersionError(
            "DomeImage was introduced in OpenSCENARIO V1.2"
        )
    if self.dome_image:
        dome_attr = {}
        if self.dome_azimuth_offset:
            dome_attr["azimuthOffset"] = str(self.dome_azimuth_offset)
        dome_element = ET.SubElement(element, "DomeImage", attrib=dome_attr)
        ET.SubElement(
            dome_element, "DomeFile", attrib={"filepath": self.dome_image}
        )
    return element
class Wind (direction, speed)

Wind creates an Wind element used by the Weather element of openscenario

Parameters

direction (float): wind direction (radians)

speed (float): wind speed (m/s)

Attributes

direction (float): wind direction (radians)

speed (float): wind speed (m/s)

Methods

parse(element)
    parses a ElementTree created by the class and returns an instance of the class

get_element()
    Returns the full ElementTree of the class

get_attributes()
    Returns a dictionary of all attributes of the class

initalize the Wind

Parameters

direction (float): wind direction (radians)

speed (float): wind speed (m/s)
Expand source code
class Wind(VersionBase):
    """Wind creates an Wind element used by the Weather element of openscenario

    Parameters
    ----------
        direction (float): wind direction (radians)

        speed (float): wind speed (m/s)

    Attributes
    ----------
        direction (float): wind direction (radians)

        speed (float): wind speed (m/s)

    Methods
    -------
        parse(element)
            parses a ElementTree created by the class and returns an instance of the class

        get_element()
            Returns the full ElementTree of the class

        get_attributes()
            Returns a dictionary of all attributes of the class

    """

    def __init__(self, direction, speed):
        """initalize the Wind

        Parameters
        ----------
            direction (float): wind direction (radians)

            speed (float): wind speed (m/s)

        """
        self.direction = direction
        self.speed = speed

    def __eq__(self, other):
        if isinstance(other, Wind):
            if self.get_attributes() == other.get_attributes():
                return True
        return False

    @staticmethod
    def parse(element):
        """Parses the xml element of Wind

        Parameters
        ----------
            element (xml.etree.ElementTree.Element): A wind element (same as generated by the class itself)

        Returns
        -------
            wind (Wind): a Wind object

        """
        direction = element.attrib["direction"]
        speed = element.attrib["speed"]

        return Wind(direction, speed)

    def get_attributes(self):
        """returns the attributes of the Wind as a dict"""
        return {"direction": str(self.direction), "speed": str(self.speed)}

    def get_element(self):
        """returns the elementTree of the Wind"""
        if self.isVersion(minor=0):
            raise OpenSCENARIOVersionError("Wind was introduced in OSC 1.1")
        element = ET.Element("Wind", attrib=self.get_attributes())

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of Wind

Parameters

element (xml.etree.ElementTree.Element): A wind element (same as generated by the class itself)

Returns

wind (Wind): a Wind object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Wind

    Parameters
    ----------
        element (xml.etree.ElementTree.Element): A wind element (same as generated by the class itself)

    Returns
    -------
        wind (Wind): a Wind object

    """
    direction = element.attrib["direction"]
    speed = element.attrib["speed"]

    return Wind(direction, speed)

Methods

def get_attributes(self)

returns the attributes of the Wind as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Wind as a dict"""
    return {"direction": str(self.direction), "speed": str(self.speed)}
def get_element(self)

returns the elementTree of the Wind

Expand source code
def get_element(self):
    """returns the elementTree of the Wind"""
    if self.isVersion(minor=0):
        raise OpenSCENARIOVersionError("Wind was introduced in OSC 1.1")
    element = ET.Element("Wind", attrib=self.get_attributes())

    return element