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.
Functions
def convert_bool(value: bool | str | int) ‑> bool-
Expand source code
def convert_bool(value: Union[bool, str, int]) -> bool: """Converts a value to a boolean. Parameters ---------- value : bool or str The value to convert. Returns ------- bool The converted boolean value. Raises ------ ValueError If the value is not a valid boolean. """ if isinstance(value, str): if value.lower() in (["true", "1"]): return True elif value.lower() in (["false", "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 is None: return None return FalseConverts a value to a boolean.
Parameters
value:boolorstr- The value to convert.
Returns
bool- The converted boolean value.
Raises
ValueError- If the value is not a valid boolean.
def convert_enum(value: scenariogeneration.xosc.enumerations._OscEnum | str,
enumtype: Type[scenariogeneration.xosc.enumerations._OscEnum],
none_ok: bool = False) ‑> scenariogeneration.xosc.enumerations._OscEnum-
Expand source code
def convert_enum( value: Union[_OscEnum, str], enumtype: Type[_OscEnum], none_ok: bool = False, ) -> _OscEnum: """Converts a value to an enumeration. Parameters ---------- value : _OscEnum or str The value to convert. enumtype : Type[_OscEnum] The enumeration type to convert to. none_ok : bool, optional Whether None is a valid value. Default is False. Returns ------- _OscEnum The converted enumeration value. Raises ------ TypeError If the value is not a valid enumeration or string. ValueError If the value is not a valid string input for the enumeration type. """ if isinstance(value, _OscEnum): if hasattr(enumtype, str(value)) or "$" == str(value)[0]: return value raise TypeError( value.get_name() + " is not of Enumeration type :" + str(enumtype) ) if isinstance(value, str): if hasattr(enumtype, value): return _OscEnum(enumtype.__name__, value) elif "$" == value[0]: return _OscEnum(enumtype.__name__, value) raise ValueError( value + " is not a valid string input for Enumeration type " + str(enumtype) ) if value is None: if none_ok: return None raise TypeError("None value not a valid option for: " + str(enumtype)) raise TypeError(str(value) + " is not of a valid enumeration or str type.")Converts a value to an enumeration.
Parameters
value:_OscEnumorstr- The value to convert.
enumtype:Type[_OscEnum]- The enumeration type to convert to.
none_ok:bool, optional- Whether None is a valid value. Default is False.
Returns
_OscEnum- The converted enumeration value.
Raises
TypeError- If the value is not a valid enumeration or string.
ValueError- If the value is not a valid string input for the enumeration type.
def convert_float(value: float | str | int | None) ‑> float | None-
Expand source code
def convert_float(value: Union[float, str, int, None]) -> Optional[float]: """Converts a value to a float. Parameters ---------- value : float, str, int or None The value to convert. Returns ------- float or None The converted float value, or None if the value is None. Raises ------ ValueError If the value is not a valid float. """ 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 NoneConverts a value to a float.
Parameters
value:float, str, intorNone- The value to convert.
Returns
floatorNone- The converted float value, or None if the value is None.
Raises
ValueError- If the value is not a valid float.
def convert_int(value: int | str | None) ‑> int | None-
Expand source code
def convert_int(value: Union[int, str, None]) -> Optional[int]: """Converts a value to an int. Parameters ---------- value : int, str or None The value to convert. Returns ------- int or None The converted int value, or None if the value is None. Raises ------ ValueError If the value is not a valid int. """ 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 NoneConverts a value to an int.
Parameters
value:int, strorNone- The value to convert.
Returns
intorNone- The converted int value, or None if the value is None.
Raises
ValueError- If the value is not a valid int.
def find_mandatory_field(element: xml.etree.ElementTree.Element, key: str) ‑> xml.etree.ElementTree.Element-
Expand source code
def find_mandatory_field(element: ET.Element, key: str) -> ET.Element: """Wrapper to find mandatory fields, throws an error if not found. Parameters ---------- element : ET.Element The element to search in. key : str The key to search for. Returns ------- ET.Element The found element. Raises ------ XMLStructureError If the key is not found in the element. """ found = element.find(key) if found is None: raise XMLStructureError( f"Mandatory field {key} not found in {element.tag}" ) return foundWrapper to find mandatory fields, throws an error if not found.
Parameters
element:ET.Element- The element to search in.
key:str- The key to search for.
Returns
ET.Element- The found element.
Raises
XMLStructureError- If the key is not found in the element.
def get_bool_string(value: bool | str) ‑> str-
Expand source code
def get_bool_string(value: Union[bool, str]) -> str: """Converts a boolean value to a string. Parameters ---------- value : bool or str The boolean value to convert. Returns ------- str The converted string value. """ if isinstance(value, str) and value[0] == "$": return value elif value: return "true" return "false"Converts a boolean value to a string.
Parameters
value:boolorstr- The boolean value to convert.
Returns
str- The converted string value.
def merge_dicts(*dict_args: dict) ‑> dict-
Expand source code
def merge_dicts(*dict_args: dict) -> dict: """Merges multiple dictionaries into one. Parameters ---------- *dict_args : dict The dictionaries to merge. Returns ------- dict The merged dictionary. """ retdict = {} for d in dict_args: retdict.update(d) return retdictMerges multiple dictionaries into one.
Parameters
*dict_args:dict- The dictionaries to merge.
Returns
dict- The merged dictionary.
Classes
class AbsoluteSpeed (value: float,
steadyState: TargetTimeSteadyState | TargetDistanceSteadyState | None = None)-
Expand source code
class AbsoluteSpeed(VersionBase): """AbsoluteSpeed creates an AbsoluteSpeed element of OpenScenario. Parameters ---------- value : float Absolute speed [m/s]. steadyState : Union[TargetTimeSteadyState, TargetDistanceSteadyState], optional Final phase of constant (final) speed, start of which defined by distance or time (valid from OpenSCENARIO V1.1). Default is None. Attributes ---------- value : float Absolute speed [m/s]. steadyState : Union[TargetTimeSteadyState, TargetDistanceSteadyState], optional Final phase of constant (final) speed, start of which defined by distance or time. Methods ------- parse(element) Parses an 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, value: float, steadyState: Optional[ Union[TargetTimeSteadyState, TargetDistanceSteadyState] ] = None, ) -> None: """Initializes the AbsoluteSpeed. Parameters ---------- value : float Absolute speed [m/s]. steadyState : Union[TargetTimeSteadyState, TargetDistanceSteadyState], optional Final phase of constant (final) speed, start of which defined by distance or time (valid from OpenSCENARIO V1.1). Default is None. """ self.value = value if steadyState: if not isinstance( steadyState, (TargetTimeSteadyState, TargetDistanceSteadyState) ): raise TypeError( "steadyState input is not an TargetTimeSteadyState or " "TargetDistanceSteadyState input" ) self.steadyState = steadyState def __eq__(self, other: object) -> bool: if isinstance(other, AbsoluteSpeed): if ( self.get_attributes() == other.get_attributes() and self.steadyState == other.steadyState ): return True return False @staticmethod def parse(element: ET.Element) -> "AbsoluteSpeed": """Parses the XML element of AbsoluteSpeed. Parameters ---------- element : ET.Element An AbsoluteSpeed element (same as generated by the class itself). Returns ------- AbsoluteSpeed An AbsoluteSpeed object. """ absolute_speed_element = find_mandatory_field(element, "AbsoluteSpeed") value = absolute_speed_element.attrib["value"] state = None if ( absolute_speed_element.find("TargetDistanceSteadyState") is not None ): state = TargetDistanceSteadyState.parse( find_mandatory_field( absolute_speed_element, "TargetDistanceSteadyState" ) ) elif absolute_speed_element.find("TargetTimeSteadyState") is not None: state = TargetTimeSteadyState.parse( find_mandatory_field( absolute_speed_element, "TargetTimeSteadyState" ) ) return AbsoluteSpeed(value, state) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the AbsoluteSpeed as a dictionary. Returns ------- dict A dictionary of all attributes of the AbsoluteSpeed. """ return {"value": str(self.value)} def get_element(self) -> ET.Element: """Returns the ElementTree of the AbsoluteSpeed. Returns ------- ET.Element The ElementTree representation 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 elementFinalSpeedAbsoluteSpeed creates an AbsoluteSpeed element of OpenScenario.
Parameters
value:float- Absolute speed [m/s].
steadyState:Union[TargetTimeSteadyState, TargetDistanceSteadyState], optional- Final phase of constant (final) speed, start of which defined by distance or time (valid from OpenSCENARIO V1.1). Default is None.
Attributes
value:float- Absolute speed [m/s].
steadyState:Union[TargetTimeSteadyState, TargetDistanceSteadyState], optional- Final phase of constant (final) speed, start of which defined by distance or time.
Methods
parse(element) Parses an 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.
Initializes the AbsoluteSpeed.
Parameters
value:float- Absolute speed [m/s].
steadyState:Union[TargetTimeSteadyState, TargetDistanceSteadyState], optional- Final phase of constant (final) speed, start of which defined by distance or time (valid from OpenSCENARIO V1.1). Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> AbsoluteSpeed-
Expand source code
@staticmethod def parse(element: ET.Element) -> "AbsoluteSpeed": """Parses the XML element of AbsoluteSpeed. Parameters ---------- element : ET.Element An AbsoluteSpeed element (same as generated by the class itself). Returns ------- AbsoluteSpeed An AbsoluteSpeed object. """ absolute_speed_element = find_mandatory_field(element, "AbsoluteSpeed") value = absolute_speed_element.attrib["value"] state = None if ( absolute_speed_element.find("TargetDistanceSteadyState") is not None ): state = TargetDistanceSteadyState.parse( find_mandatory_field( absolute_speed_element, "TargetDistanceSteadyState" ) ) elif absolute_speed_element.find("TargetTimeSteadyState") is not None: state = TargetTimeSteadyState.parse( find_mandatory_field( absolute_speed_element, "TargetTimeSteadyState" ) ) return AbsoluteSpeed(value, state)Parses the XML element of AbsoluteSpeed.
Parameters
element:ET.Element- An AbsoluteSpeed element (same as generated by the class itself).
Returns
AbsoluteSpeed- An AbsoluteSpeed object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the AbsoluteSpeed as a dictionary. Returns ------- dict A dictionary of all attributes of the AbsoluteSpeed. """ return {"value": str(self.value)}Returns the attributes of the AbsoluteSpeed as a dictionary.
Returns
dict- A dictionary of all attributes of the AbsoluteSpeed.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the AbsoluteSpeed. Returns ------- ET.Element The ElementTree representation 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 elementFinalSpeedReturns the ElementTree of the AbsoluteSpeed.
Returns
ET.Element- The ElementTree representation of the AbsoluteSpeed.
class AnimationFile (file: str, timeOffset: float | None = None)-
Expand source code
class AnimationFile(_AnimationType): """AnimationFile creates an AnimationFile element of OpenSCENARIO (valid from OpenSCENARIO V1.2). Parameters ---------- file : str Filepath of the animation/motion file. timeOffset : float, optional Time offset from beginning of animation. Default is None. Attributes ---------- file : str Filepath of the animation/motion file. timeOffset : float, optional Time offset from beginning of animation. Methods ------- parse(element) Parses an 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, file: str, timeOffset: Optional[float] = None) -> None: """Initializes the AnimationFile. Parameters ---------- file : str Filepath of the animation/motion file. timeOffset : float, optional Time offset from beginning of animation. Default is None. """ self.file = file self.timeOffset = convert_float(timeOffset) def __eq__(self, other: object) -> bool: if isinstance(other, AnimationFile): if ( other.get_attributes() == self.get_attributes() and other.file == self.file ): return True return False @staticmethod def parse(element: ET.Element) -> "AnimationFile": """Parses the XML element of AnimationFile. Parameters ---------- element : ET.Element An AnimationFile element (same as generated by the class itself). Returns ------- AnimationFile An AnimationFile object. """ timeOffset = None if element.find("File") is not None: file = find_mandatory_field(element, "File").attrib["filepath"] if "timeOffset" in element.attrib: timeOffset = convert_float(element.attrib["timeOffset"]) return AnimationFile(file, timeOffset) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the AnimationFile as a dictionary. Returns ------- dict A dictionary of all attributes of the AnimationFile. """ retdict = {} if self.timeOffset is not None: retdict["timeOffset"] = str(self.timeOffset) return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the AnimationFile. Returns ------- ET.Element The ElementTree representation of the AnimationFile. """ if not self.isVersionEqLarger(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 elementAnimationFile creates an AnimationFile element of OpenSCENARIO (valid from OpenSCENARIO V1.2).
Parameters
file:str- Filepath of the animation/motion file.
timeOffset:float, optional- Time offset from beginning of animation. Default is None.
Attributes
file:str- Filepath of the animation/motion file.
timeOffset:float, optional- Time offset from beginning of animation.
Methods
parse(element) Parses an 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.
Initializes the AnimationFile.
Parameters
file:str- Filepath of the animation/motion file.
timeOffset:float, optional- Time offset from beginning of animation. Default is None.
Ancestors
- scenariogeneration.xosc.utils._AnimationType
- VersionBase
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> AnimationFile-
Expand source code
@staticmethod def parse(element: ET.Element) -> "AnimationFile": """Parses the XML element of AnimationFile. Parameters ---------- element : ET.Element An AnimationFile element (same as generated by the class itself). Returns ------- AnimationFile An AnimationFile object. """ timeOffset = None if element.find("File") is not None: file = find_mandatory_field(element, "File").attrib["filepath"] if "timeOffset" in element.attrib: timeOffset = convert_float(element.attrib["timeOffset"]) return AnimationFile(file, timeOffset)Parses the XML element of AnimationFile.
Parameters
element:ET.Element- An AnimationFile element (same as generated by the class itself).
Returns
AnimationFile- An AnimationFile object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the AnimationFile as a dictionary. Returns ------- dict A dictionary of all attributes of the AnimationFile. """ retdict = {} if self.timeOffset is not None: retdict["timeOffset"] = str(self.timeOffset) return retdictReturns the attributes of the AnimationFile as a dictionary.
Returns
dict- A dictionary of all attributes of the AnimationFile.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the AnimationFile. Returns ------- ET.Element The ElementTree representation of the AnimationFile. """ if not self.isVersionEqLarger(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 elementReturns the ElementTree of the AnimationFile.
Returns
ET.Element- The ElementTree representation of the AnimationFile.
class BoundingBox (width: float,
length: float,
height: float,
x_center: float,
y_center: float,
z_center: float)-
Expand source code
class BoundingBox(VersionBase): """The BoundingBox class creates a bounding box for an entity. Parameters ---------- width : float The width of the entity. length : float The length of the entity. height : float The height of the entity. x_center : float X distance from back axle to center. y_center : float Y distance from back axle to center. z_center : float Z distance from back axle to center. Attributes ---------- boundingbox : Dimensions The dimensions of the entity. center : Center The center of the object relative to the back axle. Methods ------- parse(element) Parses an ElementTree created by the class and returns an instance of the class. get_element() Returns the full ElementTree of the class. """ def __init__( self, width: float, length: float, height: float, x_center: float, y_center: float, z_center: float, ) -> None: """Initializes the BoundingBox. Parameters ---------- width : float The width of the entity. length : float The length of the entity. height : float The height of the entity. x_center : float X distance from back axle to center. y_center : float Y distance from back axle to center. z_center : float Z distance from back axle to center. """ self.boundingbox = Dimensions(width, length, height) self.center = Center(x_center, y_center, z_center) def __eq__(self, other: object) -> bool: if isinstance(other, BoundingBox): if ( self.boundingbox == other.boundingbox and self.center == other.center ): return True return False @staticmethod def parse(element: ET.Element) -> "BoundingBox": """Parses the XML element of BoundingBox. Parameters ---------- element : ET.Element A BoundingBox element (same as generated by the class itself). Returns ------- BoundingBox A BoundingBox object. """ center = Center.parse(find_mandatory_field(element, "Center")) cen_dict = center.get_attributes() dimension = Dimensions.parse( find_mandatory_field(element, "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"], ) def get_element(self) -> ET.Element: """Returns the ElementTree of the BoundingBox. Returns ------- ET.Element The ElementTree representation of the BoundingBox. """ element = ET.Element("BoundingBox") element.append(self.center.get_element()) element.append(self.boundingbox.get_element()) return elementThe BoundingBox class creates a bounding box for an entity.
Parameters
width:float- The width of the entity.
length:float- The length of the entity.
height:float- The height of the entity.
x_center:float- X distance from back axle to center.
y_center:float- Y distance from back axle to center.
z_center:float- Z distance from back axle to center.
Attributes
boundingbox:Dimensions- The dimensions of the entity.
center:Center- The center of the object relative to the back axle.
Methods
parse(element) Parses an ElementTree created by the class and returns an instance of the class. get_element() Returns the full ElementTree of the class.
Initializes the BoundingBox.
Parameters
width:float- The width of the entity.
length:float- The length of the entity.
height:float- The height of the entity.
x_center:float- X distance from back axle to center.
y_center:float- Y distance from back axle to center.
z_center:float- Z distance from back axle to center.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> BoundingBox-
Expand source code
@staticmethod def parse(element: ET.Element) -> "BoundingBox": """Parses the XML element of BoundingBox. Parameters ---------- element : ET.Element A BoundingBox element (same as generated by the class itself). Returns ------- BoundingBox A BoundingBox object. """ center = Center.parse(find_mandatory_field(element, "Center")) cen_dict = center.get_attributes() dimension = Dimensions.parse( find_mandatory_field(element, "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"], )Parses the XML element of BoundingBox.
Parameters
element:ET.Element- A BoundingBox element (same as generated by the class itself).
Returns
BoundingBox- A BoundingBox object.
Methods
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the BoundingBox. Returns ------- ET.Element The ElementTree representation of the BoundingBox. """ element = ET.Element("BoundingBox") element.append(self.center.get_element()) element.append(self.boundingbox.get_element()) return elementReturns the ElementTree of the BoundingBox.
Returns
ET.Element- The ElementTree representation of the BoundingBox.
class Catalog-
Expand source code
class Catalog(VersionBase): """The Catalog class creates the CatalogLocation of the OpenScenario input. Attributes ---------- catalogs : dict Dictionary of catalogs to add, and their path. Methods ------- parse(element) Parses an 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) -> None: """Initializes the Catalog class.""" self.catalogs = {} def __eq__(self, other: object) -> bool: if isinstance(other, Catalog): if self.catalogs == other.catalogs: return True return False @staticmethod def parse(element: ET.Element) -> "Catalog": """Parses the XML element of Catalog. Parameters ---------- element : ET.Element A Catalog element (same as generated by the class itself). Returns ------- Catalog A Catalog object. """ catalog = Catalog() vc_element = element.find("VehicleCatalog") if vc_element is not None: path = find_mandatory_field(vc_element, "Directory").attrib["path"] catalog.add_catalog("VehicleCatalog", path) cc_element = element.find("ControllerCatalog") if cc_element is not None: path = find_mandatory_field(cc_element, "Directory").attrib["path"] catalog.add_catalog("ControllerCatalog", path) pc_element = element.find("PedestrianCatalog") if pc_element is not None: path = find_mandatory_field(pc_element, "Directory").attrib["path"] catalog.add_catalog("PedestrianCatalog", path) moc_element = element.find("MiscObjectCatalog") if moc_element is not None: path = find_mandatory_field(moc_element, "Directory").attrib[ "path" ] catalog.add_catalog("MiscObjectCatalog", path) ec_element = element.find("EnvironmentCatalog") if ec_element is not None: path = find_mandatory_field(ec_element, "Directory").attrib["path"] catalog.add_catalog("EnvironmentCatalog", path) mc_element = element.find("ManeuverCatalog") if mc_element is not None: path = find_mandatory_field(mc_element, "Directory").attrib["path"] catalog.add_catalog("ManeuverCatalog", path) tc_element = element.find("TrajectoryCatalog") if tc_element is not None: path = find_mandatory_field(tc_element, "Directory").attrib["path"] catalog.add_catalog("TrajectoryCatalog", path) rc_element = element.find("RouteCatalog") if rc_element is not None: path = find_mandatory_field(rc_element, "Directory").attrib["path"] catalog.add_catalog("RouteCatalog", path) return catalog def add_catalog(self, catalogname: str, path: str) -> "Catalog": """Adds a new catalog to be used. Parameters ---------- catalogname : str Name of the catalog. path : str Path to the catalog. Returns ------- Catalog The updated Catalog object. """ 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) -> ET.Element: """Returns the ElementTree of the Catalog. Returns ------- ET.Element The ElementTree representation of the Catalog. """ catloc = ET.Element("CatalogLocations") for i, catalog in self.catalogs.items(): tmpel = ET.SubElement(catloc, i) ET.SubElement(tmpel, "Directory", {"path": catalog}) return catlocThe Catalog class creates the CatalogLocation of the OpenScenario input.
Attributes
catalogs:dict- Dictionary of catalogs to add, and their path.
Methods
parse(element) Parses an 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.
Initializes the Catalog class.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Catalog-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Catalog": """Parses the XML element of Catalog. Parameters ---------- element : ET.Element A Catalog element (same as generated by the class itself). Returns ------- Catalog A Catalog object. """ catalog = Catalog() vc_element = element.find("VehicleCatalog") if vc_element is not None: path = find_mandatory_field(vc_element, "Directory").attrib["path"] catalog.add_catalog("VehicleCatalog", path) cc_element = element.find("ControllerCatalog") if cc_element is not None: path = find_mandatory_field(cc_element, "Directory").attrib["path"] catalog.add_catalog("ControllerCatalog", path) pc_element = element.find("PedestrianCatalog") if pc_element is not None: path = find_mandatory_field(pc_element, "Directory").attrib["path"] catalog.add_catalog("PedestrianCatalog", path) moc_element = element.find("MiscObjectCatalog") if moc_element is not None: path = find_mandatory_field(moc_element, "Directory").attrib[ "path" ] catalog.add_catalog("MiscObjectCatalog", path) ec_element = element.find("EnvironmentCatalog") if ec_element is not None: path = find_mandatory_field(ec_element, "Directory").attrib["path"] catalog.add_catalog("EnvironmentCatalog", path) mc_element = element.find("ManeuverCatalog") if mc_element is not None: path = find_mandatory_field(mc_element, "Directory").attrib["path"] catalog.add_catalog("ManeuverCatalog", path) tc_element = element.find("TrajectoryCatalog") if tc_element is not None: path = find_mandatory_field(tc_element, "Directory").attrib["path"] catalog.add_catalog("TrajectoryCatalog", path) rc_element = element.find("RouteCatalog") if rc_element is not None: path = find_mandatory_field(rc_element, "Directory").attrib["path"] catalog.add_catalog("RouteCatalog", path) return catalogParses the XML element of Catalog.
Parameters
element:ET.Element- A Catalog element (same as generated by the class itself).
Returns
Catalog- A Catalog object.
Methods
def add_catalog(self, catalogname: str, path: str) ‑> Catalog-
Expand source code
def add_catalog(self, catalogname: str, path: str) -> "Catalog": """Adds a new catalog to be used. Parameters ---------- catalogname : str Name of the catalog. path : str Path to the catalog. Returns ------- Catalog The updated Catalog object. """ if catalogname not in self._CATALOGS: raise ValueError( f"Not a correct catalog, approved catalogs are: {', '.join(self._CATALOGS)}." ) self.catalogs[catalogname] = path return selfAdds a new catalog to be used.
Parameters
catalogname:str- Name of the catalog.
path:str- Path to the catalog.
Returns
Catalog- The updated Catalog object.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Catalog. Returns ------- ET.Element The ElementTree representation of the Catalog. """ catloc = ET.Element("CatalogLocations") for i, catalog in self.catalogs.items(): tmpel = ET.SubElement(catloc, i) ET.SubElement(tmpel, "Directory", {"path": catalog}) return catlocReturns the ElementTree of the Catalog.
Returns
ET.Element- The ElementTree representation of the Catalog.
class CatalogFile (prettyprint: bool = True, encoding: str = 'utf-8')-
Expand source code
class CatalogFile(VersionBase): """The CatalogFile class handles any catalogs in OpenScenario, such as writing, and updating them. Parameters ---------- prettyprint : bool, optional If the final file should have prettyprint or not. Default is True. encoding : str, optional The encoding of the file. Default is "utf-8". Attributes ---------- prettyprint : bool If the final file should have prettyprint or not. catalog_element : ET.Element The element that is worked with. filename : str Path to the file to be written to. encoding : str The encoding of the file. Methods ------- get_element() Returns the full ElementTree of the class. add_to_catalog(obj) Adds an element to the catalog. open_catalog(filename) Reads an existing catalog file. create_catalog(filename, catalogtype, description, author) Creates an empty catalog of a desired type. create_catalog_element(catalogtype, description, author) Creates an empty catalog element of a desired type. dump() Writes the new/updated catalog file. """ def __init__( self, prettyprint: bool = True, encoding: str = "utf-8" ) -> None: """Initializes the CatalogFile class. Parameters ---------- prettyprint : bool, optional If the final file should have prettyprint or not. Default is True. encoding : str, optional The encoding of the file. Default is "utf-8". """ self.prettyprint = prettyprint self.catalog_element = None self.filename = "" self.encoding = encoding def add_to_catalog(self, obj: Any) -> "CatalogFile": """Adds an element to the catalog. Parameters ---------- obj : Any Any xosc object (should be matching with the catalog). Returns ------- CatalogFile The updated CatalogFile object. """ if self.catalog_element is None: raise OSError("No file has been created or opened") fileheader = find_mandatory_field(self.catalog_element, "FileHeader") if convert_int(fileheader.attrib["revMinor"]) != obj.version_minor: warnings.warn( "The Catalog and the added object does not have the same OpenSCENARIO version." ) catalogs = find_mandatory_field(self.catalog_element, "Catalog") catalogs.append(obj.get_element()) return self def open_catalog(self, filename: str) -> None: """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: str, catalogtype: str, description: str, author: str, licence=None, creation_date=None, properties=None, ) -> None: """Creates an empty catalog of a desired 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. 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.filename = filename self.catalog_element = self.create_catalog_element( catalogtype, description, author, licence, creation_date, properties, ) def create_catalog_element( self, catalogtype: str, description: str, author: str, licence=None, creation_date=None, properties=None, ) -> ET.Element: """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. 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 Returns ------- ET.Element The created catalog element. """ element = ET.Element( "OpenSCENARIO", attrib={ "xmlns:xsi": XMLNS, "xsi:noNamespaceSchemaLocation": "../../" + XSI, }, ) header = FileHeader( author, description, revMinor=self.version_minor, license=licence, creation_date=creation_date, properties=properties, ) element.append(header.get_element()) ET.SubElement(element, "Catalog", attrib={"name": catalogtype}) return element def dump(self) -> None: """Writes the new/updated catalog file.""" printToFile( self.catalog_element, self.filename, self.prettyprint, self.encoding, )The CatalogFile class handles any catalogs in OpenScenario, such as writing, and updating them.
Parameters
prettyprint:bool, optional- If the final file should have prettyprint or not. Default is True.
encoding:str, optional- The encoding of the file. Default is "utf-8".
Attributes
prettyprint:bool- If the final file should have prettyprint or not.
catalog_element:ET.Element- The element that is worked with.
filename:str- Path to the file to be written to.
encoding:str- The encoding of the file.
Methods
get_element() Returns the full ElementTree of the class. add_to_catalog(obj) Adds an element to the catalog. open_catalog(filename) Reads an existing catalog file. create_catalog(filename, catalogtype, description, author) Creates an empty catalog of a desired type. create_catalog_element(catalogtype, description, author) Creates an empty catalog element of a desired type. dump() Writes the new/updated catalog file.
Initializes the CatalogFile class.
Parameters
prettyprint:bool, optional- If the final file should have prettyprint or not. Default is True.
encoding:str, optional- The encoding of the file. Default is "utf-8".
Ancestors
Methods
def add_to_catalog(self, obj: Any) ‑> CatalogFile-
Expand source code
def add_to_catalog(self, obj: Any) -> "CatalogFile": """Adds an element to the catalog. Parameters ---------- obj : Any Any xosc object (should be matching with the catalog). Returns ------- CatalogFile The updated CatalogFile object. """ if self.catalog_element is None: raise OSError("No file has been created or opened") fileheader = find_mandatory_field(self.catalog_element, "FileHeader") if convert_int(fileheader.attrib["revMinor"]) != obj.version_minor: warnings.warn( "The Catalog and the added object does not have the same OpenSCENARIO version." ) catalogs = find_mandatory_field(self.catalog_element, "Catalog") catalogs.append(obj.get_element()) return selfAdds an element to the catalog.
Parameters
obj:Any- Any xosc object (should be matching with the catalog).
Returns
CatalogFile- The updated CatalogFile object.
def create_catalog(self,
filename: str,
catalogtype: str,
description: str,
author: str,
licence=None,
creation_date=None,
properties=None) ‑> None-
Expand source code
def create_catalog( self, filename: str, catalogtype: str, description: str, author: str, licence=None, creation_date=None, properties=None, ) -> None: """Creates an empty catalog of a desired 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. 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.filename = filename self.catalog_element = self.create_catalog_element( catalogtype, description, author, licence, creation_date, properties, )Creates an empty catalog of a desired 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.
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
def create_catalog_element(self,
catalogtype: str,
description: str,
author: str,
licence=None,
creation_date=None,
properties=None) ‑> xml.etree.ElementTree.Element-
Expand source code
def create_catalog_element( self, catalogtype: str, description: str, author: str, licence=None, creation_date=None, properties=None, ) -> ET.Element: """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. 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 Returns ------- ET.Element The created catalog element. """ element = ET.Element( "OpenSCENARIO", attrib={ "xmlns:xsi": XMLNS, "xsi:noNamespaceSchemaLocation": "../../" + XSI, }, ) header = FileHeader( author, description, revMinor=self.version_minor, license=licence, creation_date=creation_date, properties=properties, ) element.append(header.get_element()) ET.SubElement(element, "Catalog", attrib={"name": catalogtype}) return elementcreate_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.
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
Returns
ET.Element- The created catalog element.
def dump(self) ‑> None-
Expand source code
def dump(self) -> None: """Writes the new/updated catalog file.""" printToFile( self.catalog_element, self.filename, self.prettyprint, self.encoding, )Writes the new/updated catalog file.
def open_catalog(self, filename: str) ‑> None-
Expand source code
def open_catalog(self, filename: str) -> None: """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()Reads an existing catalog file.
Parameters
filename:str- Path to the catalog file.
class CatalogReference (catalogname: str, entryname: str)-
Expand source code
class CatalogReference(VersionBase): """CatalogReference creates a 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 catalog reference. Methods ------- parse(element) Parses an 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: str, entryname: str) -> None: """Initializes 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: object) -> bool: if isinstance(other, CatalogReference): if ( self.get_attributes() == other.get_attributes() and self.parameterassignments == other.parameterassignments ): return True return False @staticmethod def parse(element: ET.Element) -> "CatalogReference": """Parses the XML element of CatalogReference. Parameters ---------- element : ET.Element A CatalogReference element (same as generated by the class itself). Returns ------- CatalogReference A CatalogReference object. """ catalogname = element.attrib["catalogName"] entryname = element.attrib["entryName"] reference = CatalogReference(catalogname, entryname) parameter_assignments = element.find("ParameterAssignments") if parameter_assignments is not 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: str, value: str ) -> "CatalogReference": """Adds a parameter and value to the catalog reference. Parameters ---------- parameterref : str Name of the parameter. value : str Assigned value of the parameter. Returns ------- CatalogReference The updated CatalogReference object. """ self.parameterassignments.append( ParameterAssignment(parameterref, value) ) return self def get_attributes(self) -> dict[str, str]: """Returns the attributes of the CatalogReference as a dictionary. Returns ------- dict A dictionary of all attributes of the CatalogReference. """ return {"catalogName": self.catalogname, "entryName": self.entryname} def get_element(self) -> ET.Element: """Returns the ElementTree of the CatalogReference. Returns ------- ET.Element The ElementTree representation 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 elementCatalogReference creates a 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:listofParameterAssignment- The parameter assignments for the given catalog reference.
Methods
parse(element) Parses an 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.
Initializes the CatalogReference.
Parameters
catalogname:str- Name of the catalog.
entryname:str- Name of the entry in the catalog.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> CatalogReference-
Expand source code
@staticmethod def parse(element: ET.Element) -> "CatalogReference": """Parses the XML element of CatalogReference. Parameters ---------- element : ET.Element A CatalogReference element (same as generated by the class itself). Returns ------- CatalogReference A CatalogReference object. """ catalogname = element.attrib["catalogName"] entryname = element.attrib["entryName"] reference = CatalogReference(catalogname, entryname) parameter_assignments = element.find("ParameterAssignments") if parameter_assignments is not None: parameters = parameter_assignments.findall("ParameterAssignment") for parameter in parameters: parameter_assignment = ParameterAssignment.parse(parameter) reference.parameterassignments.append(parameter_assignment) return referenceParses the XML element of CatalogReference.
Parameters
element:ET.Element- A CatalogReference element (same as generated by the class itself).
Returns
CatalogReference- A CatalogReference object.
Methods
def add_parameter_assignment(self, parameterref: str, value: str) ‑> CatalogReference-
Expand source code
def add_parameter_assignment( self, parameterref: str, value: str ) -> "CatalogReference": """Adds a parameter and value to the catalog reference. Parameters ---------- parameterref : str Name of the parameter. value : str Assigned value of the parameter. Returns ------- CatalogReference The updated CatalogReference object. """ self.parameterassignments.append( ParameterAssignment(parameterref, value) ) return selfAdds a parameter and value to the catalog reference.
Parameters
parameterref:str- Name of the parameter.
value:str- Assigned value of the parameter.
Returns
CatalogReference- The updated CatalogReference object.
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the CatalogReference as a dictionary. Returns ------- dict A dictionary of all attributes of the CatalogReference. """ return {"catalogName": self.catalogname, "entryName": self.entryname}Returns the attributes of the CatalogReference as a dictionary.
Returns
dict- A dictionary of all attributes of the CatalogReference.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the CatalogReference. Returns ------- ET.Element The ElementTree representation 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 elementReturns the ElementTree of the CatalogReference.
Returns
ET.Element- The ElementTree representation of the CatalogReference.
class Center (x: float, y: float, z: float)-
Expand source code
class Center(VersionBase): """The Center class creates a center point for a bounding box, reference point of a vehicle is the back axle. Parameters ---------- x : float X distance from back axle to center. y : float Y distance from back axle to center. z : float Z distance from back axle to center. Attributes ---------- x : float X distance from back axle to center. y : float Y distance from back axle to center. z : float Z distance from back axle to center. Methods ------- parse(element) Parses an 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, x: float, y: float, z: float) -> None: """Initializes the Center. Parameters ---------- x : float X distance from back axle to center. y : float Y distance from back axle to center. z : float Z distance from back axle to center. """ self.x = convert_float(x) self.y = convert_float(y) self.z = convert_float(z) @staticmethod def parse(element: ET.Element) -> "Center": """Parses the XML element of Center. Parameters ---------- element : ET.Element A Center element (same as generated by the class itself). Returns ------- 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: object) -> bool: if isinstance(other, Center): if self.get_attributes() == other.get_attributes(): return True return False def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Center as a dictionary. Returns ------- dict A dictionary of all attributes of the Center. """ return {"x": str(self.x), "y": str(self.y), "z": str(self.z)} def get_element(self) -> ET.Element: """Returns the ElementTree of the Center. Returns ------- ET.Element The ElementTree representation of the Center. """ element = ET.Element("Center", attrib=self.get_attributes()) return elementThe Center class creates a center point for a bounding box, reference point of a vehicle is the back axle.
Parameters
x:float- X distance from back axle to center.
y:float- Y distance from back axle to center.
z:float- Z distance from back axle to center.
Attributes
x:float- X distance from back axle to center.
y:float- Y distance from back axle to center.
z:float- Z distance from back axle to center.
Methods
parse(element) Parses an 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.
Initializes the Center.
Parameters
x:float- X distance from back axle to center.
y:float- Y distance from back axle to center.
z:float- Z distance from back axle to center.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Center-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Center": """Parses the XML element of Center. Parameters ---------- element : ET.Element A Center element (same as generated by the class itself). Returns ------- 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)Parses the XML element of Center.
Parameters
element:ET.Element- A Center element (same as generated by the class itself).
Returns
Center- A Center object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Center as a dictionary. Returns ------- dict A dictionary of all attributes of the Center. """ return {"x": str(self.x), "y": str(self.y), "z": str(self.z)}Returns the attributes of the Center as a dictionary.
Returns
dict- A dictionary of all attributes of the Center.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Center. Returns ------- ET.Element The ElementTree representation of the Center. """ element = ET.Element("Center", attrib=self.get_attributes()) return elementReturns the ElementTree of the Center.
Returns
ET.Element- The ElementTree representation of the Center.
class Color (color_type: ColorType,
color_definition: scenariogeneration.xosc.utils._ColorDefinition)-
Expand source code
class Color(VersionBase): """Color creates a Color element of OpenSCENARIO (valid from OpenSCENARIO V1.2). 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 an 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, color_type: ColorType, color_definition: _ColorDefinition ) -> None: """Initializes the Color. Parameters ---------- color_type : ColorType Semantic value of color. color_definition : _ColorDefinition 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: object) -> bool: 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: ET.Element) -> "Color": """Parses the XML element of Color. Parameters ---------- element : ET.Element A Color element (same as generated by the class itself). Returns ------- Color A Color object. """ color_type = convert_enum(element.attrib["colorType"], ColorType) if element.find("ColorRgb") is not None: color_def = ColorRGB.parse( find_mandatory_field(element, "ColorRgb") ) elif element.find("ColorCmyk") is not None: color_def = ColorCMYK.parse( find_mandatory_field(element, "ColorCmyk") ) return Color(color_type, color_def) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Color as a dictionary. Returns ------- dict A dictionary of all attributes of the Color. """ retdict = {} retdict["colorType"] = self.color_type.get_name() return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the Color. Returns ------- ET.Element The ElementTree representation of the Color. """ if not self.isVersionEqLarger(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 elementColor creates a Color element of OpenSCENARIO (valid from OpenSCENARIO V1.2).
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 an 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.
Initializes the Color.
Parameters
color_type:ColorType- Semantic value of color.
color_definition:_ColorDefinition- The color definition.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Color-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Color": """Parses the XML element of Color. Parameters ---------- element : ET.Element A Color element (same as generated by the class itself). Returns ------- Color A Color object. """ color_type = convert_enum(element.attrib["colorType"], ColorType) if element.find("ColorRgb") is not None: color_def = ColorRGB.parse( find_mandatory_field(element, "ColorRgb") ) elif element.find("ColorCmyk") is not None: color_def = ColorCMYK.parse( find_mandatory_field(element, "ColorCmyk") ) return Color(color_type, color_def)Parses the XML element of Color.
Parameters
element:ET.Element- A Color element (same as generated by the class itself).
Returns
Color- A Color object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Color as a dictionary. Returns ------- dict A dictionary of all attributes of the Color. """ retdict = {} retdict["colorType"] = self.color_type.get_name() return retdictReturns the attributes of the Color as a dictionary.
Returns
dict- A dictionary of all attributes of the Color.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Color. Returns ------- ET.Element The ElementTree representation of the Color. """ if not self.isVersionEqLarger(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 elementReturns the ElementTree of the Color.
Returns
ET.Element- The ElementTree representation of the Color.
class ColorCMYK (cyan: float = 0, magenta: float = 0, yellow: float = 0, key: float = 0)-
Expand source code
class ColorCMYK(_ColorDefinition): """ColorCMYK creates a ColorCMYK element of OpenSCENARIO (valid from OpenSCENARIO V1.2). Parameters ---------- cyan : float, optional Cyan component (0..1). Default is 0. magenta : float, optional Magenta component (0..1). Default is 0. yellow : float, optional Yellow component (0..1). Default is 0. key : float, optional Black component (0..1). Default is 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 an 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, cyan: float = 0, magenta: float = 0, yellow: float = 0, key: float = 0, ) -> None: """Initializes the ColorCMYK. Parameters ---------- cyan : float, optional Cyan component (0..1). Default is 0. magenta : float, optional Magenta component (0..1). Default is 0. yellow : float, optional Yellow component (0..1). Default is 0. key : float, optional Black component (0..1). Default is 0. """ self.cyan = cyan self.magenta = magenta self.yellow = yellow self.key = key def __eq__(self, other: object) -> bool: if isinstance(other, ColorCMYK): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "ColorCMYK": """Parses the XML element of ColorCMYK. Parameters ---------- element : ET.Element A ColorCMYK element (same as generated by the class itself). Returns ------- ColorCMYK A 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) -> dict[str, str]: """Returns the attributes of the ColorCMYK as a dictionary. Returns ------- dict A dictionary of all attributes of the ColorCMYK. """ 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) -> ET.Element: """Returns the ElementTree of the ColorCMYK. Returns ------- ET.Element The ElementTree representation of the ColorCMYK. """ if not self.isVersionEqLarger(minor=2): raise OpenSCENARIOVersionError( "ColorCMYK was introduced in OpenSCENARIO V1.2" ) element = ET.Element("ColorCmyk", attrib=self.get_attributes()) return elementColorCMYK creates a ColorCMYK element of OpenSCENARIO (valid from OpenSCENARIO V1.2).
Parameters
cyan:float, optional- Cyan component (0..1). Default is 0.
magenta:float, optional- Magenta component (0..1). Default is 0.
yellow:float, optional- Yellow component (0..1). Default is 0.
key:float, optional- Black component (0..1). Default is 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 an 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.
Initializes the ColorCMYK.
Parameters
cyan:float, optional- Cyan component (0..1). Default is 0.
magenta:float, optional- Magenta component (0..1). Default is 0.
yellow:float, optional- Yellow component (0..1). Default is 0.
key:float, optional- Black component (0..1). Default is 0.
Ancestors
- scenariogeneration.xosc.utils._ColorDefinition
- VersionBase
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> ColorCMYK-
Expand source code
@staticmethod def parse(element: ET.Element) -> "ColorCMYK": """Parses the XML element of ColorCMYK. Parameters ---------- element : ET.Element A ColorCMYK element (same as generated by the class itself). Returns ------- ColorCMYK A ColorCMYK object. """ cyan = element.attrib["cyan"] magenta = element.attrib["magenta"] yellow = element.attrib["yellow"] key = element.attrib["key"] return ColorCMYK(cyan, magenta, yellow, key)Parses the XML element of ColorCMYK.
Parameters
element:ET.Element- A ColorCMYK element (same as generated by the class itself).
Returns
ColorCMYK- A ColorCMYK object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the ColorCMYK as a dictionary. Returns ------- dict A dictionary of all attributes of the ColorCMYK. """ retdict = {} retdict["cyan"] = str(self.cyan) retdict["magenta"] = str(self.magenta) retdict["yellow"] = str(self.yellow) retdict["key"] = str(self.key) return retdictReturns the attributes of the ColorCMYK as a dictionary.
Returns
dict- A dictionary of all attributes of the ColorCMYK.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the ColorCMYK. Returns ------- ET.Element The ElementTree representation of the ColorCMYK. """ if not self.isVersionEqLarger(minor=2): raise OpenSCENARIOVersionError( "ColorCMYK was introduced in OpenSCENARIO V1.2" ) element = ET.Element("ColorCmyk", attrib=self.get_attributes()) return elementReturns the ElementTree of the ColorCMYK.
Returns
ET.Element- The ElementTree representation of the ColorCMYK.
class ColorRGB (red: float = 0, green: float = 0, blue: float = 0)-
Expand source code
class ColorRGB(_ColorDefinition): """ColorRGB creates a ColorRGB element of OpenSCENARIO (valid from OpenSCENARIO V1.2). Parameters ---------- red : float, optional Red component (0..1). Default is 0. green : float, optional Green component (0..1). Default is 0. blue : float, optional Blue component (0..1). Default is 0. Attributes ---------- red : float Red component (0..1). green : float Green component (0..1). blue : float Blue component (0..1). Methods ------- parse(element) Parses an 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, red: float = 0, green: float = 0, blue: float = 0 ) -> None: """Initializes the ColorRGB. Parameters ---------- red : float, optional Red component (0..1). Default is 0. green : float, optional Green component (0..1). Default is 0. blue : float, optional Blue component (0..1). Default is 0. """ self.red = red self.green = green self.blue = blue def __eq__(self, other: object) -> bool: if isinstance(other, ColorRGB): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "ColorRGB": """Parses the XML element of ColorRGB. Parameters ---------- element : ET.Element A ColorRGB element (same as generated by the class itself). Returns ------- ColorRGB A ColorRGB object. """ red = element.attrib["red"] green = element.attrib["green"] blue = element.attrib["blue"] return ColorRGB(red, green, blue) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the ColorRGB as a dictionary. Returns ------- dict A dictionary of all attributes of the ColorRGB. """ retdict = {} retdict["red"] = str(self.red) retdict["green"] = str(self.green) retdict["blue"] = str(self.blue) return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the ColorRGB. Returns ------- ET.Element The ElementTree representation of the ColorRGB. """ if not self.isVersionEqLarger(minor=2): raise OpenSCENARIOVersionError( "ColorRGB was introduced in OpenSCENARIO V1.2" ) element = ET.Element("ColorRgb", attrib=self.get_attributes()) return elementColorRGB creates a ColorRGB element of OpenSCENARIO (valid from OpenSCENARIO V1.2).
Parameters
red:float, optional- Red component (0..1). Default is 0.
green:float, optional- Green component (0..1). Default is 0.
blue:float, optional- Blue component (0..1). Default is 0.
Attributes
red:float- Red component (0..1).
green:float- Green component (0..1).
blue:float- Blue component (0..1).
Methods
parse(element) Parses an 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.
Initializes the ColorRGB.
Parameters
red:float, optional- Red component (0..1). Default is 0.
green:float, optional- Green component (0..1). Default is 0.
blue:float, optional- Blue component (0..1). Default is 0.
Ancestors
- scenariogeneration.xosc.utils._ColorDefinition
- VersionBase
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> ColorRGB-
Expand source code
@staticmethod def parse(element: ET.Element) -> "ColorRGB": """Parses the XML element of ColorRGB. Parameters ---------- element : ET.Element A ColorRGB element (same as generated by the class itself). Returns ------- ColorRGB A ColorRGB object. """ red = element.attrib["red"] green = element.attrib["green"] blue = element.attrib["blue"] return ColorRGB(red, green, blue)Parses the XML element of ColorRGB.
Parameters
element:ET.Element- A ColorRGB element (same as generated by the class itself).
Returns
ColorRGB- A ColorRGB object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the ColorRGB as a dictionary. Returns ------- dict A dictionary of all attributes of the ColorRGB. """ retdict = {} retdict["red"] = str(self.red) retdict["green"] = str(self.green) retdict["blue"] = str(self.blue) return retdictReturns the attributes of the ColorRGB as a dictionary.
Returns
dict- A dictionary of all attributes of the ColorRGB.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the ColorRGB. Returns ------- ET.Element The ElementTree representation of the ColorRGB. """ if not self.isVersionEqLarger(minor=2): raise OpenSCENARIOVersionError( "ColorRGB was introduced in OpenSCENARIO V1.2" ) element = ET.Element("ColorRgb", attrib=self.get_attributes()) return elementReturns the ElementTree of the ColorRGB.
Returns
ET.Element- The ElementTree representation of the ColorRGB.
class Controller (name: str,
properties: Properties | None = None,
controller_type: ControllerType | None = None)-
Expand source code
class Controller(_BaseCatalog): """The Controller class creates a controller of OpenScenario. Parameters ---------- name : str Name of the controller. properties : Properties Properties of the controller. controller_type : ControllerType, optional Controller type (valid from V1.2). Default is None. Attributes ---------- name : str Name of the controller. properties : Properties Properties of the controller. controller_type : ControllerType, optional Controller type. Methods ------- parse(element) Parses an 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 controller to an existing catalog. dump_to_catalog(filename, catalogtype, description, author) Creates a new catalog with the controller. get_element() Returns the full ElementTree of the class. get_attributes() Returns a dictionary of all attributes of the class. """ def __init__( self, name: str, properties: Optional[Properties] = None, controller_type: Optional[ControllerType] = None, ) -> None: """Initializes the Controller. Parameters ---------- name : str Name of the controller. properties : Properties Properties of the controller. controller_type : ControllerType, optional Controller type (valid from V1.2). Default is None. """ super().__init__() self.name = name self.properties = ( properties if properties is not None else Properties() ) if not isinstance(self.properties, Properties): raise TypeError("properties input is not of type Properties") self.controller_type = convert_enum( controller_type, ControllerType, True ) def __eq__(self, other: object) -> bool: 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: ET.Element) -> "Controller": """Parses the XML element of Controller. Parameters ---------- element : ET.Element A Controller element (same as generated by the class itself). Returns ------- Controller A Controller object. """ name = element.attrib["name"] properties = Properties() if element.find("Properties"): properties_element = find_mandatory_field(element, "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) -> dict[str, str]: """Returns the attributes of the Controller as a dictionary. Returns ------- dict A dictionary of all attributes of the Controller. """ retdict = {"name": self.name} if self.controller_type: if self.isVersionEqLarger(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) -> ET.Element: """Returns the ElementTree of the Controller. Returns ------- ET.Element The ElementTree representation of the Controller. """ element = ET.Element("Controller", attrib=self.get_attributes()) self.add_parameters_to_element(element) prop_obj = self.properties.get_element() if prop_obj is not None: element.append(prop_obj) return elementThe Controller class creates a controller of OpenScenario.
Parameters
name:str- Name of the controller.
properties:Properties- Properties of the controller.
controller_type:ControllerType, optional- Controller type (valid from V1.2). Default is None.
Attributes
name:str- Name of the controller.
properties:Properties- Properties of the controller.
controller_type:ControllerType, optional- Controller type.
Methods
parse(element) Parses an 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 controller to an existing catalog. dump_to_catalog(filename, catalogtype, description, author) Creates a new catalog with the controller. get_element() Returns the full ElementTree of the class. get_attributes() Returns a dictionary of all attributes of the class.
Initializes the Controller.
Parameters
name:str- Name of the controller.
properties:Properties- Properties of the controller.
controller_type:ControllerType, optional- Controller type (valid from V1.2). Default is None.
Ancestors
- scenariogeneration.xosc.utils._BaseCatalog
- VersionBase
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Controller-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Controller": """Parses the XML element of Controller. Parameters ---------- element : ET.Element A Controller element (same as generated by the class itself). Returns ------- Controller A Controller object. """ name = element.attrib["name"] properties = Properties() if element.find("Properties"): properties_element = find_mandatory_field(element, "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 controllerParses the XML element of Controller.
Parameters
element:ET.Element- A Controller element (same as generated by the class itself).
Returns
Controller- A Controller object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Controller as a dictionary. Returns ------- dict A dictionary of all attributes of the Controller. """ retdict = {"name": self.name} if self.controller_type: if self.isVersionEqLarger(minor=2): retdict["controllerType"] = self.controller_type.get_name() else: raise OpenSCENARIOVersionError( "controllerType was introduced in OSC v1.2" ) return retdictReturns the attributes of the Controller as a dictionary.
Returns
dict- A dictionary of all attributes of the Controller.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Controller. Returns ------- ET.Element The ElementTree representation of the Controller. """ element = ET.Element("Controller", attrib=self.get_attributes()) self.add_parameters_to_element(element) prop_obj = self.properties.get_element() if prop_obj is not None: element.append(prop_obj) return elementReturns the ElementTree of the Controller.
Returns
ET.Element- The ElementTree representation of the Controller.
class Dimensions (width: float, length: float, height: float)-
Expand source code
class Dimensions(VersionBase): """The Dimensions class describes the size of an entity. Parameters ---------- width : float The width of the entity. length : float The length of the entity. height : float The height of the entity. Attributes ---------- width : float The width of the entity. length : float The length of the entity. height : float The height of the entity. Methods ------- parse(element) Parses an 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, width: float, length: float, height: float) -> None: """Initializes the Dimensions. Parameters ---------- width : float The width of the entity. length : float The length 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: ET.Element) -> "Dimensions": """Parses the XML element of Dimensions. Parameters ---------- element : ET.Element A Dimensions element (same as generated by the class itself). Returns ------- 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: object) -> bool: if isinstance(other, Dimensions): if self.get_attributes() == other.get_attributes(): return True return False def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Dimensions as a dictionary. Returns ------- dict A dictionary of all attributes of the Dimensions. """ return { "width": str(self.width), "length": str(self.length), "height": str(self.height), } def get_element(self) -> ET.Element: """Returns the ElementTree of the Dimensions. Returns ------- ET.Element The ElementTree representation of the Dimensions. """ element = ET.Element("Dimensions", attrib=self.get_attributes()) return elementThe Dimensions class describes the size of an entity.
Parameters
width:float- The width of the entity.
length:float- The length of the entity.
height:float- The height of the entity.
Attributes
width:float- The width of the entity.
length:float- The length of the entity.
height:float- The height of the entity.
Methods
parse(element) Parses an 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.
Initializes the Dimensions.
Parameters
width:float- The width of the entity.
length:float- The length of the entity.
height:float- The height of the entity.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Dimensions-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Dimensions": """Parses the XML element of Dimensions. Parameters ---------- element : ET.Element A Dimensions element (same as generated by the class itself). Returns ------- 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)Parses the XML element of Dimensions.
Parameters
element:ET.Element- A Dimensions element (same as generated by the class itself).
Returns
Dimensions- A Dimensions object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Dimensions as a dictionary. Returns ------- dict A dictionary of all attributes of the Dimensions. """ return { "width": str(self.width), "length": str(self.length), "height": str(self.height), }Returns the attributes of the Dimensions as a dictionary.
Returns
dict- A dictionary of all attributes of the Dimensions.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Dimensions. Returns ------- ET.Element The ElementTree representation of the Dimensions. """ element = ET.Element("Dimensions", attrib=self.get_attributes()) return elementReturns the ElementTree of the Dimensions.
Returns
ET.Element- The ElementTree representation of the Dimensions.
class DirectionOfTravelDistribution (opposite: float, same: float)-
Expand source code
class DirectionOfTravelDistribution(VersionBase): """DirectionOfTravelDistribution creates a DirectionOfTravelDistribution element of OpenSCENARIO (valid from OpenSCENARIO V1.2). Parameters ---------- opposite : float Weight of traffic going against the reference entity. same : float Weight of traffic going the same way as the reference entity. Attributes ---------- opposite : float Weight of traffic going against the reference entity. same : float Weight of traffic going the same way as the reference entity. Methods ------- parse(element) Parses an 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, opposite: float, same: float) -> None: """Initializes the DirectionOfTravelDistribution. Parameters ---------- opposite : float Weight of traffic going against the reference entity. same : float Weight of traffic going the same way as the reference entity. """ self.opposite = convert_float(opposite) self.same = convert_float(same) def __eq__(self, other: object) -> bool: if isinstance(other, DirectionOfTravelDistribution): if other.get_attributes() == self.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "DirectionOfTravelDistribution": """Parses the XML element of DirectionOfTravelDistribution. Parameters ---------- element : ET.Element A DirectionOfTravelDistribution element (same as generated by the class itself). Returns ------- DirectionOfTravelDistribution A DirectionOfTravelDistribution object. """ return DirectionOfTravelDistribution( convert_float(element.attrib["opposite"]), convert_float(element.attrib["same"]), ) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the DirectionOfTravelDistribution as a dictionary. Returns ------- dict A dictionary of all attributes of the DirectionOfTravelDistribution. """ retdict = {"opposite": str(self.opposite), "same": str(self.same)} return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the DirectionOfTravelDistribution. Returns ------- ET.Element The ElementTree representation of the DirectionOfTravelDistribution. """ if not self.isVersionEqLarger(minor=2): raise OpenSCENARIOVersionError( "DirectionOfTravelDistribution was introduced in OpenSCENARIO V1.2" ) element = ET.Element( "DirectionOfTravelDistribution", attrib=self.get_attributes() ) return elementDirectionOfTravelDistribution creates a DirectionOfTravelDistribution element of OpenSCENARIO (valid from OpenSCENARIO V1.2).
Parameters
opposite:float- Weight of traffic going against the reference entity.
same:float- Weight of traffic going the same way as the reference entity.
Attributes
opposite:float- Weight of traffic going against the reference entity.
same:float- Weight of traffic going the same way as the reference entity.
Methods
parse(element) Parses an 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.
Initializes the DirectionOfTravelDistribution.
Parameters
opposite:float- Weight of traffic going against the reference entity.
same:float- Weight of traffic going the same way as the reference entity.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> DirectionOfTravelDistribution-
Expand source code
@staticmethod def parse(element: ET.Element) -> "DirectionOfTravelDistribution": """Parses the XML element of DirectionOfTravelDistribution. Parameters ---------- element : ET.Element A DirectionOfTravelDistribution element (same as generated by the class itself). Returns ------- DirectionOfTravelDistribution A DirectionOfTravelDistribution object. """ return DirectionOfTravelDistribution( convert_float(element.attrib["opposite"]), convert_float(element.attrib["same"]), )Parses the XML element of DirectionOfTravelDistribution.
Parameters
element:ET.Element- A DirectionOfTravelDistribution element (same as generated by the class itself).
Returns
DirectionOfTravelDistribution- A DirectionOfTravelDistribution object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the DirectionOfTravelDistribution as a dictionary. Returns ------- dict A dictionary of all attributes of the DirectionOfTravelDistribution. """ retdict = {"opposite": str(self.opposite), "same": str(self.same)} return retdictReturns the attributes of the DirectionOfTravelDistribution as a dictionary.
Returns
dict- A dictionary of all attributes of the DirectionOfTravelDistribution.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the DirectionOfTravelDistribution. Returns ------- ET.Element The ElementTree representation of the DirectionOfTravelDistribution. """ if not self.isVersionEqLarger(minor=2): raise OpenSCENARIOVersionError( "DirectionOfTravelDistribution was introduced in OpenSCENARIO V1.2" ) element = ET.Element( "DirectionOfTravelDistribution", attrib=self.get_attributes() ) return elementReturns the ElementTree of the DirectionOfTravelDistribution.
Returns
ET.Element- The ElementTree representation of the DirectionOfTravelDistribution.
class DynamicsConstraints (max_acceleration: float | None = None,
max_deceleration: float | None = None,
max_speed: float | None = None,
max_acceleration_rate: float | None = None,
max_deceleration_rate: float | None = None)-
Expand source code
class DynamicsConstraints(VersionBase): """DynamicsConstraints is used by triggers. Parameters ---------- max_acceleration : float, optional Maximum acceleration allowed. Default is None. max_deceleration : float, optional Maximum deceleration allowed. Default is None. max_speed : float, optional Maximum speed allowed. Default is None. max_acceleration_rate : float, optional Maximum acceleration rate allowed. Default is None. max_deceleration_rate : float, optional Maximum deceleration rate allowed. Default is None. Attributes ---------- max_acceleration : float, optional Maximum acceleration allowed. max_deceleration : float, optional Maximum deceleration allowed. max_speed : float, optional Maximum speed allowed. max_acceleration_rate : float, optional Maximum acceleration rate allowed. max_deceleration_rate : float, optional Maximum deceleration rate allowed. Methods ------- parse(element) Parses an ElementTree created by the class and returns an instance of the class. is_filled() Checks if 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: Optional[float] = None, max_deceleration: Optional[float] = None, max_speed: Optional[float] = None, max_acceleration_rate: Optional[float] = None, max_deceleration_rate: Optional[float] = None, ) -> None: """Initializes the DynamicsConstraints. Parameters ---------- max_acceleration : float, optional Maximum acceleration allowed. Default is None. max_deceleration : float, optional Maximum deceleration allowed. Default is None. max_speed : float, optional Maximum speed allowed. Default is None. max_acceleration_rate : float, optional Maximum acceleration rate allowed. Default is None. max_deceleration_rate : float, optional Maximum deceleration rate allowed. Default is None. """ 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: ET.Element) -> "DynamicsConstraints": """Parses the XML element of DynamicsConstraints. Parameters ---------- element : ET.Element A DynamicsConstraints element (same as generated by the class itself). Returns ------- DynamicsConstraints A DynamicsConstraints 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: object) -> bool: if isinstance(other, DynamicsConstraints): if self.get_attributes() == other.get_attributes(): return True return False def is_filled(self) -> bool: """Checks if any constraints are set. Returns ------- bool True if any constraints are set, False otherwise. """ if self.max_acceleration or self.max_deceleration or self.max_speed: return True else: return False def get_attributes(self) -> dict[str, str]: """Returns the attributes of the DynamicsConstraints as a dictionary. Returns ------- dict A dictionary of all attributes of the DynamicsConstraints. """ 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.isVersionEqLarger(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.isVersionEqLarger(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: str = "DynamicConstraints") -> ET.Element: """Returns the ElementTree of the DynamicsConstraints. Parameters ---------- name : str, optional The name of the element. Default is "DynamicConstraints". Returns ------- ET.Element The ElementTree representation of the DynamicsConstraints. """ return ET.Element(name, attrib=self.get_attributes())DynamicsConstraints is used by triggers.
Parameters
max_acceleration:float, optional- Maximum acceleration allowed. Default is None.
max_deceleration:float, optional- Maximum deceleration allowed. Default is None.
max_speed:float, optional- Maximum speed allowed. Default is None.
max_acceleration_rate:float, optional- Maximum acceleration rate allowed. Default is None.
max_deceleration_rate:float, optional- Maximum deceleration rate allowed. Default is None.
Attributes
max_acceleration:float, optional- Maximum acceleration allowed.
max_deceleration:float, optional- Maximum deceleration allowed.
max_speed:float, optional- Maximum speed allowed.
max_acceleration_rate:float, optional- Maximum acceleration rate allowed.
max_deceleration_rate:float, optional- Maximum deceleration rate allowed.
Methods
parse(element) Parses an ElementTree created by the class and returns an instance of the class. is_filled() Checks if any constraints are set. get_element() Returns the full ElementTree of the class. get_attributes() Returns a dictionary of all attributes of the class.
Initializes the DynamicsConstraints.
Parameters
max_acceleration:float, optional- Maximum acceleration allowed. Default is None.
max_deceleration:float, optional- Maximum deceleration allowed. Default is None.
max_speed:float, optional- Maximum speed allowed. Default is None.
max_acceleration_rate:float, optional- Maximum acceleration rate allowed. Default is None.
max_deceleration_rate:float, optional- Maximum deceleration rate allowed. Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> DynamicsConstraints-
Expand source code
@staticmethod def parse(element: ET.Element) -> "DynamicsConstraints": """Parses the XML element of DynamicsConstraints. Parameters ---------- element : ET.Element A DynamicsConstraints element (same as generated by the class itself). Returns ------- DynamicsConstraints A DynamicsConstraints 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, )Parses the XML element of DynamicsConstraints.
Parameters
element:ET.Element- A DynamicsConstraints element (same as generated by the class itself).
Returns
DynamicsConstraints- A DynamicsConstraints object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the DynamicsConstraints as a dictionary. Returns ------- dict A dictionary of all attributes of the DynamicsConstraints. """ 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.isVersionEqLarger(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.isVersionEqLarger(minor=2): raise OpenSCENARIOVersionError( "maxDecelerationRate was introduced in OpenSCENARIO V1.2" ) retdict["maxDecelerationRate"] = str(self.max_deceleration_rate) return retdictReturns the attributes of the DynamicsConstraints as a dictionary.
Returns
dict- A dictionary of all attributes of the DynamicsConstraints.
def get_element(self, name: str = 'DynamicConstraints') ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self, name: str = "DynamicConstraints") -> ET.Element: """Returns the ElementTree of the DynamicsConstraints. Parameters ---------- name : str, optional The name of the element. Default is "DynamicConstraints". Returns ------- ET.Element The ElementTree representation of the DynamicsConstraints. """ return ET.Element(name, attrib=self.get_attributes())Returns the ElementTree of the DynamicsConstraints.
Parameters
name:str, optional- The name of the element. Default is "DynamicConstraints".
Returns
ET.Element- The ElementTree representation of the DynamicsConstraints.
def is_filled(self) ‑> bool-
Expand source code
def is_filled(self) -> bool: """Checks if any constraints are set. Returns ------- bool True if any constraints are set, False otherwise. """ if self.max_acceleration or self.max_deceleration or self.max_speed: return True else: return FalseChecks if any constraints are set.
Returns
bool- True if any constraints are set, False otherwise.
class EntityRef (entity: str)-
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 an 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: str) -> None: """Initializes the EntityRef. Parameters ---------- entity : str Name of the entity. """ self.entity = entity @staticmethod def parse(element: ET.Element) -> "EntityRef": """Parses the XML element of EntityRef. Parameters ---------- element : ET.Element An EntityRef element (same as generated by the class itself). Returns ------- EntityRef An EntityRef object. """ entity = element.attrib["entityRef"] return EntityRef(entity) def __eq__(self, other: object) -> bool: if isinstance(other, EntityRef): if self.entity == other.entity: return True return False def get_attributes(self) -> dict[str, str]: """Returns the attributes of the EntityRef as a dictionary. Returns ------- dict A dictionary of all attributes of the EntityRef. """ return {"entityRef": self.entity} def get_element(self, elementname: str = "EntityRef") -> ET.Element: """Returns the ElementTree of the EntityRef. Parameters ---------- elementname : str Used if another name is needed for the EntityRef. Default is "EntityRef". Returns ------- ET.Element The ElementTree representation of the EntityRef. """ return ET.Element(elementname, attrib=self.get_attributes())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 an 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.
Initializes the EntityRef.
Parameters
entity:str- Name of the entity.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> EntityRef-
Expand source code
@staticmethod def parse(element: ET.Element) -> "EntityRef": """Parses the XML element of EntityRef. Parameters ---------- element : ET.Element An EntityRef element (same as generated by the class itself). Returns ------- EntityRef An EntityRef object. """ entity = element.attrib["entityRef"] return EntityRef(entity)Parses the XML element of EntityRef.
Parameters
element:ET.Element- An EntityRef element (same as generated by the class itself).
Returns
EntityRef- An EntityRef object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the EntityRef as a dictionary. Returns ------- dict A dictionary of all attributes of the EntityRef. """ return {"entityRef": self.entity}Returns the attributes of the EntityRef as a dictionary.
Returns
dict- A dictionary of all attributes of the EntityRef.
def get_element(self, elementname: str = 'EntityRef') ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self, elementname: str = "EntityRef") -> ET.Element: """Returns the ElementTree of the EntityRef. Parameters ---------- elementname : str Used if another name is needed for the EntityRef. Default is "EntityRef". Returns ------- ET.Element The ElementTree representation of the EntityRef. """ return ET.Element(elementname, attrib=self.get_attributes())Returns the ElementTree of the EntityRef.
Parameters
elementname:str- Used if another name is needed for the EntityRef. Default is "EntityRef".
Returns
ET.Element- The ElementTree representation of the EntityRef.
class Environment (name: str,
timeofday: TimeOfDay | None = None,
weather: Weather | None = None,
roadcondition: RoadCondition | None = None,
parameters: ParameterDeclarations | None = None)-
Expand source code
class Environment(_BaseCatalog): """The Environment class creates an environment used by Environment. Parameters ---------- name : str Name of the environment. If used in catalog name is required. timeofday : TimeOfDay, optional Time of day for the environment. Default is None. weather : Weather, optional Weather of the environment. Default is None. roadcondition : RoadCondition, optional Road condition of the environment. Default is None. parameters : ParameterDeclarations, optional The parameters to be used in the scenario. Default is None. Attributes ---------- name : str Name of the environment. timeofday : TimeOfDay, optional Time of day for the environment. weather : Weather, optional Weather of the environment. roadcondition : RoadCondition, optional Road condition of the environment. parameters : ParameterDeclarations, optional The parameters to be used in the scenario. Methods ------- parse(element) Parses an ElementTree created by the class and returns an instance of the class. append_to_catalog(filename) Adds the environment to an existing catalog. dump_to_catalog(filename, catalogtype, description, author) Creates a new catalog with the environment. get_element() Returns the full ElementTree of the class. get_attributes() Returns a dictionary of all attributes of the class. """ def __init__( self, name: str, timeofday: Optional[TimeOfDay] = None, weather: Optional[Weather] = None, roadcondition: Optional[RoadCondition] = None, parameters: Optional[ParameterDeclarations] = None, ) -> None: """Initializes the Environment. Parameters ---------- name : str Name of the environment. If used in catalog name is required. timeofday : TimeOfDay, optional Time of day for the environment. Default is None. weather : Weather, optional Weather of the environment. Default is None. roadcondition : RoadCondition, optional Road condition of the environment. Default is None. parameters : ParameterDeclarations, optional The parameters to be used in the scenario. Default is 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: object) -> bool: 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: ET.Element) -> "Environment": """Parses the XML element of Environment. Parameters ---------- element : ET.Element An Environment element (same as generated by the class itself). Returns ------- Environment An Environment object. """ name = element.attrib["name"] parameters = None weather = None timeofday = None roadcondition = None if element.find("ParameterDeclarations") is not None: parameters = ParameterDeclarations.parse( find_mandatory_field(element, "ParameterDeclarations") ) if element.find("TimeOfDay") is not None: timeofday = TimeOfDay.parse( find_mandatory_field(element, "TimeOfDay") ) if element.find("Weather") is not None: weather = Weather.parse(find_mandatory_field(element, "Weather")) if element.find("RoadCondition") is not None: roadcondition = RoadCondition.parse( find_mandatory_field(element, "RoadCondition") ) return Environment(name, timeofday, weather, roadcondition, parameters) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Environment as a dictionary. Returns ------- dict A dictionary of all attributes of the Environment. """ return {"name": str(self.name)} def get_element(self) -> ET.Element: """Returns the ElementTree of the Environment. Returns ------- ET.Element The ElementTree representation 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 elementThe Environment class creates an environment used by Environment.
Parameters
name:str- Name of the environment. If used in catalog name is required.
timeofday:TimeOfDay, optional- Time of day for the environment. Default is None.
weather:Weather, optional- Weather of the environment. Default is None.
roadcondition:RoadCondition, optional- Road condition of the environment. Default is None.
parameters:ParameterDeclarations, optional- The parameters to be used in the scenario. Default is None.
Attributes
name:str- Name of the environment.
timeofday:TimeOfDay, optional- Time of day for the environment.
weather:Weather, optional- Weather of the environment.
roadcondition:RoadCondition, optional- Road condition of the environment.
parameters:ParameterDeclarations, optional- The parameters to be used in the scenario.
Methods
parse(element) Parses an ElementTree created by the class and returns an instance of the class. append_to_catalog(filename) Adds the environment to an existing catalog. dump_to_catalog(filename, catalogtype, description, author) Creates a new catalog with the environment. get_element() Returns the full ElementTree of the class. get_attributes() Returns a dictionary of all attributes of the class.
Initializes the Environment.
Parameters
name:str- Name of the environment. If used in catalog name is required.
timeofday:TimeOfDay, optional- Time of day for the environment. Default is None.
weather:Weather, optional- Weather of the environment. Default is None.
roadcondition:RoadCondition, optional- Road condition of the environment. Default is None.
parameters:ParameterDeclarations, optional- The parameters to be used in the scenario. Default is None.
Ancestors
- scenariogeneration.xosc.utils._BaseCatalog
- VersionBase
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Environment-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Environment": """Parses the XML element of Environment. Parameters ---------- element : ET.Element An Environment element (same as generated by the class itself). Returns ------- Environment An Environment object. """ name = element.attrib["name"] parameters = None weather = None timeofday = None roadcondition = None if element.find("ParameterDeclarations") is not None: parameters = ParameterDeclarations.parse( find_mandatory_field(element, "ParameterDeclarations") ) if element.find("TimeOfDay") is not None: timeofday = TimeOfDay.parse( find_mandatory_field(element, "TimeOfDay") ) if element.find("Weather") is not None: weather = Weather.parse(find_mandatory_field(element, "Weather")) if element.find("RoadCondition") is not None: roadcondition = RoadCondition.parse( find_mandatory_field(element, "RoadCondition") ) return Environment(name, timeofday, weather, roadcondition, parameters)Parses the XML element of Environment.
Parameters
element:ET.Element- An Environment element (same as generated by the class itself).
Returns
Environment- An Environment object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Environment as a dictionary. Returns ------- dict A dictionary of all attributes of the Environment. """ return {"name": str(self.name)}Returns the attributes of the Environment as a dictionary.
Returns
dict- A dictionary of all attributes of the Environment.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Environment. Returns ------- ET.Element The ElementTree representation 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 elementReturns the ElementTree of the Environment.
Returns
ET.Element- The ElementTree representation of the Environment.
class FileHeader (author: str,
description: str,
revMinor: int = 3,
license: License | None = None,
creation_date: datetime.datetime | None = None,
properties: Properties | None = None)-
Expand source code
class FileHeader(VersionBase): """FileHeader creates the header of the OpenScenario file. Parameters ---------- author : str The author of the scenario. description : str Description of the scenario. revMinor : int, optional The minor revision of the standard. Default is 2. license : License, optional License (valid from OpenSCENARIO V1.1). Default is None. creation_date : datetime.datetime, optional Optional hardcoded creation date. Default is datetime.datetime.now(). properties : Properties, optional Additional info about the scenario. Default is None. Attributes ---------- author : str The author of the scenario. description : str Description of the scenario. revMinor : int The minor revision of the standard. license : License, optional License. creation_date : datetime.datetime, optional Optional hardcoded creation date. properties : Properties, optional Additional info about the scenario. Methods ------- parse(element) Parses an 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, author: str, description: str, revMinor: int = _MINOR_VERSION, license: Optional[License] = None, creation_date: Optional[dt.datetime] = None, properties: Optional[Properties] = None, ) -> None: """Initializes the FileHeader. Parameters ---------- author : str The author of the scenario. description : str Description of the scenario. revMinor : int, optional The minor revision of the standard. Default is 2. license : License, optional License (valid from OpenSCENARIO V1.1). Default is None. creation_date : datetime.datetime, optional Optional hardcoded creation date. Default is datetime.datetime.now(). properties : Properties, optional Additional info about the scenario. Default is 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: object) -> bool: 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.version_minor == other.version_minor and self.properties == other.properties ): # will not compare date, since this will never be the same return True return False @staticmethod def parse(element: ET.Element) -> "FileHeader": """Parses the XML element of FileHeader. Parameters ---------- element : ET.Element A FileHeader element (same as generated by the class itself). Returns ------- FileHeader A FileHeader object. """ author = element.attrib["author"] description = element.attrib["description"] license = None if element.find("license") is not None: license = License.parse(find_mandatory_field(element, "license")) rev_minor = convert_int(element.attrib["revMinor"]) return FileHeader( author=author, description=description, license=license, revMinor=rev_minor, ) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the FileHeader as a dictionary. Returns ------- dict A dictionary of all attributes of the FileHeader. """ retdict = { "description": self.description, "author": self.author, "revMajor": str(self.version_major), "revMinor": str(self.version_minor), } if self.creation_date is not None: retdict["date"] = self.creation_date.isoformat() else: retdict["date"] = dt.datetime.now().isoformat() return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the FileHeader. Returns ------- ET.Element The ElementTree representation 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 elementFileHeader creates the header of the OpenScenario file.
Parameters
author:str- The author of the scenario.
description:str- Description of the scenario.
revMinor:int, optional- The minor revision of the standard. Default is 2.
license:License, optional- License (valid from OpenSCENARIO V1.1). Default is None.
creation_date:datetime.datetime, optional- Optional hardcoded creation date. Default is datetime.datetime.now().
properties:Properties, optional- Additional info about the scenario. Default is None.
Attributes
author:str- The author of the scenario.
description:str- Description of the scenario.
revMinor:int- The minor revision of the standard.
license:License, optional- License.
creation_date:datetime.datetime, optional- Optional hardcoded creation date.
properties:Properties, optional- Additional info about the scenario.
Methods
parse(element) Parses an 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.
Initializes the FileHeader.
Parameters
author:str- The author of the scenario.
description:str- Description of the scenario.
revMinor:int, optional- The minor revision of the standard. Default is 2.
license:License, optional- License (valid from OpenSCENARIO V1.1). Default is None.
creation_date:datetime.datetime, optional- Optional hardcoded creation date. Default is datetime.datetime.now().
properties:Properties, optional- Additional info about the scenario. Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> FileHeader-
Expand source code
@staticmethod def parse(element: ET.Element) -> "FileHeader": """Parses the XML element of FileHeader. Parameters ---------- element : ET.Element A FileHeader element (same as generated by the class itself). Returns ------- FileHeader A FileHeader object. """ author = element.attrib["author"] description = element.attrib["description"] license = None if element.find("license") is not None: license = License.parse(find_mandatory_field(element, "license")) rev_minor = convert_int(element.attrib["revMinor"]) return FileHeader( author=author, description=description, license=license, revMinor=rev_minor, )Parses the XML element of FileHeader.
Parameters
element:ET.Element- A FileHeader element (same as generated by the class itself).
Returns
FileHeader- A FileHeader object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the FileHeader as a dictionary. Returns ------- dict A dictionary of all attributes of the FileHeader. """ retdict = { "description": self.description, "author": self.author, "revMajor": str(self.version_major), "revMinor": str(self.version_minor), } if self.creation_date is not None: retdict["date"] = self.creation_date.isoformat() else: retdict["date"] = dt.datetime.now().isoformat() return retdictReturns the attributes of the FileHeader as a dictionary.
Returns
dict- A dictionary of all attributes of the FileHeader.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the FileHeader. Returns ------- ET.Element The ElementTree representation 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 elementReturns the ElementTree of the FileHeader.
Returns
ET.Element- The ElementTree representation of the FileHeader.
class Fog (visual_range: int,
bounding_box: BoundingBox | None = None)-
Expand source code
class Fog(VersionBase): """Fog creates a Fog element used by the Weather element of OpenScenario. Parameters ---------- visual_range : int Visual range of fog. bounding_box : BoundingBox, optional Bounding box of fog. Default is None. Attributes ---------- visual_range : int Visual range of fog. bounding_box : BoundingBox, optional Bounding box of fog. Methods ------- parse(element) Parses an 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: int, bounding_box: Optional[BoundingBox] = None ) -> None: """Initializes the Fog. Parameters ---------- visual_range : int Visual range of fog. bounding_box : BoundingBox, optional Bounding box of fog. Default is 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: object) -> bool: 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: ET.Element) -> "Fog": """Parses the XML element of Fog. Parameters ---------- element : ET.Element A Fog element (same as generated by the class itself). Returns ------- Fog A Fog object. """ visual_range = element.attrib["visualRange"] bounding_box = None if element.find("BoundingBox") is not None: bounding_box = BoundingBox.parse( find_mandatory_field(element, "BoundingBox") ) return Fog(visual_range, bounding_box) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Fog as a dictionary. Returns ------- dict A dictionary of all attributes of the Fog. """ retdict = {} retdict["visualRange"] = str(self.visual_range) return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the Fog. Returns ------- ET.Element The ElementTree representation 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 elementFog creates a Fog element used by the Weather element of OpenScenario.
Parameters
visual_range:int- Visual range of fog.
bounding_box:BoundingBox, optional- Bounding box of fog. Default is None.
Attributes
visual_range:int- Visual range of fog.
bounding_box:BoundingBox, optional- Bounding box of fog.
Methods
parse(element) Parses an 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.
Initializes the Fog.
Parameters
visual_range:int- Visual range of fog.
bounding_box:BoundingBox, optional- Bounding box of fog. Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Fog-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Fog": """Parses the XML element of Fog. Parameters ---------- element : ET.Element A Fog element (same as generated by the class itself). Returns ------- Fog A Fog object. """ visual_range = element.attrib["visualRange"] bounding_box = None if element.find("BoundingBox") is not None: bounding_box = BoundingBox.parse( find_mandatory_field(element, "BoundingBox") ) return Fog(visual_range, bounding_box)Parses the XML element of Fog.
Parameters
element:ET.Element- A Fog element (same as generated by the class itself).
Returns
Fog- A Fog object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Fog as a dictionary. Returns ------- dict A dictionary of all attributes of the Fog. """ retdict = {} retdict["visualRange"] = str(self.visual_range) return retdictReturns the attributes of the Fog as a dictionary.
Returns
dict- A dictionary of all attributes of the Fog.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Fog. Returns ------- ET.Element The ElementTree representation 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 elementReturns the ElementTree of the Fog.
Returns
ET.Element- The ElementTree representation of the Fog.
class HitchCoupler (dx: float, dz: float | None = None)-
Expand source code
class HitchCoupler(VersionBase): """HitchCoupler represents the TrailerHitch and TrailerCoupler classes in OpenScenario Parameters ---------- dx : float the relative position in the x axis, relative to the vehicle dz : float the relative position in the z axis, relative to the vehicle, default: None Attributes ---------- dx : float the relative position in the x axis, relative to the vehicle dz : float the relative position in the z axis, relative to the vehicle Methods ------- parse(element) Parses an ElementTree created by the class and returns an instance of the class. get_element() Returns the full ElementTree of the class. """ def __init__(self, dx: float, dz: Optional[float] = None): self.dx = convert_float(dx) self.dz = convert_float(dz) def __eq__(self, other: Any) -> bool: return ( isinstance(other, HitchCoupler) and self.get_attributes() == other.get_attributes() ) @staticmethod def parse(element: ET.Element) -> "HitchCoupler": """Parses the XML element of HitchCoupler. Parameters ---------- element : ET.Element A HitchCoupler element (same as generated by the class itself). Returns ------- HitchCoupler A HitchCoupler object. """ dz = element.attrib.get("dz") return HitchCoupler(element.attrib["dx"], element.attrib.get("dz")) def get_attributes(self) -> dict[str, str]: """returns the attributes of the HitchCoupler""" retdict = {"dx": str(self.dx)} if self.dz is not None: retdict["dz"] = str(self.dz) return retdict def get_element(self, element_name: str) -> ET.Element: """Returns the ElementTree of the HitchCoupler. Parameters ---------- element_name:str if it is a Hitch or a Coupler Returns ------- ET.Element The ElementTree representation of the HitchCoupler. """ if element_name not in ["Hitch", "Coupler"]: raise ValueError( f"{element_name} has to be either Hitch or Coupler" ) if self.isVersionEqLess(minor=2): raise OpenSCENARIOVersionError( f"Trailer{element_name} was " "introduced in OpenScenario 1.3" ) return ET.Element( f"Trailer{element_name}", attrib=self.get_attributes() )HitchCoupler represents the TrailerHitch and TrailerCoupler classes in OpenScenario
Parameters
dx:float- the relative position in the x axis, relative to the vehicle
dz:float- the relative position in the z axis, relative to the vehicle, default: None
Attributes
dx:float- the relative position in the x axis, relative to the vehicle
dz:float- the relative position in the z axis, relative to the vehicle
Methods
parse(element) Parses an ElementTree created by the class and returns an instance of the class. get_element() Returns the full ElementTree of the class.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> HitchCoupler-
Expand source code
@staticmethod def parse(element: ET.Element) -> "HitchCoupler": """Parses the XML element of HitchCoupler. Parameters ---------- element : ET.Element A HitchCoupler element (same as generated by the class itself). Returns ------- HitchCoupler A HitchCoupler object. """ dz = element.attrib.get("dz") return HitchCoupler(element.attrib["dx"], element.attrib.get("dz"))Parses the XML element of HitchCoupler.
Parameters
element:ET.Element- A HitchCoupler element (same as generated by the class itself).
Returns
HitchCoupler- A HitchCoupler object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """returns the attributes of the HitchCoupler""" retdict = {"dx": str(self.dx)} if self.dz is not None: retdict["dz"] = str(self.dz) return retdictreturns the attributes of the HitchCoupler
def get_element(self, element_name: str) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self, element_name: str) -> ET.Element: """Returns the ElementTree of the HitchCoupler. Parameters ---------- element_name:str if it is a Hitch or a Coupler Returns ------- ET.Element The ElementTree representation of the HitchCoupler. """ if element_name not in ["Hitch", "Coupler"]: raise ValueError( f"{element_name} has to be either Hitch or Coupler" ) if self.isVersionEqLess(minor=2): raise OpenSCENARIOVersionError( f"Trailer{element_name} was " "introduced in OpenScenario 1.3" ) return ET.Element( f"Trailer{element_name}", attrib=self.get_attributes() )Returns the ElementTree of the HitchCoupler.
Parameters
element_name:str if it is a Hitch or a Coupler Returns
ET.Element- The ElementTree representation of the HitchCoupler.
class License (name: str, resource: str | None = None, spdxId: str | None = 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, optional Link to URL. Default is None. spdxId : str, optional License identifier. Default is None. Attributes ---------- name : str Name of the License. resource : str, optional Link to URL. spdxId : str, optional License identifier. Methods ------- parse(element) Parses an 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: str, resource: Optional[str] = None, spdxId: Optional[str] = None, ) -> None: """Initializes the License. Parameters ---------- name : str Name of the License. resource : str, optional Link to URL. Default is None. spdxId : str, optional License identifier. Default is None. """ self.name = name self.resource = resource self.spdxId = spdxId def __eq__(self, other: object) -> bool: if isinstance(other, License): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "License": """Parses the XML element of License. Parameters ---------- element : ET.Element A License element (same as generated by the class itself). Returns ------- 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) -> dict[str, str]: """Returns the attributes of the License as a dictionary. Returns ------- dict A dictionary of all attributes 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) -> ET.Element: """Returns the ElementTree of the License. Returns ------- ET.Element The ElementTree representation 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 elementLicense creates the License used by FileHeader in the OpenScenario file (valid from OpenSCENARIO V1.1).
Parameters
name:str- Name of the License.
resource:str, optional- Link to URL. Default is None.
spdxId:str, optional- License identifier. Default is None.
Attributes
name:str- Name of the License.
resource:str, optional- Link to URL.
spdxId:str, optional- License identifier.
Methods
parse(element) Parses an 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.
Initializes the License.
Parameters
name:str- Name of the License.
resource:str, optional- Link to URL. Default is None.
spdxId:str, optional- License identifier. Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> License-
Expand source code
@staticmethod def parse(element: ET.Element) -> "License": """Parses the XML element of License. Parameters ---------- element : ET.Element A License element (same as generated by the class itself). Returns ------- 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)Parses the XML element of License.
Parameters
element:ET.Element- A License element (same as generated by the class itself).
Returns
License- A License object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the License as a dictionary. Returns ------- dict A dictionary of all attributes of the License. """ retdict = {} retdict["name"] = self.name if self.resource: retdict["resource"] = self.resource if self.spdxId: retdict["spdxId"] = self.spdxId return retdictReturns the attributes of the License as a dictionary.
Returns
dict- A dictionary of all attributes of the License.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the License. Returns ------- ET.Element The ElementTree representation 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 elementReturns the ElementTree of the License.
Returns
ET.Element- The ElementTree representation of the License.
class Monitor (name: str, value: bool)-
Expand source code
class Monitor(VersionBase): """Monitor is a declaration of an entry in MonitorDeclarations. Parameters ---------- name : str Name of the monitor. value : bool Initialisation value of the monitor. Attributes ---------- name : str Name of the monitor. value : bool Value of the monitor. Methods ------- parse(element) Parses an 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: str, value: bool) -> None: """Initializes the Monitor. Parameters ---------- name : str Name of the monitor. value : bool Initialisation value of the monitor. """ if not isinstance(name, str) or not isinstance( value, (str, bool, int) ): raise TypeError( "name of monitor must be an string and value must be a bool/str/int" ) self.name = str(name) self.value = convert_bool(value) def __eq__(self, other: object) -> bool: if isinstance(other, Monitor): if other.get_attributes() == self.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "Monitor": """Parses the XML element of Monitor. Parameters ---------- element : ET.Element A Monitor element (same as generated by the class itself). Returns ---------- Monitor An object of type Monitor """ if "name" not in element.attrib: raise ValueError("Monitor must have a name attribute") if "value" not in element.attrib: raise ValueError("Monitor must have a value attribute") return Monitor( element.attrib["name"], convert_bool(element.attrib["value"]) ) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Monitor as a dictionary. Returns ------- dict A dictionary of all attributes of the Monitor. """ retdict = {} retdict["name"] = self.name retdict["value"] = get_bool_string(self.value) return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the MonitorDeclaration. Returns ------- ET.Element The ElementTree representation of the MonitorDeclaration. """ if not self.isVersionEqLarger(minor=3): raise OpenSCENARIOVersionError( "MonitorDeclaration was introduced in OpenSCENARIO V1.3" ) element = ET.Element( "MonitorDeclaration", attrib=self.get_attributes() ) return elementMonitor is a declaration of an entry in MonitorDeclarations.
Parameters
name:str- Name of the monitor.
value:bool- Initialisation value of the monitor.
Attributes
name:str- Name of the monitor.
value:bool- Value of the monitor.
Methods
parse(element) Parses an 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.
Initializes the Monitor.
Parameters
name:str- Name of the monitor.
value:bool- Initialisation value of the monitor.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Monitor-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Monitor": """Parses the XML element of Monitor. Parameters ---------- element : ET.Element A Monitor element (same as generated by the class itself). Returns ---------- Monitor An object of type Monitor """ if "name" not in element.attrib: raise ValueError("Monitor must have a name attribute") if "value" not in element.attrib: raise ValueError("Monitor must have a value attribute") return Monitor( element.attrib["name"], convert_bool(element.attrib["value"]) )Parses the XML element of Monitor.
Parameters
element:ET.Element- A Monitor element (same as generated by the class itself).
Returns
Monitor- An object of type Monitor
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Monitor as a dictionary. Returns ------- dict A dictionary of all attributes of the Monitor. """ retdict = {} retdict["name"] = self.name retdict["value"] = get_bool_string(self.value) return retdictReturns the attributes of the Monitor as a dictionary.
Returns
dict- A dictionary of all attributes of the Monitor.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the MonitorDeclaration. Returns ------- ET.Element The ElementTree representation of the MonitorDeclaration. """ if not self.isVersionEqLarger(minor=3): raise OpenSCENARIOVersionError( "MonitorDeclaration was introduced in OpenSCENARIO V1.3" ) element = ET.Element( "MonitorDeclaration", attrib=self.get_attributes() ) return elementReturns the ElementTree of the MonitorDeclaration.
Returns
ET.Element- The ElementTree representation of the MonitorDeclaration.
class MonitorDeclarations-
Expand source code
class MonitorDeclarations(VersionBase): """The MonitorDeclarations class creates the MonitorDeclarations of OpenScenario (Valid from V1.3). Attributes ---------- monitors : list of Monitor List of Monitor objects. Methods ------- get_element() Returns the full ElementTree of the class. add_monitor(monitor) Adds a Monitor to the MonitorDeclarations. parse(element) Parses an ElementTree created by the class and returns an instance of the class. """ def __init__(self) -> None: """Initializes the MonitorDeclarations.""" self.monitors = [] @staticmethod def parse(element: ET.Element) -> "MonitorDeclarations": """Parses the XML element of MonitorDeclarations. Parameters ---------- element : ET.Element A MonitorDeclarations element (same as generated by the class itself). Returns ------- MonitorDeclarations A MonitorDeclarations object. """ monitor_declarations = MonitorDeclarations() declarations = element.findall("MonitorDeclaration") for declaration in declarations: monitor = Monitor.parse(declaration) monitor_declarations.add_monitor(monitor) return monitor_declarations def __eq__(self, other: object) -> bool: if isinstance(other, MonitorDeclarations): if self.monitors == other.monitors: return True return False def add_monitor(self, monitor: Monitor) -> "MonitorDeclarations": """Adds a Monitor to the MonitorDeclarations. Parameters ---------- monitor : Monitor A new monitor to be added to a MonitorDeclarations object. Returns ------- MonitorDeclarations The updated MonitorDeclarations object. """ if not isinstance(monitor, Monitor): raise TypeError("{monitor} input is not of type Monitor") self.monitors.append(monitor) return self def get_element(self) -> Optional[ET.Element]: """Returns the ElementTree of the MonitorDeclarations. Returns ------- ET.Element or None The ElementTree representation of the MonitorDeclarations, or None if no monitors exist. """ if self.isVersionEqLess(minor=2): raise OpenSCENARIOVersionError( "Monitors were introduced in OSC 1.3" ) element = ET.Element("MonitorDeclarations") for m in self.monitors: element.append(m.get_element()) return elementThe MonitorDeclarations class creates the MonitorDeclarations of OpenScenario (Valid from V1.3).
Attributes
monitors:listofMonitor- List of Monitor objects.
Methods
get_element() Returns the full ElementTree of the class. add_monitor(monitor) Adds a Monitor to the MonitorDeclarations. parse(element) Parses an ElementTree created by the class and returns an instance of the class.
Initializes the MonitorDeclarations.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> MonitorDeclarations-
Expand source code
@staticmethod def parse(element: ET.Element) -> "MonitorDeclarations": """Parses the XML element of MonitorDeclarations. Parameters ---------- element : ET.Element A MonitorDeclarations element (same as generated by the class itself). Returns ------- MonitorDeclarations A MonitorDeclarations object. """ monitor_declarations = MonitorDeclarations() declarations = element.findall("MonitorDeclaration") for declaration in declarations: monitor = Monitor.parse(declaration) monitor_declarations.add_monitor(monitor) return monitor_declarationsParses the XML element of MonitorDeclarations.
Parameters
element:ET.Element- A MonitorDeclarations element (same as generated by the class itself).
Returns
MonitorDeclarations- A MonitorDeclarations object.
Methods
def add_monitor(self,
monitor: Monitor) ‑> MonitorDeclarations-
Expand source code
def add_monitor(self, monitor: Monitor) -> "MonitorDeclarations": """Adds a Monitor to the MonitorDeclarations. Parameters ---------- monitor : Monitor A new monitor to be added to a MonitorDeclarations object. Returns ------- MonitorDeclarations The updated MonitorDeclarations object. """ if not isinstance(monitor, Monitor): raise TypeError("{monitor} input is not of type Monitor") self.monitors.append(monitor) return selfAdds a Monitor to the MonitorDeclarations.
Parameters
monitor:Monitor- A new monitor to be added to a MonitorDeclarations object.
Returns
MonitorDeclarations- The updated MonitorDeclarations object.
def get_element(self) ‑> xml.etree.ElementTree.Element | None-
Expand source code
def get_element(self) -> Optional[ET.Element]: """Returns the ElementTree of the MonitorDeclarations. Returns ------- ET.Element or None The ElementTree representation of the MonitorDeclarations, or None if no monitors exist. """ if self.isVersionEqLess(minor=2): raise OpenSCENARIOVersionError( "Monitors were introduced in OSC 1.3" ) element = ET.Element("MonitorDeclarations") for m in self.monitors: element.append(m.get_element()) return elementReturns the ElementTree of the MonitorDeclarations.
Returns
ET.ElementorNone- The ElementTree representation of the MonitorDeclarations, or None if no monitors exist.
class Orientation (h: float | None = None,
p: float | None = None,
r: float | None = None,
reference: ReferenceContext | None = None)-
Expand source code
class Orientation(VersionBase): """Orientation describes the angular orientation of an entity. Parameters ---------- h : float, optional Header. Default is None. p : float, optional Pitch. Default is None. r : float, optional Roll. Default is None. reference : ReferenceContext, optional Absolute or relative. Default is None. Attributes ---------- h : float, optional Header. p : float, optional Pitch. r : float, optional Roll. reference : ReferenceContext, optional Absolute or relative. Methods ------- is_filled() Checks if any orientations are set. parse(element) Parses an 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: Optional[float] = None, p: Optional[float] = None, r: Optional[float] = None, reference: Optional[ReferenceContext] = None, ) -> None: """Initializes the Orientation. Parameters ---------- h : float, optional Header. Default is None. p : float, optional Pitch. Default is None. r : float, optional Roll. Default is None. reference : ReferenceContext, optional Absolute or relative. Default is None. """ 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: object) -> bool: if isinstance(other, Orientation): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "Orientation": """Parses the XML element of Orientation. Parameters ---------- element : ET.Element An Orientation element (same as generated by the class itself). Returns ------- Orientation An 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) -> bool: """Checks if any orientations are set. Returns ------- bool True if any orientations are set, False otherwise. """ return ( self.h is not None or self.p is not None or self.r is not None or self.ref is not None ) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Orientation as a dictionary. Returns ------- dict A dictionary of all attributes of the Orientation. """ 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) -> ET.Element: """Returns the ElementTree of the Orientation. Returns ------- ET.Element The ElementTree representation of the Orientation. """ return ET.Element("Orientation", attrib=self.get_attributes())Orientation describes the angular orientation of an entity.
Parameters
h:float, optional- Header. Default is None.
p:float, optional- Pitch. Default is None.
r:float, optional- Roll. Default is None.
reference:ReferenceContext, optional- Absolute or relative. Default is None.
Attributes
h:float, optional- Header.
p:float, optional- Pitch.
r:float, optional- Roll.
reference:ReferenceContext, optional- Absolute or relative.
Methods
is_filled() Checks if any orientations are set. parse(element) Parses an 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.
Initializes the Orientation.
Parameters
h:float, optional- Header. Default is None.
p:float, optional- Pitch. Default is None.
r:float, optional- Roll. Default is None.
reference:ReferenceContext, optional- Absolute or relative. Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Orientation-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Orientation": """Parses the XML element of Orientation. Parameters ---------- element : ET.Element An Orientation element (same as generated by the class itself). Returns ------- Orientation An 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)Parses the XML element of Orientation.
Parameters
element:ET.Element- An Orientation element (same as generated by the class itself).
Returns
Orientation- An Orientation object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Orientation as a dictionary. Returns ------- dict A dictionary of all attributes of the Orientation. """ 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 retdictReturns the attributes of the Orientation as a dictionary.
Returns
dict- A dictionary of all attributes of the Orientation.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Orientation. Returns ------- ET.Element The ElementTree representation of the Orientation. """ return ET.Element("Orientation", attrib=self.get_attributes())Returns the ElementTree of the Orientation.
Returns
ET.Element- The ElementTree representation of the Orientation.
def is_filled(self) ‑> bool-
Expand source code
def is_filled(self) -> bool: """Checks if any orientations are set. Returns ------- bool True if any orientations are set, False otherwise. """ return ( self.h is not None or self.p is not None or self.r is not None or self.ref is not None )Checks if any orientations are set.
Returns
bool- True if any orientations are set, False otherwise.
class Parameter (name: str,
parameter_type: ParameterType,
value: str)-
Expand source code
class Parameter(VersionBase): """Parameter is a declaration of a ParameterDeclaration for declarations. Parameters ---------- name : str Name of the parameter. parameter_type : ParameterType Type of the parameter. value : str Value of the parameter. Attributes ---------- name : str Name of the parameter. parameter_type : ParameterType Type of the parameter. value : str Value of the parameter. constraint_group : ValueConstraintGroup Constraint groups to the parameter value. Methods ------- parse(element) Parses an 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: str, parameter_type: ParameterType, value: str ) -> None: """Initializes the Parameter. Parameters ---------- name : str Name of the 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: object) -> bool: 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: ET.Element) -> "Parameter": """Parses the XML element of Parameter. Parameters ---------- element : ET.Element A Parameter element (same as generated by the class itself). Returns ------- Parameter A 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: ValueConstraintGroup ) -> "Parameter": """Adds a value constraint to the value constraint group. Parameters ---------- constraint_group : ValueConstraintGroup The value constraint group to be added. Returns ------- Parameter The updated Parameter object. """ 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) -> dict[str, str]: """Returns the attributes of the Parameter as a dictionary. Returns ------- dict A dictionary of all attributes of the Parameter. """ return { "name": self.name, "parameterType": self.parameter_type.get_name(), "value": str(self.value), } def get_element(self) -> ET.Element: """Returns the ElementTree of the Parameter. Returns ------- ET.Element The ElementTree representation 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 elementParameter is a declaration of a ParameterDeclaration for declarations.
Parameters
name:str- Name of the parameter.
parameter_type:ParameterType- Type of the parameter.
value:str- Value of the parameter.
Attributes
name:str- Name of the parameter.
parameter_type:ParameterType- Type of the parameter.
value:str- Value of the parameter.
constraint_group:ValueConstraintGroup- Constraint groups to the parameter value.
Methods
parse(element) Parses an 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.
Initializes the Parameter.
Parameters
name:str- Name of the parameter.
parameter_type:ParameterType- Type of the parameter.
value:str- Value of the parameter.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Parameter-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Parameter": """Parses the XML element of Parameter. Parameters ---------- element : ET.Element A Parameter element (same as generated by the class itself). Returns ------- Parameter A 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 parameterParses the XML element of Parameter.
Parameters
element:ET.Element- A Parameter element (same as generated by the class itself).
Returns
Parameter- A Parameter object.
Methods
def add_value_constraint_group(self,
constraint_group: ValueConstraintGroup) ‑> Parameter-
Expand source code
def add_value_constraint_group( self, constraint_group: ValueConstraintGroup ) -> "Parameter": """Adds a value constraint to the value constraint group. Parameters ---------- constraint_group : ValueConstraintGroup The value constraint group to be added. Returns ------- Parameter The updated Parameter object. """ if not isinstance(constraint_group, ValueConstraintGroup): raise TypeError( "value_conatraint input is not of type ValueConstraintGroup" ) self.constraint_groups.append(constraint_group) return selfAdds a value constraint to the value constraint group.
Parameters
constraint_group:ValueConstraintGroup- The value constraint group to be added.
Returns
Parameter- The updated Parameter object.
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Parameter as a dictionary. Returns ------- dict A dictionary of all attributes of the Parameter. """ return { "name": self.name, "parameterType": self.parameter_type.get_name(), "value": str(self.value), }Returns the attributes of the Parameter as a dictionary.
Returns
dict- A dictionary of all attributes of the Parameter.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Parameter. Returns ------- ET.Element The ElementTree representation 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 elementReturns the ElementTree of the Parameter.
Returns
ET.Element- The ElementTree representation of the Parameter.
class ParameterAssignment (parameterref: str, value: str)-
Expand source code
class ParameterAssignment(VersionBase): """ParameterAssignment creates a 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 an 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: str, value: str) -> None: """Initializes 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: object) -> bool: if isinstance(other, ParameterAssignment): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "ParameterAssignment": """Parses the XML element of ParameterAssignment. Parameters ---------- element : ET.Element A ParameterAssignment element (same as generated by the class itself). Returns ------- ParameterAssignment A ParameterAssignment object. """ value = element.attrib["value"] parameterref = element.attrib["parameterRef"] return ParameterAssignment(parameterref, value) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the ParameterAssignment as a dictionary. Returns ------- dict A dictionary of all attributes of the ParameterAssignment. """ retdict = {} retdict["parameterRef"] = self.parameterref retdict["value"] = str(self.value) return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the ParameterAssignment. Returns ------- ET.Element The ElementTree representation of the ParameterAssignment. """ return ET.Element("ParameterAssignment", attrib=self.get_attributes())ParameterAssignment creates a 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 an 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.
Initializes the ParameterAssignment.
Parameters
parameterref:str- Name of the parameter.
value:str- Assigned value of the parameter.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> ParameterAssignment-
Expand source code
@staticmethod def parse(element: ET.Element) -> "ParameterAssignment": """Parses the XML element of ParameterAssignment. Parameters ---------- element : ET.Element A ParameterAssignment element (same as generated by the class itself). Returns ------- ParameterAssignment A ParameterAssignment object. """ value = element.attrib["value"] parameterref = element.attrib["parameterRef"] return ParameterAssignment(parameterref, value)Parses the XML element of ParameterAssignment.
Parameters
element:ET.Element- A ParameterAssignment element (same as generated by the class itself).
Returns
ParameterAssignment- A ParameterAssignment object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the ParameterAssignment as a dictionary. Returns ------- dict A dictionary of all attributes of the ParameterAssignment. """ retdict = {} retdict["parameterRef"] = self.parameterref retdict["value"] = str(self.value) return retdictReturns the attributes of the ParameterAssignment as a dictionary.
Returns
dict- A dictionary of all attributes of the ParameterAssignment.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the ParameterAssignment. Returns ------- ET.Element The ElementTree representation of the ParameterAssignment. """ return ET.Element("ParameterAssignment", attrib=self.get_attributes())Returns the ElementTree of the ParameterAssignment.
Returns
ET.Element- The ElementTree representation of the ParameterAssignment.
class ParameterDeclarations-
Expand source code
class ParameterDeclarations(VersionBase): """The ParameterDeclarations class creates the ParameterDeclaration of OpenScenario. Attributes ---------- parameters : list of Parameter 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 an ElementTree created by the class and returns an instance of the class. """ def __init__(self) -> None: """Initializes the ParameterDeclarations.""" self.parameters = [] @staticmethod def parse(element: ET.Element) -> "ParameterDeclarations": """Parses the XML element of ParameterDeclarations. Parameters ---------- element : ET.Element A ParameterDeclarations element (same as generated by the class itself). Returns ------- ParameterDeclarations A ParameterDeclarations 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: object) -> bool: if isinstance(other, ParameterDeclarations): if self.parameters == other.parameters: return True return False def add_parameter(self, parameter: Parameter) -> "ParameterDeclarations": """Adds a Parameter to the ParameterDeclarations. Parameters ---------- parameter : Parameter A new parameter. Returns ------- ParameterDeclarations The updated ParameterDeclarations object. """ if not isinstance(parameter, Parameter): raise TypeError("parameter input is not of type Parameter") self.parameters.append(parameter) return self def get_element(self) -> Optional[ET.Element]: """Returns the ElementTree of the ParameterDeclarations. Returns ------- ET.Element or None The ElementTree representation of the ParameterDeclarations, or None if no parameters exist. """ if self.parameters: element = ET.Element("ParameterDeclarations") for p in self.parameters: element.append(p.get_element()) return element return NoneThe ParameterDeclarations class creates the ParameterDeclaration of OpenScenario.
Attributes
parameters:listofParameter- 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 an ElementTree created by the class and returns an instance of the class.
Initializes the ParameterDeclarations.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> ParameterDeclarations-
Expand source code
@staticmethod def parse(element: ET.Element) -> "ParameterDeclarations": """Parses the XML element of ParameterDeclarations. Parameters ---------- element : ET.Element A ParameterDeclarations element (same as generated by the class itself). Returns ------- ParameterDeclarations A ParameterDeclarations 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_declarationsParses the XML element of ParameterDeclarations.
Parameters
element:ET.Element- A ParameterDeclarations element (same as generated by the class itself).
Returns
ParameterDeclarations- A ParameterDeclarations object.
Methods
def add_parameter(self,
parameter: Parameter) ‑> ParameterDeclarations-
Expand source code
def add_parameter(self, parameter: Parameter) -> "ParameterDeclarations": """Adds a Parameter to the ParameterDeclarations. Parameters ---------- parameter : Parameter A new parameter. Returns ------- ParameterDeclarations The updated ParameterDeclarations object. """ if not isinstance(parameter, Parameter): raise TypeError("parameter input is not of type Parameter") self.parameters.append(parameter) return selfAdds a Parameter to the ParameterDeclarations.
Parameters
parameter:Parameter- A new parameter.
Returns
ParameterDeclarations- The updated ParameterDeclarations object.
def get_element(self) ‑> xml.etree.ElementTree.Element | None-
Expand source code
def get_element(self) -> Optional[ET.Element]: """Returns the ElementTree of the ParameterDeclarations. Returns ------- ET.Element or None The ElementTree representation of the ParameterDeclarations, or None if no parameters exist. """ if self.parameters: element = ET.Element("ParameterDeclarations") for p in self.parameters: element.append(p.get_element()) return element return NoneReturns the ElementTree of the ParameterDeclarations.
Returns
ET.ElementorNone- The ElementTree representation of the ParameterDeclarations, or None if no parameters exist.
class PedestrianAnimation (motion: PedestrianMotionType | None = None,
animation: str | None = None)-
Expand source code
class PedestrianAnimation(_AnimationType): """PedestrianAnimation creates a PedestrianAnimation element of OpenSCENARIO (valid from OpenSCENARIO V1.2). Parameters ---------- motion : PedestrianMotionType, optional Motion of a pedestrian. Default is None. userDefinedPedestrianAnimation : str, optional User-defined pedestrian animation. Default is None. Attributes ---------- motion : PedestrianMotionType, optional Motion of a pedestrian. userDefinedPedestrianAnimation : str, optional User-defined pedestrian animation. gestures : list of PedestrianGestureType Gestures of a pedestrian. Methods ------- parse(element) Parses an 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() Returns the full ElementTree of the class. get_attributes() Returns a dictionary of all attributes of the class. """ def __init__( self, motion: Optional[PedestrianMotionType] = None, animation: Optional[str] = None, ) -> None: """Initializes the PedestrianAnimation. Parameters ---------- motion : PedestrianMotionType, optional Motion of a pedestrian. Default is None. userDefinedPedestrianAnimation : str, optional User-defined pedestrian animation. Default is None. """ self.motion = convert_enum(motion, PedestrianMotionType, True) self.animation = animation self.gestures = [] def __eq__(self, other: object) -> bool: if isinstance(other, PedestrianAnimation): if ( other.get_attributes() == self.get_attributes() and other.gestures == self.gestures ): return True return False @staticmethod def parse(element: ET.Element) -> "PedestrianAnimation": """Parses the XML element of PedestrianAnimation. Parameters ---------- element : ET.Element A PedestrianAnimation element (same as generated by the class itself). Returns ------- 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: PedestrianGestureType ) -> "PedestrianAnimation": """Adds a pedestrian gesture to the pedestrian animation. Parameters ---------- gesture : PedestrianGestureType A new gesture of the pedestrian. Returns ------- PedestrianAnimation The updated PedestrianAnimation object. """ self.gestures.append(convert_enum(gesture, PedestrianGestureType)) return self def get_attributes(self) -> dict[str, str]: """Returns the attributes of the PedestrianAnimation as a dictionary. Returns ------- dict A dictionary of all attributes of the PedestrianAnimation. """ retdict = {} retdict["motion"] = self.motion.get_name() retdict["userDefinedPedestrianAnimation"] = str(self.animation) return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the PedestrianAnimation. Returns ------- ET.Element The ElementTree representation of the PedestrianAnimation. """ if not self.isVersionEqLarger(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 elementPedestrianAnimation creates a PedestrianAnimation element of OpenSCENARIO (valid from OpenSCENARIO V1.2).
Parameters
motion:PedestrianMotionType, optional- Motion of a pedestrian. Default is None.
userDefinedPedestrianAnimation:str, optional- User-defined pedestrian animation. Default is None.
Attributes
motion:PedestrianMotionType, optional- Motion of a pedestrian.
userDefinedPedestrianAnimation:str, optional- User-defined pedestrian animation.
gestures:listofPedestrianGestureType- Gestures of a pedestrian.
Methods
parse(element) Parses an 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() Returns the full ElementTree of the class. get_attributes() Returns a dictionary of all attributes of the class.
Initializes the PedestrianAnimation.
Parameters
motion:PedestrianMotionType, optional- Motion of a pedestrian. Default is None.
userDefinedPedestrianAnimation:str, optional- User-defined pedestrian animation. Default is None.
Ancestors
- scenariogeneration.xosc.utils._AnimationType
- VersionBase
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> PedestrianAnimation-
Expand source code
@staticmethod def parse(element: ET.Element) -> "PedestrianAnimation": """Parses the XML element of PedestrianAnimation. Parameters ---------- element : ET.Element A PedestrianAnimation element (same as generated by the class itself). Returns ------- 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 paParses the XML element of PedestrianAnimation.
Parameters
element:ET.Element- A PedestrianAnimation element (same as generated by the class itself).
Returns
PedestrianAnimation- A PedestrianAnimation object.
Methods
def add_gesture(self,
gesture: PedestrianGestureType) ‑> PedestrianAnimation-
Expand source code
def add_gesture( self, gesture: PedestrianGestureType ) -> "PedestrianAnimation": """Adds a pedestrian gesture to the pedestrian animation. Parameters ---------- gesture : PedestrianGestureType A new gesture of the pedestrian. Returns ------- PedestrianAnimation The updated PedestrianAnimation object. """ self.gestures.append(convert_enum(gesture, PedestrianGestureType)) return selfAdds a pedestrian gesture to the pedestrian animation.
Parameters
gesture:PedestrianGestureType- A new gesture of the pedestrian.
Returns
PedestrianAnimation- The updated PedestrianAnimation object.
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the PedestrianAnimation as a dictionary. Returns ------- dict A dictionary of all attributes of the PedestrianAnimation. """ retdict = {} retdict["motion"] = self.motion.get_name() retdict["userDefinedPedestrianAnimation"] = str(self.animation) return retdictReturns the attributes of the PedestrianAnimation as a dictionary.
Returns
dict- A dictionary of all attributes of the PedestrianAnimation.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the PedestrianAnimation. Returns ------- ET.Element The ElementTree representation of the PedestrianAnimation. """ if not self.isVersionEqLarger(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 elementReturns the ElementTree of the PedestrianAnimation.
Returns
ET.Element- The ElementTree representation of the PedestrianAnimation.
class Phase (name: str, duration: float, traffic_group_state: str | None = None)-
Expand source code
class Phase(VersionBase): """Creates a Traffic light phase. Parameters ---------- name : str ID of the phase. duration : float Duration of the phase. traffic_group_state : str, optional State for a group of signals (valid since V1.2). Default is None. Attributes ---------- name : str ID of the phase. duration : float Duration of the phase. signalstates : list of _TrafficSignalState Traffic signal states. traffic_group_state : str, optional State for a group of signals. Methods ------- parse(element) Parses an 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_signal_state(signal_id, state) Adds a traffic signal state. """ def __init__( self, name: str, duration: float, traffic_group_state: Optional[str] = None, ) -> None: """Initializes the Phase. Parameters ---------- name : str ID of the phase. duration : float Duration of the phase. traffic_group_state : str, optional State for a group of signals (valid since V1.2). Default is None. """ self.name = name self.duration = convert_float(duration) self.signalstates = [] self.traffic_group_state = traffic_group_state def __eq__(self, other: object) -> bool: if isinstance(other, Phase): if ( self.get_attributes() == other.get_attributes() and self.signalstates == other.signalstates ): return True return False @staticmethod def parse(element: ET.Element) -> "Phase": """Parses the XML element of Phase. Parameters ---------- element : ET.Element A Phase element (same as generated by the class itself). Returns ------- 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 = find_mandatory_field( element, "TrafficeSignalGroupState" ).attrib["state"] phase = Phase(name, duration, group) signalstates = element.findall("TrafficSignalState") if signalstates is not 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: str, state: str) -> "Phase": """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. Returns ------- Phase The updated Phase object. """ self.signalstates.append(_TrafficSignalState(signal_id, state)) return self def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Phase as a dictionary. Returns ------- dict A dictionary of all attributes of the Phase. """ retdict = {} retdict["name"] = self.name retdict["duration"] = str(self.duration) return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the Phase. Returns ------- ET.Element The ElementTree representation of the Phase. """ 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 elementCreates a Traffic light phase.
Parameters
name:str- ID of the phase.
duration:float- Duration of the phase.
traffic_group_state:str, optional- State for a group of signals (valid since V1.2). Default is None.
Attributes
name:str- ID of the phase.
duration:float- Duration of the phase.
signalstates:listof_TrafficSignalState- Traffic signal states.
traffic_group_state:str, optional- State for a group of signals.
Methods
parse(element) Parses an 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_signal_state(signal_id, state) Adds a traffic signal state.
Initializes the Phase.
Parameters
name:str- ID of the phase.
duration:float- Duration of the phase.
traffic_group_state:str, optional- State for a group of signals (valid since V1.2). Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Phase-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Phase": """Parses the XML element of Phase. Parameters ---------- element : ET.Element A Phase element (same as generated by the class itself). Returns ------- 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 = find_mandatory_field( element, "TrafficeSignalGroupState" ).attrib["state"] phase = Phase(name, duration, group) signalstates = element.findall("TrafficSignalState") if signalstates is not None: for signalstate in signalstates: traffic_signal_state = _TrafficSignalState.parse(signalstate) phase.signalstates.append(traffic_signal_state) return phaseParses the XML element of Phase.
Parameters
element:ET.Element- A Phase element (same as generated by the class itself).
Returns
Phase- A Phase object.
Methods
def add_signal_state(self, signal_id: str, state: str) ‑> Phase-
Expand source code
def add_signal_state(self, signal_id: str, state: str) -> "Phase": """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. Returns ------- Phase The updated Phase object. """ self.signalstates.append(_TrafficSignalState(signal_id, state)) return selfAdds 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.
Returns
Phase- The updated Phase object.
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Phase as a dictionary. Returns ------- dict A dictionary of all attributes of the Phase. """ retdict = {} retdict["name"] = self.name retdict["duration"] = str(self.duration) return retdictReturns the attributes of the Phase as a dictionary.
Returns
dict- A dictionary of all attributes of the Phase.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Phase. Returns ------- ET.Element The ElementTree representation of the Phase. """ 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 elementReturns the ElementTree of the Phase.
Returns
ET.Element- The ElementTree representation of the Phase.
class Precipitation (precipitation: PrecipitationType,
intensity: float)-
Expand source code
class Precipitation(VersionBase): """Precipitation creates a 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 an 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: PrecipitationType, intensity: float ) -> None: """Initializes 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: object) -> bool: if isinstance(other, Precipitation): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "Precipitation": """Parses the XML element of Precipitation. Parameters ---------- element : ET.Element A Precipitation element (same as generated by the class itself). Returns ------- 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) -> dict[str, str]: """Returns the attributes of the Precipitation as a dictionary. Returns ------- dict A dictionary of all attributes of the Precipitation. """ 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) -> ET.Element: """Returns the ElementTree of the Precipitation. Returns ------- ET.Element The ElementTree representation of the Precipitation. """ element = ET.Element("Precipitation", attrib=self.get_attributes()) return elementPrecipitation creates a 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 an 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.
Initializes the Precipitation.
Parameters
precipitation:PrecipitationType- Dry, rain or snow.
intensity:float- Intensity of precipitation (0…1).
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Precipitation-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Precipitation": """Parses the XML element of Precipitation. Parameters ---------- element : ET.Element A Precipitation element (same as generated by the class itself). Returns ------- 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)Parses the XML element of Precipitation.
Parameters
element:ET.Element- A Precipitation element (same as generated by the class itself).
Returns
Precipitation- A Precipitation object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Precipitation as a dictionary. Returns ------- dict A dictionary of all attributes of the Precipitation. """ retdict = {} retdict["precipitationType"] = self.precipitation.get_name() if self.isVersion(minor=0): retdict["intensity"] = str(self.intensity) else: retdict["precipitationIntensity"] = str(self.intensity) return retdictReturns the attributes of the Precipitation as a dictionary.
Returns
dict- A dictionary of all attributes of the Precipitation.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Precipitation. Returns ------- ET.Element The ElementTree representation of the Precipitation. """ element = ET.Element("Precipitation", attrib=self.get_attributes()) return elementReturns the ElementTree of the Precipitation.
Returns
ET.Element- The ElementTree representation of the Precipitation.
class Properties-
Expand source code
class Properties(VersionBase): """The Properties class contains 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 an 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) -> None: """Initializes the Properties.""" self.files = [] self.properties = [] def __eq__(self, other: object) -> bool: if isinstance(other, Properties): if ( self.files == other.files and self.properties == other.properties ): return True return False @staticmethod def parse(element: ET.Element) -> "Properties": """Parses the XML element of Properties. Parameters ---------- element : ET.Element A Properties element (same as generated by the class itself). Returns ------- Properties A Properties object. """ properties = Properties() files = element.findall("File") if files is not None: for file in files: filepath = file.attrib["filepath"] properties.add_file(filepath) props = element.findall("Property") if props is not 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: str) -> "Properties": """Adds a property file. Parameters ---------- filename : str Name of the file. Returns ------- Properties The updated Properties object. """ self.files.append(filename) return self def add_property(self, name: str, value: str) -> "Properties": """Adds a property pair. Parameters ---------- name : str Name of the property. value : str Value of the property. Returns ------- Properties The updated Properties object. """ self.properties.append((name, value)) return self def get_element(self) -> ET.Element: """Returns the ElementTree of the Properties. Returns ------- ET.Element The ElementTree representation of the Properties. """ element = ET.Element("Properties") if ( len(self.files) == 0 and len(self.properties) == 0 and self.isVersionEqLarger(minor=3) ): return None 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 elementThe Properties class contains user-defined properties of an object.
Attributes
files:listofstr- Arbitrary files with properties.
properties:listoftuple(str, str)- Properties in name/value pairs.
Methods
parse(element) Parses an 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.
Initializes the Properties.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Properties-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Properties": """Parses the XML element of Properties. Parameters ---------- element : ET.Element A Properties element (same as generated by the class itself). Returns ------- Properties A Properties object. """ properties = Properties() files = element.findall("File") if files is not None: for file in files: filepath = file.attrib["filepath"] properties.add_file(filepath) props = element.findall("Property") if props is not None: for property in props: name = property.attrib["name"] value = property.attrib["value"] properties.add_property(name, value) return propertiesParses the XML element of Properties.
Parameters
element:ET.Element- A Properties element (same as generated by the class itself).
Returns
Properties- A Properties object.
Methods
def add_file(self, filename: str) ‑> Properties-
Expand source code
def add_file(self, filename: str) -> "Properties": """Adds a property file. Parameters ---------- filename : str Name of the file. Returns ------- Properties The updated Properties object. """ self.files.append(filename) return selfAdds a property file.
Parameters
filename:str- Name of the file.
Returns
Properties- The updated Properties object.
def add_property(self, name: str, value: str) ‑> Properties-
Expand source code
def add_property(self, name: str, value: str) -> "Properties": """Adds a property pair. Parameters ---------- name : str Name of the property. value : str Value of the property. Returns ------- Properties The updated Properties object. """ self.properties.append((name, value)) return selfAdds a property pair.
Parameters
name:str- Name of the property.
value:str- Value of the property.
Returns
Properties- The updated Properties object.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Properties. Returns ------- ET.Element The ElementTree representation of the Properties. """ element = ET.Element("Properties") if ( len(self.files) == 0 and len(self.properties) == 0 and self.isVersionEqLarger(minor=3) ): return None 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 elementReturns the ElementTree of the Properties.
Returns
ET.Element- The ElementTree representation of the Properties.
class RelativeSpeedToMaster (value: float,
speedTargetValueType: SpeedTargetValueType,
steadyState: TargetTimeSteadyState | TargetDistanceSteadyState | None = None)-
Expand source code
class RelativeSpeedToMaster(VersionBase): """RelativeSpeedToMaster creates a RelativeSpeedToMaster element of OpenScenario. Parameters ---------- value : float Relative speed. Unit: m/s. speedTargetValueType : SpeedTargetValueType The semantics of the value (delta, offset, factor). steadyState : Union[TargetTimeSteadyState, TargetDistanceSteadyState], optional Optional final phase of constant (final) speed (valid from OpenSCENARIO V1.1). Default is None. Attributes ---------- value : float Relative speed. Unit: m/s. speedTargetValueType : SpeedTargetValueType The semantics of the value (delta, offset, factor). steadyState : Union[TargetTimeSteadyState, TargetDistanceSteadyState], optional Optional final phase of constant (final) speed. Methods ------- parse(element) Parses an 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, value: float, speedTargetValueType: SpeedTargetValueType, steadyState: Optional[ Union[TargetTimeSteadyState, TargetDistanceSteadyState] ] = None, ) -> None: """Initializes the RelativeSpeedToMaster. Parameters ---------- value : float Relative speed. Unit: m/s. speedTargetValueType : SpeedTargetValueType The semantics of the value (delta, offset, factor). steadyState : Union[TargetTimeSteadyState, TargetDistanceSteadyState], optional Optional final phase of constant (final) speed (valid from OpenSCENARIO V1.1). Default is None. """ self.value = value if steadyState: if not isinstance( steadyState, (TargetTimeSteadyState, 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: object) -> bool: if isinstance(other, RelativeSpeedToMaster): if ( self.get_attributes() == other.get_attributes() and self.steadyState == other.steadyState ): return True return False @staticmethod def parse(element: ET.Element) -> "RelativeSpeedToMaster": """Parses the XML element of RelativeSpeedToMaster. Parameters ---------- element : ET.Element A RelativeSpeedToMaster element (same as generated by the class itself). Returns ------- RelativeSpeedToMaster A RelativeSpeedToMaster object. """ speed_element = find_mandatory_field(element, "RelativeSpeedToMaster") value = speed_element.attrib["value"] speedTargetValueType = convert_enum( speed_element.attrib["speedTargetValueType"], SpeedTargetValueType ) state = None if speed_element.find("TargetDistanceSteadyState") is not None: state = TargetDistanceSteadyState.parse( find_mandatory_field( speed_element, "TargetDistanceSteadyState" ) ) elif speed_element.find("TargetTimeSteadyState") is not None: state = TargetTimeSteadyState.parse( find_mandatory_field(speed_element, "TargetTimeSteadyState") ) return RelativeSpeedToMaster(value, speedTargetValueType, state) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the RelativeSpeedToMaster as a dictionary. Returns ------- dict A dictionary of all attributes of the RelativeSpeedToMaster. """ return { "speedTargetValueType": str(self.speedTargetValueType), "value": str(self.value), } def get_element(self) -> ET.Element: """Returns the ElementTree of the RelativeSpeedToMaster. Returns ------- ET.Element The ElementTree representation 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 elementFinalSpeedRelativeSpeedToMaster creates a RelativeSpeedToMaster element of OpenScenario.
Parameters
value:float- Relative speed. Unit: m/s.
speedTargetValueType:SpeedTargetValueType- The semantics of the value (delta, offset, factor).
steadyState:Union[TargetTimeSteadyState, TargetDistanceSteadyState], optional- Optional final phase of constant (final) speed (valid from OpenSCENARIO V1.1). Default is None.
Attributes
value:float- Relative speed. Unit: m/s.
speedTargetValueType:SpeedTargetValueType- The semantics of the value (delta, offset, factor).
steadyState:Union[TargetTimeSteadyState, TargetDistanceSteadyState], optional- Optional final phase of constant (final) speed.
Methods
parse(element) Parses an 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.
Initializes the RelativeSpeedToMaster.
Parameters
value:float- Relative speed. Unit: m/s.
speedTargetValueType:SpeedTargetValueType- The semantics of the value (delta, offset, factor).
steadyState:Union[TargetTimeSteadyState, TargetDistanceSteadyState], optional- Optional final phase of constant (final) speed (valid from OpenSCENARIO V1.1). Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> RelativeSpeedToMaster-
Expand source code
@staticmethod def parse(element: ET.Element) -> "RelativeSpeedToMaster": """Parses the XML element of RelativeSpeedToMaster. Parameters ---------- element : ET.Element A RelativeSpeedToMaster element (same as generated by the class itself). Returns ------- RelativeSpeedToMaster A RelativeSpeedToMaster object. """ speed_element = find_mandatory_field(element, "RelativeSpeedToMaster") value = speed_element.attrib["value"] speedTargetValueType = convert_enum( speed_element.attrib["speedTargetValueType"], SpeedTargetValueType ) state = None if speed_element.find("TargetDistanceSteadyState") is not None: state = TargetDistanceSteadyState.parse( find_mandatory_field( speed_element, "TargetDistanceSteadyState" ) ) elif speed_element.find("TargetTimeSteadyState") is not None: state = TargetTimeSteadyState.parse( find_mandatory_field(speed_element, "TargetTimeSteadyState") ) return RelativeSpeedToMaster(value, speedTargetValueType, state)Parses the XML element of RelativeSpeedToMaster.
Parameters
element:ET.Element- A RelativeSpeedToMaster element (same as generated by the class itself).
Returns
RelativeSpeedToMaster- A RelativeSpeedToMaster object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the RelativeSpeedToMaster as a dictionary. Returns ------- dict A dictionary of all attributes of the RelativeSpeedToMaster. """ return { "speedTargetValueType": str(self.speedTargetValueType), "value": str(self.value), }Returns the attributes of the RelativeSpeedToMaster as a dictionary.
Returns
dict- A dictionary of all attributes of the RelativeSpeedToMaster.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the RelativeSpeedToMaster. Returns ------- ET.Element The ElementTree representation 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 elementFinalSpeedReturns the ElementTree of the RelativeSpeedToMaster.
Returns
ET.Element- The ElementTree representation of the RelativeSpeedToMaster.
class RoadCondition (friction_scale_factor: float,
properties: Properties | None = None,
wetness: Wetness | None = None)-
Expand source code
class RoadCondition(VersionBase): """RoadCondition creates a RoadCondition element of OpenScenario. Parameters ---------- friction_scale_factor : float Scale factor of the friction. properties : Properties, optional Properties of the road condition. Default is None. wetness : Wetness, optional Wetness of the road. Default is None. Attributes ---------- friction_scale_factor : float Scale factor of the friction. properties : Properties, optional Properties of the road condition. wetness : Wetness, optional Wetness of the road. Methods ------- parse(element) Parses an 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: float, properties: Optional[Properties] = None, wetness: Optional[Wetness] = None, ) -> None: """Initializes the RoadCondition. Parameters ---------- friction_scale_factor : float Scale factor of the friction. properties : Properties, optional Properties of the road condition. Default is None. wetness : Wetness, optional Wetness of the road. Default is 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: object) -> bool: if isinstance(other, RoadCondition): if ( self.get_attributes() == other.get_attributes() and self.properties == other.properties ): return True return False @staticmethod def parse(element: ET.Element) -> "RoadCondition": """Parses the XML element of RoadCondition. Parameters ---------- element : ET.Element A RoadCondition element (same as generated by the class itself). Returns ------- RoadCondition A RoadCondition object. """ friction_scale_factor = element.attrib["frictionScaleFactor"] properties = None wetness = None if element.find("Properties") is not None: properties = Properties.parse( find_mandatory_field(element, "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) -> dict[str, str]: """Returns the attributes of the RoadCondition as a dictionary. Returns ------- dict A dictionary of all attributes of the RoadCondition. """ retdict = {"frictionScaleFactor": str(self.friction_scale_factor)} if self.wetness: retdict["wetness"] = self.wetness.get_name() return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the RoadCondition. Returns ------- ET.Element The ElementTree representation of the RoadCondition. """ element = ET.Element("RoadCondition", attrib=self.get_attributes()) if self.properties: element.append(self.properties.get_element()) return elementRoadCondition creates a RoadCondition element of OpenScenario.
Parameters
friction_scale_factor:float- Scale factor of the friction.
properties:Properties, optional- Properties of the road condition. Default is None.
wetness:Wetness, optional- Wetness of the road. Default is None.
Attributes
friction_scale_factor:float- Scale factor of the friction.
properties:Properties, optional- Properties of the road condition.
wetness:Wetness, optional- Wetness of the road.
Methods
parse(element) Parses an 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.
Initializes the RoadCondition.
Parameters
friction_scale_factor:float- Scale factor of the friction.
properties:Properties, optional- Properties of the road condition. Default is None.
wetness:Wetness, optional- Wetness of the road. Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> RoadCondition-
Expand source code
@staticmethod def parse(element: ET.Element) -> "RoadCondition": """Parses the XML element of RoadCondition. Parameters ---------- element : ET.Element A RoadCondition element (same as generated by the class itself). Returns ------- RoadCondition A RoadCondition object. """ friction_scale_factor = element.attrib["frictionScaleFactor"] properties = None wetness = None if element.find("Properties") is not None: properties = Properties.parse( find_mandatory_field(element, "Properties") ) if "wetness" in element.attrib: wetness = convert_enum(element.attrib["wetness"], Wetness, False) return RoadCondition(friction_scale_factor, properties, wetness)Parses the XML element of RoadCondition.
Parameters
element:ET.Element- A RoadCondition element (same as generated by the class itself).
Returns
RoadCondition- A RoadCondition object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the RoadCondition as a dictionary. Returns ------- dict A dictionary of all attributes of the RoadCondition. """ retdict = {"frictionScaleFactor": str(self.friction_scale_factor)} if self.wetness: retdict["wetness"] = self.wetness.get_name() return retdictReturns the attributes of the RoadCondition as a dictionary.
Returns
dict- A dictionary of all attributes of the RoadCondition.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the RoadCondition. Returns ------- ET.Element The ElementTree representation of the RoadCondition. """ element = ET.Element("RoadCondition", attrib=self.get_attributes()) if self.properties: element.append(self.properties.get_element()) return elementReturns the ElementTree of the RoadCondition.
Returns
ET.Element- The ElementTree representation of the RoadCondition.
class Sun (intensity: float, azimuth: float, elevation: float)-
Expand source code
class Sun(VersionBase): """Sun creates a 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 an 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: float, azimuth: float, elevation: float ) -> None: """Initializes 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: object) -> bool: if isinstance(other, Sun): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "Sun": """Parses the XML element of Sun. Parameters ---------- element : ET.Element A Sun element (same as generated by the class itself). Returns ------- 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) -> dict[str, str]: """Returns the attributes of the Sun as a dictionary. Returns ------- dict A dictionary of all attributes of the Sun. """ retdict = {} retdict["azimuth"] = str(self.azimuth) if self.isVersionEqLarger(minor=2): retdict["illuminance"] = str(self.intensity) else: retdict["intensity"] = str(self.intensity) retdict["elevation"] = str(self.elevation) return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the Sun. Returns ------- ET.Element The ElementTree representation of the Sun. """ element = ET.Element("Sun", attrib=self.get_attributes()) return elementSun creates a 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 an 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.
Initializes 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.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Sun-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Sun": """Parses the XML element of Sun. Parameters ---------- element : ET.Element A Sun element (same as generated by the class itself). Returns ------- 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)Parses the XML element of Sun.
Parameters
element:ET.Element- A Sun element (same as generated by the class itself).
Returns
Sun- A Sun object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Sun as a dictionary. Returns ------- dict A dictionary of all attributes of the Sun. """ retdict = {} retdict["azimuth"] = str(self.azimuth) if self.isVersionEqLarger(minor=2): retdict["illuminance"] = str(self.intensity) else: retdict["intensity"] = str(self.intensity) retdict["elevation"] = str(self.elevation) return retdictReturns the attributes of the Sun as a dictionary.
Returns
dict- A dictionary of all attributes of the Sun.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Sun. Returns ------- ET.Element The ElementTree representation of the Sun. """ element = ET.Element("Sun", attrib=self.get_attributes()) return elementReturns the ElementTree of the Sun.
Returns
ET.Element- The ElementTree representation of the Sun.
class TargetDistanceSteadyState (distance: float)-
Expand source code
class TargetDistanceSteadyState(VersionBase): """TargetDistanceSteadyState creates a TargetDistanceSteadyState element of OpenScenario (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 an 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, distance: float) -> None: """Initializes the TargetDistanceSteadyState. Parameters ---------- distance : float Distance to target for the steady state. """ self.distance = distance def __eq__(self, other: object) -> bool: if isinstance(other, TargetDistanceSteadyState): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "TargetDistanceSteadyState": """Parses the XML element of TargetDistanceSteadyState. Parameters ---------- element : ET.Element A TargetDistanceSteadyState element (same as generated by the class itself). Returns ------- TargetDistanceSteadyState A TargetDistanceSteadyState object. """ distance = element.attrib["distance"] return TargetDistanceSteadyState(distance) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the TargetDistanceSteadyState as a dictionary. Returns ------- dict A dictionary of all 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) -> ET.Element: """Returns the ElementTree of the TargetDistanceSteadyState. Returns ------- ET.Element The ElementTree representation 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() )TargetDistanceSteadyState creates a TargetDistanceSteadyState element of OpenScenario (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 an 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.
Initializes the TargetDistanceSteadyState.
Parameters
distance:float- Distance to target for the steady state.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> TargetDistanceSteadyState-
Expand source code
@staticmethod def parse(element: ET.Element) -> "TargetDistanceSteadyState": """Parses the XML element of TargetDistanceSteadyState. Parameters ---------- element : ET.Element A TargetDistanceSteadyState element (same as generated by the class itself). Returns ------- TargetDistanceSteadyState A TargetDistanceSteadyState object. """ distance = element.attrib["distance"] return TargetDistanceSteadyState(distance)Parses the XML element of TargetDistanceSteadyState.
Parameters
element:ET.Element- A TargetDistanceSteadyState element (same as generated by the class itself).
Returns
TargetDistanceSteadyState- A TargetDistanceSteadyState object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the TargetDistanceSteadyState as a dictionary. Returns ------- dict A dictionary of all attributes of the TargetDistanceSteadyState. """ if self.isVersion(1, 0): raise OpenSCENARIOVersionError( "TargetDistanceSteadyState was introduced in OpenSCENARIO V1.1" ) return {"distance": str(self.distance)}Returns the attributes of the TargetDistanceSteadyState as a dictionary.
Returns
dict- A dictionary of all attributes of the TargetDistanceSteadyState.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the TargetDistanceSteadyState. Returns ------- ET.Element The ElementTree representation 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() )Returns the ElementTree of the TargetDistanceSteadyState.
Returns
ET.Element- The ElementTree representation of the TargetDistanceSteadyState.
class TargetTimeSteadyState (time_gap: float)-
Expand source code
class TargetTimeSteadyState(VersionBase): """TargetTimeSteadyState creates a TargetTimeSteadyState element of OpenScenario (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 an 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, time_gap: float) -> None: """Initializes the TargetTimeSteadyState. Parameters ---------- time_gap : float Time gap to target for the steady state. """ self.time_gap = time_gap def __eq__(self, other: object) -> bool: if isinstance(other, TargetTimeSteadyState): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "TargetTimeSteadyState": """Parses the XML element of TargetTimeSteadyState. Parameters ---------- element : ET.Element A TargetTimeSteadyState element (same as generated by the class itself). Returns ------- TargetTimeSteadyState A TargetTimeSteadyState object. """ time = element.attrib["time"] return TargetTimeSteadyState(time) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the TargetTimeSteadyState as a dictionary. Returns ------- dict A dictionary of all 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) -> ET.Element: """Returns the ElementTree of the TargetTimeSteadyState. Returns ------- ET.Element The ElementTree representation 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() )TargetTimeSteadyState creates a TargetTimeSteadyState element of OpenScenario (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 an 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.
Initializes the TargetTimeSteadyState.
Parameters
time_gap:float- Time gap to target for the steady state.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> TargetTimeSteadyState-
Expand source code
@staticmethod def parse(element: ET.Element) -> "TargetTimeSteadyState": """Parses the XML element of TargetTimeSteadyState. Parameters ---------- element : ET.Element A TargetTimeSteadyState element (same as generated by the class itself). Returns ------- TargetTimeSteadyState A TargetTimeSteadyState object. """ time = element.attrib["time"] return TargetTimeSteadyState(time)Parses the XML element of TargetTimeSteadyState.
Parameters
element:ET.Element- A TargetTimeSteadyState element (same as generated by the class itself).
Returns
TargetTimeSteadyState- A TargetTimeSteadyState object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the TargetTimeSteadyState as a dictionary. Returns ------- dict A dictionary of all attributes of the TargetTimeSteadyState. """ if self.isVersion(1, 0): raise OpenSCENARIOVersionError( "TargetTimeSteadyState was introduced in OpenSCENARIO V1.1" ) return {"time": str(self.time_gap)}Returns the attributes of the TargetTimeSteadyState as a dictionary.
Returns
dict- A dictionary of all attributes of the TargetTimeSteadyState.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the TargetTimeSteadyState. Returns ------- ET.Element The ElementTree representation 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() )Returns the ElementTree of the TargetTimeSteadyState.
Returns
ET.Element- The ElementTree representation of the TargetTimeSteadyState.
class TimeOfDay (animation: bool, year: int, month: int, day: int, hour: int, minute: int, second: int)-
Expand source code
class TimeOfDay(VersionBase): """TimeOfDay creates a 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 an 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: bool, year: int, month: int, day: int, hour: int, minute: int, second: int, ) -> None: """Initializes 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: object) -> bool: if isinstance(other, TimeOfDay): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "TimeOfDay": """Parses the XML element of TimeOfDay. Parameters ---------- element : ET.Element A TimeOfDay element (same as generated by the class itself). Returns ------- 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) -> dict[str, str]: """Returns the attributes of the TimeOfDay as a dictionary. Returns ------- dict A dictionary of all attributes of the TimeOfDay. """ tod = ( 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": tod} def get_element(self) -> ET.Element: """Returns the ElementTree of the TimeOfDay. Returns ------- ET.Element The ElementTree representation of the TimeOfDay. """ return ET.Element("TimeOfDay", attrib=self.get_attributes())TimeOfDay creates a 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 an 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.
Initializes 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.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> TimeOfDay-
Expand source code
@staticmethod def parse(element: ET.Element) -> "TimeOfDay": """Parses the XML element of TimeOfDay. Parameters ---------- element : ET.Element A TimeOfDay element (same as generated by the class itself). Returns ------- 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)Parses the XML element of TimeOfDay.
Parameters
element:ET.Element- A TimeOfDay element (same as generated by the class itself).
Returns
TimeOfDay- A TimeOfDay object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the TimeOfDay as a dictionary. Returns ------- dict A dictionary of all attributes of the TimeOfDay. """ tod = ( 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": tod}Returns the attributes of the TimeOfDay as a dictionary.
Returns
dict- A dictionary of all attributes of the TimeOfDay.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the TimeOfDay. Returns ------- ET.Element The ElementTree representation of the TimeOfDay. """ return ET.Element("TimeOfDay", attrib=self.get_attributes())Returns the ElementTree of the TimeOfDay.
Returns
ET.Element- The ElementTree representation of the TimeOfDay.
class TimeReference (reference_domain: ReferenceContext | None = None,
scale: float | None = None,
offset: float | None = None)-
Expand source code
class TimeReference(VersionBase): """The TimeReference class creates a TimeReference. Parameters ---------- reference_domain : ReferenceContext, optional Absolute or relative time reference (must be combined with scale and offset). Default is None. scale : float, optional Scalefactor of the timings (must be combined with reference_domain and offset). Default is None. offset : float, optional Offset for time values (must be combined with reference_domain and scale). Default is None. Attributes ---------- reference_domain : ReferenceContext, optional Absolute or relative time reference. scale : float, optional Scalefactor of the timings. offset : float, optional Offset for time values. Methods ------- parse(element) Parses an 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: Optional[ReferenceContext] = None, scale: Optional[float] = None, offset: Optional[float] = None, ) -> None: """Initializes the TimeReference. Parameters ---------- reference_domain : ReferenceContext, optional Absolute or relative time reference (must be combined with scale and offset). Default is None. scale : float, optional Scalefactor of the timings (must be combined with reference_domain and offset). Default is None. offset : float, optional Offset for time values (must be combined with reference_domain and scale). Default is None. """ nones = [reference_domain is None, scale is None, offset is 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: object) -> bool: 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: ET.Element) -> "TimeReference": """Parses the XML element of TimeReference. Parameters ---------- element : ET.Element A TimeReference element (same as generated by the class itself). Returns ------- TimeReference A TimeReference object. """ if element.find("None") is not None: return TimeReference() timing_element = find_mandatory_field(element, "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) -> dict[str, str]: """Returns the attributes of the TimeReference as a dictionary. Returns ------- dict A dictionary of all attributes of the TimeReference. """ retdict = {} retdict["domainAbsoluteRelative"] = self.reference_domain.get_name() retdict["scale"] = str(self.scale) retdict["offset"] = str(self.offset) return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the TimeReference. Returns ------- ET.Element The ElementTree representation of the TimeReference. """ element = ET.Element("TimeReference") if self._only_nones: ET.SubElement(element, "None") else: ET.SubElement(element, "Timing", self.get_attributes()) return elementThe TimeReference class creates a TimeReference.
Parameters
reference_domain:ReferenceContext, optional- Absolute or relative time reference (must be combined with scale and offset). Default is None.
scale:float, optional- Scalefactor of the timings (must be combined with reference_domain and offset). Default is None.
offset:float, optional- Offset for time values (must be combined with reference_domain and scale). Default is None.
Attributes
reference_domain:ReferenceContext, optional- Absolute or relative time reference.
scale:float, optional- Scalefactor of the timings.
offset:float, optional- Offset for time values.
Methods
parse(element) Parses an 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.
Initializes the TimeReference.
Parameters
reference_domain:ReferenceContext, optional- Absolute or relative time reference (must be combined with scale and offset). Default is None.
scale:float, optional- Scalefactor of the timings (must be combined with reference_domain and offset). Default is None.
offset:float, optional- Offset for time values (must be combined with reference_domain and scale). Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> TimeReference-
Expand source code
@staticmethod def parse(element: ET.Element) -> "TimeReference": """Parses the XML element of TimeReference. Parameters ---------- element : ET.Element A TimeReference element (same as generated by the class itself). Returns ------- TimeReference A TimeReference object. """ if element.find("None") is not None: return TimeReference() timing_element = find_mandatory_field(element, "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)Parses the XML element of TimeReference.
Parameters
element:ET.Element- A TimeReference element (same as generated by the class itself).
Returns
TimeReference- A TimeReference object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the TimeReference as a dictionary. Returns ------- dict A dictionary of all attributes of the TimeReference. """ retdict = {} retdict["domainAbsoluteRelative"] = self.reference_domain.get_name() retdict["scale"] = str(self.scale) retdict["offset"] = str(self.offset) return retdictReturns the attributes of the TimeReference as a dictionary.
Returns
dict- A dictionary of all attributes of the TimeReference.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the TimeReference. Returns ------- ET.Element The ElementTree representation of the TimeReference. """ element = ET.Element("TimeReference") if self._only_nones: ET.SubElement(element, "None") else: ET.SubElement(element, "Timing", self.get_attributes()) return elementReturns the ElementTree of the TimeReference.
Returns
ET.Element- The ElementTree representation of the TimeReference.
class TrafficDefinition (name: str)-
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 float The weights of the vehicle categories (VehicleCategoryDistribution-weight). vehiclecategories : list of VehicleCategory The vehicle category (VehicleCategoryDistribution-category). controllerweights : list of float The weights of the controllers. controllers : list of Controller or CatalogReference The controllers for the traffic. vehicle_roles : list of Role The roles of the vehicles. vehicle_roles_weights : list of float The weights of the vehicle roles. Methods ------- parse(element) Parses an 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. add_vehicle_role(vehicle_role, weight) Adds a vehicle role to the traffic definition. """ def __init__(self, name: str) -> None: """Initializes 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: object) -> bool: 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: ET.Element) -> "TrafficDefinition": """Parses the XML element of TrafficDefinition. Parameters ---------- element : ET.Element A TrafficDefinition element (same as generated by the class itself). Returns ------- TrafficDefinition A TrafficDefinition object. """ name = element.attrib["name"] td = TrafficDefinition(name) vehicle_distributions = find_mandatory_field( element, "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 = find_mandatory_field( element, "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") is not None: controller = Controller.parse( find_mandatory_field(controller_dist, "Controller") ) td.add_controller(controller, weight) else: catalog_reference = CatalogReference.parse( find_mandatory_field(controller_dist, "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: VehicleCategory, weight: float ) -> "TrafficDefinition": """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. Returns ------- TrafficDefinition The updated TrafficDefinition object. """ self.vehiclecategories.append( convert_enum(vehiclecategory, VehicleCategory) ) self.vehicleweights.append(weight) return self def add_vehicle_role( self, vehicle_role: Role, weight: float ) -> "TrafficDefinition": """Adds a vehicle role to the traffic distribution. Parameters ---------- vehicle_role : Role Role of the vehicle. weight : float The corresponding weight for the distribution of the vehicle role. Returns ------- TrafficDefinition The updated TrafficDefinition object. """ self.vehicle_roles_weights.append(convert_float(weight)) self.vehicle_roles.append(convert_enum(vehicle_role, Role)) def add_controller( self, controller: Union[Controller, CatalogReference], weight: float ) -> "TrafficDefinition": """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. Returns ------- TrafficDefinition The updated TrafficDefinition object. """ if not isinstance(controller, (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) -> dict[str, str]: """Returns the attributes of the TrafficDefinition as a dictionary. Returns ------- dict A dictionary of all attributes of the TrafficDefinition. """ retdict = {} retdict["name"] = self.name return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the TrafficDefinition. Returns ------- ET.Element The ElementTree representation of the TrafficDefinition. """ if not self.controllers: raise ValueError( "No controllers defined for the TrafficDefinition" ) if not self.vehiclecategories: raise ValueError("No Vehicles defined for the TrafficDefinition") element = ET.Element("TrafficDefinition", attrib=self.get_attributes()) veh_element = ET.SubElement(element, "VehicleCategoryDistribution") for i, vehicle_category in enumerate(self.vehiclecategories): ET.SubElement( veh_element, "VehicleCategoryDistributionEntry", attrib={ "category": vehicle_category.get_name(), "weight": str(self.vehicleweights[i]), }, ) cnt_element = ET.SubElement(element, "ControllerDistribution") for i, controller in enumerate(self.controllers): tmp_controller = ET.SubElement( cnt_element, "ControllerDistributionEntry", attrib={"weight": str(self.controllerweights[i])}, ) tmp_controller.append(controller.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, role in enumerate(self.vehicle_roles): ET.SubElement( role_element, "VehicleRoleDistributionEntry", attrib={ "role": role.get_name(), "weight": str(self.vehicle_roles_weights[i]), }, ) return elementThe 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:listoffloat- The weights of the vehicle categories (VehicleCategoryDistribution-weight).
vehiclecategories:listofVehicleCategory- The vehicle category (VehicleCategoryDistribution-category).
controllerweights:listoffloat- The weights of the controllers.
controllers:listofControllerorCatalogReference- The controllers for the traffic.
vehicle_roles:listofRole- The roles of the vehicles.
vehicle_roles_weights:listoffloat- The weights of the vehicle roles.
Methods
parse(element) Parses an 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. add_vehicle_role(vehicle_role, weight) Adds a vehicle role to the traffic definition.
Initializes the TrafficDefinition.
Parameters
name:str- Name of the traffic definition.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> TrafficDefinition-
Expand source code
@staticmethod def parse(element: ET.Element) -> "TrafficDefinition": """Parses the XML element of TrafficDefinition. Parameters ---------- element : ET.Element A TrafficDefinition element (same as generated by the class itself). Returns ------- TrafficDefinition A TrafficDefinition object. """ name = element.attrib["name"] td = TrafficDefinition(name) vehicle_distributions = find_mandatory_field( element, "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 = find_mandatory_field( element, "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") is not None: controller = Controller.parse( find_mandatory_field(controller_dist, "Controller") ) td.add_controller(controller, weight) else: catalog_reference = CatalogReference.parse( find_mandatory_field(controller_dist, "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 tdParses the XML element of TrafficDefinition.
Parameters
element:ET.Element- A TrafficDefinition element (same as generated by the class itself).
Returns
TrafficDefinition- A TrafficDefinition object.
Methods
def add_controller(self,
controller: Controller | CatalogReference,
weight: float) ‑> TrafficDefinition-
Expand source code
def add_controller( self, controller: Union[Controller, CatalogReference], weight: float ) -> "TrafficDefinition": """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. Returns ------- TrafficDefinition The updated TrafficDefinition object. """ if not isinstance(controller, (Controller, CatalogReference)): raise TypeError( "controller input not of type Controller or CatalogReference" ) self.controllers.append(controller) self.controllerweights.append(weight) return selfAdds a controller to the traffic distribution.
Parameters
controller:ControllerorCatalogReference- A controller or catalog reference to a controller.
weight:float- The corresponding weight for the controller.
Returns
TrafficDefinition- The updated TrafficDefinition object.
def add_vehicle(self,
vehiclecategory: VehicleCategory,
weight: float) ‑> TrafficDefinition-
Expand source code
def add_vehicle( self, vehiclecategory: VehicleCategory, weight: float ) -> "TrafficDefinition": """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. Returns ------- TrafficDefinition The updated TrafficDefinition object. """ self.vehiclecategories.append( convert_enum(vehiclecategory, VehicleCategory) ) self.vehicleweights.append(weight) return selfAdds 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.
Returns
TrafficDefinition- The updated TrafficDefinition object.
def add_vehicle_role(self,
vehicle_role: Role,
weight: float) ‑> TrafficDefinition-
Expand source code
def add_vehicle_role( self, vehicle_role: Role, weight: float ) -> "TrafficDefinition": """Adds a vehicle role to the traffic distribution. Parameters ---------- vehicle_role : Role Role of the vehicle. weight : float The corresponding weight for the distribution of the vehicle role. Returns ------- TrafficDefinition The updated TrafficDefinition object. """ self.vehicle_roles_weights.append(convert_float(weight)) self.vehicle_roles.append(convert_enum(vehicle_role, Role))Adds a vehicle role to the traffic distribution.
Parameters
vehicle_role:Role- Role of the vehicle.
weight:float- The corresponding weight for the distribution of the vehicle role.
Returns
TrafficDefinition- The updated TrafficDefinition object.
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the TrafficDefinition as a dictionary. Returns ------- dict A dictionary of all attributes of the TrafficDefinition. """ retdict = {} retdict["name"] = self.name return retdictReturns the attributes of the TrafficDefinition as a dictionary.
Returns
dict- A dictionary of all attributes of the TrafficDefinition.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the TrafficDefinition. Returns ------- ET.Element The ElementTree representation of the TrafficDefinition. """ if not self.controllers: raise ValueError( "No controllers defined for the TrafficDefinition" ) if not self.vehiclecategories: raise ValueError("No Vehicles defined for the TrafficDefinition") element = ET.Element("TrafficDefinition", attrib=self.get_attributes()) veh_element = ET.SubElement(element, "VehicleCategoryDistribution") for i, vehicle_category in enumerate(self.vehiclecategories): ET.SubElement( veh_element, "VehicleCategoryDistributionEntry", attrib={ "category": vehicle_category.get_name(), "weight": str(self.vehicleweights[i]), }, ) cnt_element = ET.SubElement(element, "ControllerDistribution") for i, controller in enumerate(self.controllers): tmp_controller = ET.SubElement( cnt_element, "ControllerDistributionEntry", attrib={"weight": str(self.controllerweights[i])}, ) tmp_controller.append(controller.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, role in enumerate(self.vehicle_roles): ET.SubElement( role_element, "VehicleRoleDistributionEntry", attrib={ "role": role.get_name(), "weight": str(self.vehicle_roles_weights[i]), }, ) return elementReturns the ElementTree of the TrafficDefinition.
Returns
ET.Element- The ElementTree representation of the TrafficDefinition.
class TrafficSignalController (name: str, delay: float | None = None, reference: str | None = None)-
Expand source code
class TrafficSignalController(VersionBase): """The TrafficSignalController class creates a polyline of (minimum 2) positions. Parameters ---------- name : str ID of the traffic signal. delay : float, optional Delay of the phase shift. Default is None. reference : str, optional ID to the controller in the road network. Default is None. Attributes ---------- name : str ID of the traffic signal. delay : float, optional Delay of the phase shift. reference : str, optional ID to the controller in the road network. Methods ------- parse(element) Parses an 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) Adds a phase to the traffic signal controller. """ def __init__( self, name: str, delay: Optional[float] = None, reference: Optional[str] = None, ) -> None: """Initializes the TrafficSignalController. Parameters ---------- name : str ID of the traffic signal. delay : float, optional Delay of the phase shift. Default is None. reference : str, optional ID to the controller in the road network. Default is None. """ self.name = name self.delay = delay self.reference = reference self.phases = [] def __eq__(self, other: object) -> bool: if isinstance(other, TrafficSignalController): if ( self.get_attributes() == other.get_attributes() and self.phases == other.phases ): return True return False @staticmethod def parse(element: ET.Element) -> "TrafficSignalController": """Parses the XML element of TrafficSignalController. Parameters ---------- element : ET.Element A traffic signal controller element (same as generated by the class itself). Returns ------- 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 is not None: for phase in phases: tsc.phases.append(Phase.parse(phase)) return tsc def add_phase(self, phase: Phase) -> "TrafficSignalController": """Adds a phase of the traffic signal. Parameters ---------- phase : Phase A phase of the traffic signal. Returns ------- TrafficSignalController The updated TrafficSignalController object. """ if not isinstance(phase, Phase): raise TypeError("phase input is not of type Phase") self.phases.append(phase) return self def get_attributes(self) -> dict[str, str]: """Returns the attributes of the TrafficSignalController as a dictionary. Returns ------- dict A dictionary of all 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) -> ET.Element: """Returns the ElementTree of the TrafficSignalController. Returns ------- ET.Element The ElementTree representation of the TrafficSignalController. """ element = ET.Element( "TrafficSignalController", attrib=self.get_attributes() ) for ph in self.phases: element.append(ph.get_element()) return elementThe TrafficSignalController class creates a polyline of (minimum 2) positions.
Parameters
name:str- ID of the traffic signal.
delay:float, optional- Delay of the phase shift. Default is None.
reference:str, optional- ID to the controller in the road network. Default is None.
Attributes
name:str- ID of the traffic signal.
delay:float, optional- Delay of the phase shift.
reference:str, optional- ID to the controller in the road network.
Methods
parse(element) Parses an 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) Adds a phase to the traffic signal controller.
Initializes the TrafficSignalController.
Parameters
name:str- ID of the traffic signal.
delay:float, optional- Delay of the phase shift. Default is None.
reference:str, optional- ID to the controller in the road network. Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> TrafficSignalController-
Expand source code
@staticmethod def parse(element: ET.Element) -> "TrafficSignalController": """Parses the XML element of TrafficSignalController. Parameters ---------- element : ET.Element A traffic signal controller element (same as generated by the class itself). Returns ------- 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 is not None: for phase in phases: tsc.phases.append(Phase.parse(phase)) return tscParses the XML element of TrafficSignalController.
Parameters
element:ET.Element- A traffic signal controller element (same as generated by the class itself).
Returns
TrafficSignalController- A TrafficSignalController object.
Methods
def add_phase(self,
phase: Phase) ‑> TrafficSignalController-
Expand source code
def add_phase(self, phase: Phase) -> "TrafficSignalController": """Adds a phase of the traffic signal. Parameters ---------- phase : Phase A phase of the traffic signal. Returns ------- TrafficSignalController The updated TrafficSignalController object. """ if not isinstance(phase, Phase): raise TypeError("phase input is not of type Phase") self.phases.append(phase) return selfAdds a phase of the traffic signal.
Parameters
phase:Phase- A phase of the traffic signal.
Returns
TrafficSignalController- The updated TrafficSignalController object.
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the TrafficSignalController as a dictionary. Returns ------- dict A dictionary of all 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 retdictReturns the attributes of the TrafficSignalController as a dictionary.
Returns
dict- A dictionary of all attributes of the TrafficSignalController.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the TrafficSignalController. Returns ------- ET.Element The ElementTree representation of the TrafficSignalController. """ element = ET.Element( "TrafficSignalController", attrib=self.get_attributes() ) for ph in self.phases: element.append(ph.get_element()) return elementReturns the ElementTree of the TrafficSignalController.
Returns
ET.Element- The ElementTree representation of the TrafficSignalController.
class TransitionDynamics (shape: DynamicsShapes,
dimension: DynamicsDimension,
value: float,
following_mode: FollowingMode | None = 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, optional The following mode of the TransitionDynamics (valid from OSC V1.2). Default is 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, optional The following mode of the TransitionDynamics. Methods ------- parse(element) Parses an 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: DynamicsShapes, dimension: DynamicsDimension, value: float, following_mode: Optional[FollowingMode] = None, ) -> None: """Initializes the TransitionDynamics. 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, optional The following mode of the TransitionDynamics (valid from OSC V1.2). Default is 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: object) -> bool: if isinstance(other, TransitionDynamics): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "TransitionDynamics": """Parses the XML element of TransitionDynamics. Parameters ---------- element : ET.Element A TransitionDynamics element (same as generated by the class itself). Returns ------- 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) -> dict[str, str]: """Returns the attributes of the TransitionDynamics as a dictionary. Returns ------- dict A dictionary of all attributes of the TransitionDynamics. """ 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: str = "TransitionDynamics") -> ET.Element: """Returns the ElementTree of the TransitionDynamics. Parameters ---------- name : str, optional The name of the element. Default is "TransitionDynamics". Returns ------- ET.Element The ElementTree representation of the TransitionDynamics. """ return ET.Element(name, self.get_attributes())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, optional- The following mode of the TransitionDynamics (valid from OSC V1.2). Default is 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, optional- The following mode of the TransitionDynamics.
Methods
parse(element) Parses an 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.
Initializes the TransitionDynamics.
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, optional- The following mode of the TransitionDynamics (valid from OSC V1.2). Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> TransitionDynamics-
Expand source code
@staticmethod def parse(element: ET.Element) -> "TransitionDynamics": """Parses the XML element of TransitionDynamics. Parameters ---------- element : ET.Element A TransitionDynamics element (same as generated by the class itself). Returns ------- 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)Parses the XML element of TransitionDynamics.
Parameters
element:ET.Element- A TransitionDynamics element (same as generated by the class itself).
Returns
TransitionDynamics- A TransitionDynamics object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the TransitionDynamics as a dictionary. Returns ------- dict A dictionary of all attributes of the TransitionDynamics. """ 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 retdictReturns the attributes of the TransitionDynamics as a dictionary.
Returns
dict- A dictionary of all attributes of the TransitionDynamics.
def get_element(self, name: str = 'TransitionDynamics') ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self, name: str = "TransitionDynamics") -> ET.Element: """Returns the ElementTree of the TransitionDynamics. Parameters ---------- name : str, optional The name of the element. Default is "TransitionDynamics". Returns ------- ET.Element The ElementTree representation of the TransitionDynamics. """ return ET.Element(name, self.get_attributes())Returns the ElementTree of the TransitionDynamics.
Parameters
name:str, optional- The name of the element. Default is "TransitionDynamics".
Returns
ET.Element- The ElementTree representation of the TransitionDynamics.
class UserDefinedAnimation (type: str)-
Expand source code
class UserDefinedAnimation(_AnimationType): """UserDefinedAnimation creates a UserDefinedAnimation element of OpenSCENARIO (valid from OpenSCENARIO V1.2). Parameters ---------- userDefinedAnimationType : str The available user-defined animation types are subject to a contract between the simulation environment provider and the scenario author. Attributes ---------- userDefinedAnimationType : str The available user-defined animation types are subject to a contract between the simulation environment provider and the scenario author. Methods ------- parse(element) Parses an 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, type: str) -> None: """Initializes the UserDefinedAnimation. Parameters ---------- userDefinedAnimationType : str The available user-defined animation types are subject to a contract between the simulation environment provider and the scenario author. """ self.type = type def __eq__(self, other: object) -> bool: if isinstance(other, UserDefinedAnimation): if other.get_attributes() == self.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "UserDefinedAnimation": """Parses the XML element of UserDefinedAnimation. Parameters ---------- element : ET.Element A UserDefinedAnimation element (same as generated by the class itself). Returns ------- UserDefinedAnimation A UserDefinedAnimation object. """ return UserDefinedAnimation(element.attrib["userDefinedAnimationType"]) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the UserDefinedAnimation as a dictionary. Returns ------- dict A dictionary of all attributes of the UserDefinedAnimation. """ retdict = {} retdict["userDefinedAnimationType"] = self.type return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the UserDefinedAnimation. Returns ------- ET.Element The ElementTree representation of the UserDefinedAnimation. """ if not self.isVersionEqLarger(minor=2): raise OpenSCENARIOVersionError( "UserDefinedAnimation was introduced in OpenSCENARIO V1.2" ) element = ET.Element( "UserDefinedAnimation", attrib=self.get_attributes() ) return elementUserDefinedAnimation creates a UserDefinedAnimation element of OpenSCENARIO (valid from OpenSCENARIO V1.2).
Parameters
userDefinedAnimationType:str- The available user-defined animation types are subject to a contract between the simulation environment provider and the scenario author.
Attributes
userDefinedAnimationType:str- The available user-defined animation types are subject to a contract between the simulation environment provider and the scenario author.
Methods
parse(element) Parses an 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.
Initializes the UserDefinedAnimation.
Parameters
userDefinedAnimationType:str- The available user-defined animation types are subject to a contract between the simulation environment provider and the scenario author.
Ancestors
- scenariogeneration.xosc.utils._AnimationType
- VersionBase
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> UserDefinedAnimation-
Expand source code
@staticmethod def parse(element: ET.Element) -> "UserDefinedAnimation": """Parses the XML element of UserDefinedAnimation. Parameters ---------- element : ET.Element A UserDefinedAnimation element (same as generated by the class itself). Returns ------- UserDefinedAnimation A UserDefinedAnimation object. """ return UserDefinedAnimation(element.attrib["userDefinedAnimationType"])Parses the XML element of UserDefinedAnimation.
Parameters
element:ET.Element- A UserDefinedAnimation element (same as generated by the class itself).
Returns
UserDefinedAnimation- A UserDefinedAnimation object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the UserDefinedAnimation as a dictionary. Returns ------- dict A dictionary of all attributes of the UserDefinedAnimation. """ retdict = {} retdict["userDefinedAnimationType"] = self.type return retdictReturns the attributes of the UserDefinedAnimation as a dictionary.
Returns
dict- A dictionary of all attributes of the UserDefinedAnimation.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the UserDefinedAnimation. Returns ------- ET.Element The ElementTree representation of the UserDefinedAnimation. """ if not self.isVersionEqLarger(minor=2): raise OpenSCENARIOVersionError( "UserDefinedAnimation was introduced in OpenSCENARIO V1.2" ) element = ET.Element( "UserDefinedAnimation", attrib=self.get_attributes() ) return elementReturns the ElementTree of the UserDefinedAnimation.
Returns
ET.Element- The ElementTree representation of the UserDefinedAnimation.
class UserDefinedComponent (type: str)-
Expand source code
class UserDefinedComponent(_AnimationType): """UserDefinedComponent creates a UserDefinedComponent element of OpenSCENARIO (valid from OpenSCENARIO V1.2). Parameters ---------- userDefinedComponentType : str User-defined component type. Attributes ---------- userDefinedComponentType : str User-defined component type. Methods ------- parse(element) Parses an 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, type: str) -> None: """Initializes the UserDefinedComponent. Parameters ---------- userDefinedComponentType : str User-defined component type. """ self.type = type def __eq__(self, other: object) -> bool: if isinstance(other, UserDefinedComponent): if other.get_attributes() == self.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "UserDefinedComponent": """Parses the XML element of UserDefinedComponent. Parameters ---------- element : ET.Element A UserDefinedComponent element (same as generated by the class itself). Returns ------- UserDefinedComponent A UserDefinedComponent object. """ return UserDefinedComponent(element.attrib["userDefinedComponentType"]) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the UserDefinedComponent as a dictionary. Returns ------- dict A dictionary of all attributes of the UserDefinedComponent. """ retdict = {} retdict["userDefinedComponentType"] = self.type return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the UserDefinedComponent. Returns ------- ET.Element The ElementTree representation of the UserDefinedComponent. """ if not self.isVersionEqLarger(minor=2): raise OpenSCENARIOVersionError( "UserDefinedComponent was introduced in OpenSCENARIO V1.2" ) element = ET.Element( "UserDefinedComponent", attrib=self.get_attributes() ) return elementUserDefinedComponent creates a UserDefinedComponent element of OpenSCENARIO (valid from OpenSCENARIO V1.2).
Parameters
userDefinedComponentType:str- User-defined component type.
Attributes
userDefinedComponentType:str- User-defined component type.
Methods
parse(element) Parses an 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.
Initializes the UserDefinedComponent.
Parameters
userDefinedComponentType:str- User-defined component type.
Ancestors
- scenariogeneration.xosc.utils._AnimationType
- VersionBase
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> UserDefinedComponent-
Expand source code
@staticmethod def parse(element: ET.Element) -> "UserDefinedComponent": """Parses the XML element of UserDefinedComponent. Parameters ---------- element : ET.Element A UserDefinedComponent element (same as generated by the class itself). Returns ------- UserDefinedComponent A UserDefinedComponent object. """ return UserDefinedComponent(element.attrib["userDefinedComponentType"])Parses the XML element of UserDefinedComponent.
Parameters
element:ET.Element- A UserDefinedComponent element (same as generated by the class itself).
Returns
UserDefinedComponent- A UserDefinedComponent object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the UserDefinedComponent as a dictionary. Returns ------- dict A dictionary of all attributes of the UserDefinedComponent. """ retdict = {} retdict["userDefinedComponentType"] = self.type return retdictReturns the attributes of the UserDefinedComponent as a dictionary.
Returns
dict- A dictionary of all attributes of the UserDefinedComponent.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the UserDefinedComponent. Returns ------- ET.Element The ElementTree representation of the UserDefinedComponent. """ if not self.isVersionEqLarger(minor=2): raise OpenSCENARIOVersionError( "UserDefinedComponent was introduced in OpenSCENARIO V1.2" ) element = ET.Element( "UserDefinedComponent", attrib=self.get_attributes() ) return elementReturns the ElementTree of the UserDefinedComponent.
Returns
ET.Element- The ElementTree representation of the UserDefinedComponent.
class UserDefinedLight (user_defined_type: str)-
Expand source code
class UserDefinedLight(VersionBase): """UserDefinedLight creates a UserDefinedLight element of OpenSCENARIO (valid from OpenSCENARIO V1.2). Parameters ---------- user_defined_type : str String of the user-defined light. Attributes ---------- type : str Type of the user-defined light. Methods ------- parse(element) Parses an ElementTree created by the class and returns an instance of the class. get_element() Returns the full ElementTree of the class. """ def __init__(self, user_defined_type: str) -> None: """Initializes the UserDefinedLight. Parameters ---------- user_defined_type : str Type of the user-defined light. """ self.type = user_defined_type def __eq__(self, other: object) -> bool: if isinstance(other, UserDefinedLight): if other.type == self.type: return True return False @staticmethod def parse(element: ET.Element) -> "UserDefinedLight": """Parses the XML element of UserDefinedLight. Parameters ---------- element : ET.Element A UserDefinedLight element (same as generated by the class itself). Returns ------- UserDefinedLight A UserDefinedLight object. """ return UserDefinedLight(element.attrib["userDefinedLightType"]) def get_element(self) -> ET.Element: """Returns the ElementTree of the UserDefinedLight. Returns ------- ET.Element The ElementTree representation 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 elementUserDefinedLight creates a UserDefinedLight element of OpenSCENARIO (valid from OpenSCENARIO V1.2).
Parameters
user_defined_type:str- String of the user-defined light.
Attributes
type:str- Type of the user-defined light.
Methods
parse(element) Parses an ElementTree created by the class and returns an instance of the class. get_element() Returns the full ElementTree of the class.
Initializes the UserDefinedLight.
Parameters
user_defined_type:str- Type of the user-defined light.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> UserDefinedLight-
Expand source code
@staticmethod def parse(element: ET.Element) -> "UserDefinedLight": """Parses the XML element of UserDefinedLight. Parameters ---------- element : ET.Element A UserDefinedLight element (same as generated by the class itself). Returns ------- UserDefinedLight A UserDefinedLight object. """ return UserDefinedLight(element.attrib["userDefinedLightType"])Parses the XML element of UserDefinedLight.
Parameters
element:ET.Element- A UserDefinedLight element (same as generated by the class itself).
Returns
UserDefinedLight- A UserDefinedLight object.
Methods
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the UserDefinedLight. Returns ------- ET.Element The ElementTree representation 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 elementReturns the ElementTree of the UserDefinedLight.
Returns
ET.Element- The ElementTree representation of the UserDefinedLight.
class ValueConstraint (rule: Rule,
value: str)-
Expand source code
class ValueConstraint(VersionBase): """ValueConstraint creates a ValueConstraint element of OpenScenario (valid from OpenSCENARIO V1.1). 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 : str 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. value : str A constant value, parameter or parameter expression. Methods ------- parse(element) Parses an 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, rule: Rule, value: str) -> None: """Initializes the ValueConstraint. 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 : str 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: object) -> bool: if isinstance(other, ValueConstraint): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "ValueConstraint": """Parses the XML element of ValueConstraint. Parameters ---------- element : ET.Element A ValueConstraint element (same as generated by the class itself). Returns ------- ValueConstraint A ValueConstraint object. """ value = element.attrib["value"] rule = convert_enum(element.attrib["rule"], Rule) return ValueConstraint(rule, value) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the ValueConstraint as a dictionary. Returns ------- dict A dictionary of all attributes of the ValueConstraint. """ retdict = {} retdict["rule"] = self.rule.get_name() retdict["value"] = str(self.value) return retdict def get_element(self) -> ET.Element: """Returns the ElementTree of the ValueConstraint. Returns ------- ET.Element The ElementTree representation 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 elementValueConstraint creates a ValueConstraint element of OpenScenario (valid from OpenSCENARIO V1.1).
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:str- 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.
value:str- A constant value, parameter or parameter expression.
Methods
parse(element) Parses an 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.
Initializes the ValueConstraint.
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:str- A constant value, parameter or parameter expression. The value must match the enclosing parameter declaration.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> ValueConstraint-
Expand source code
@staticmethod def parse(element: ET.Element) -> "ValueConstraint": """Parses the XML element of ValueConstraint. Parameters ---------- element : ET.Element A ValueConstraint element (same as generated by the class itself). Returns ------- ValueConstraint A ValueConstraint object. """ value = element.attrib["value"] rule = convert_enum(element.attrib["rule"], Rule) return ValueConstraint(rule, value)Parses the XML element of ValueConstraint.
Parameters
element:ET.Element- A ValueConstraint element (same as generated by the class itself).
Returns
ValueConstraint- A ValueConstraint object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the ValueConstraint as a dictionary. Returns ------- dict A dictionary of all attributes of the ValueConstraint. """ retdict = {} retdict["rule"] = self.rule.get_name() retdict["value"] = str(self.value) return retdictReturns the attributes of the ValueConstraint as a dictionary.
Returns
dict- A dictionary of all attributes of the ValueConstraint.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the ValueConstraint. Returns ------- ET.Element The ElementTree representation 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 elementReturns the ElementTree of the ValueConstraint.
Returns
ET.Element- The ElementTree representation of the ValueConstraint.
class ValueConstraintGroup-
Expand source code
class ValueConstraintGroup(VersionBase): """ValueConstraintGroup creates a ValueConstraintGroup element of OpenScenario (valid from OpenSCENARIO V1.1). Attributes ---------- value_constraints : list of ValueConstraint List of value constraints. Methods ------- add_value_constraint(value_constraint) Adds a value constraint to the value constraint group. parse(element) Parses an ElementTree created by the class and returns an instance of the class. get_element() Returns the full ElementTree of the class. """ def __init__(self) -> None: """Initializes the ValueConstraintGroup.""" self.value_constraints = [] def __eq__(self, other: object) -> bool: if isinstance(other, ValueConstraintGroup): if self.value_constraints == other.value_constraints: return True return False def add_value_constraint( self, value_constraint: ValueConstraint ) -> "ValueConstraintGroup": """Adds a value constraint to the value constraint group. Parameters ---------- value_constraint : ValueConstraint The value constraint to be added. Returns ------- ValueConstraintGroup The updated ValueConstraintGroup object. """ 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: ET.Element) -> "ValueConstraintGroup": """Parses the XML element of ValueConstraintGroup. Parameters ---------- element : ET.Element A ValueConstraintGroup element (same as generated by the class itself). Returns ------- 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) -> ET.Element: """Returns the ElementTree of the ValueConstraintGroup. Returns ------- ET.Element The ElementTree representation 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 elementValueConstraintGroup creates a ValueConstraintGroup element of OpenScenario (valid from OpenSCENARIO V1.1).
Attributes
value_constraints:listofValueConstraint- List of value constraints.
Methods
add_value_constraint(value_constraint) Adds a value constraint to the value constraint group. parse(element) Parses an ElementTree created by the class and returns an instance of the class. get_element() Returns the full ElementTree of the class.
Initializes the ValueConstraintGroup.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> ValueConstraintGroup-
Expand source code
@staticmethod def parse(element: ET.Element) -> "ValueConstraintGroup": """Parses the XML element of ValueConstraintGroup. Parameters ---------- element : ET.Element A ValueConstraintGroup element (same as generated by the class itself). Returns ------- 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_constraintsParses the XML element of ValueConstraintGroup.
Parameters
element:ET.Element- A ValueConstraintGroup element (same as generated by the class itself).
Returns
ValueConstraintGroup- A ValueConstraintGroup object.
Methods
def add_value_constraint(self,
value_constraint: ValueConstraint) ‑> ValueConstraintGroup-
Expand source code
def add_value_constraint( self, value_constraint: ValueConstraint ) -> "ValueConstraintGroup": """Adds a value constraint to the value constraint group. Parameters ---------- value_constraint : ValueConstraint The value constraint to be added. Returns ------- ValueConstraintGroup The updated ValueConstraintGroup object. """ if not isinstance(value_constraint, ValueConstraint): raise TypeError( "value_conatraint input is not of type ValueConstraint" ) self.value_constraints.append(value_constraint) return selfAdds a value constraint to the value constraint group.
Parameters
value_constraint:ValueConstraint- The value constraint to be added.
Returns
ValueConstraintGroup- The updated ValueConstraintGroup object.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the ValueConstraintGroup. Returns ------- ET.Element The ElementTree representation 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 elementReturns the ElementTree of the ValueConstraintGroup.
Returns
ET.Element- The ElementTree representation of the ValueConstraintGroup.
class Variable (name: str,
variable_type: ParameterType,
value: str)-
Expand source code
class Variable(VersionBase): """Variable is a declaration of an entry in VariableDeclaration (valid from V1.2). Parameters ---------- name : str Name of the variable. variable_type : ParameterType Type of the variable. value : str Value of the variable. Attributes ---------- name : str Name of the variable. variable_type : ParameterType Type of the variable. value : str Value of the variable. Methods ------- parse(element) Parses an 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: str, variable_type: ParameterType, value: str ) -> None: """Initializes the Variable. Parameters ---------- name : str Name of the 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: object) -> bool: 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: ET.Element) -> "Variable": """Parses the XML element of Variable. Parameters ---------- element : ET.Element A Variable element (same as generated by the class itself). Returns ------- Variable A 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) return variable def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Variable as a dictionary. Returns ------- dict A dictionary of all attributes of the Variable. """ return { "name": self.name, "variableType": self.variable_type.get_name(), "value": str(self.value), } def get_element(self) -> ET.Element: """Returns the ElementTree of the Variable. Returns ------- ET.Element The ElementTree representation 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 elementVariable is a declaration of an entry in VariableDeclaration (valid from V1.2).
Parameters
name:str- Name of the variable.
variable_type:ParameterType- Type of the variable.
value:str- Value of the variable.
Attributes
name:str- Name of the variable.
variable_type:ParameterType- Type of the variable.
value:str- Value of the variable.
Methods
parse(element) Parses an 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.
Initializes the Variable.
Parameters
name:str- Name of the variable.
variable_type:ParameterType- Type of the variable.
value:str- Value of the variable.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Variable-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Variable": """Parses the XML element of Variable. Parameters ---------- element : ET.Element A Variable element (same as generated by the class itself). Returns ------- Variable A 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) return variableParses the XML element of Variable.
Parameters
element:ET.Element- A Variable element (same as generated by the class itself).
Returns
Variable- A Variable object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Variable as a dictionary. Returns ------- dict A dictionary of all attributes of the Variable. """ return { "name": self.name, "variableType": self.variable_type.get_name(), "value": str(self.value), }Returns the attributes of the Variable as a dictionary.
Returns
dict- A dictionary of all attributes of the Variable.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Variable. Returns ------- ET.Element The ElementTree representation 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 elementReturns the ElementTree of the Variable.
Returns
ET.Element- The ElementTree representation of the Variable.
class VariableDeclarations-
Expand source code
class VariableDeclarations(VersionBase): """The VariableDeclarations class creates the VariableDeclarations of OpenScenario (Valid from V1.2). Attributes ---------- variables : list of Variable 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 an ElementTree created by the class and returns an instance of the class. """ def __init__(self) -> None: """Initializes the VariableDeclarations.""" self.variables = [] @staticmethod def parse(element: ET.Element) -> "VariableDeclarations": """Parses the XML element of VariableDeclarations. Parameters ---------- element : ET.Element A VariableDeclarations element (same as generated by the class itself). Returns ------- 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: object) -> bool: if isinstance(other, VariableDeclarations): if self.variables == other.variables: return True return False def add_variable(self, variable: Variable) -> "VariableDeclarations": """Adds a Variable to the VariableDeclarations. Parameters ---------- variable : Variable A new variable. Returns ------- VariableDeclarations The updated VariableDeclarations object. """ if not isinstance(variable, Variable): raise TypeError("variable input is not of type Variable") self.variables.append(variable) return self def get_element(self) -> Optional[ET.Element]: """Returns the ElementTree of the VariableDeclarations. Returns ------- ET.Element or None The ElementTree representation of the VariableDeclarations, or None if no variables exist. """ if self.version_minor < 2: raise OpenSCENARIOVersionError( "Variables were introduced in OSC 1.2" ) element = ET.Element("VariableDeclarations") for p in self.variables: element.append(p.get_element()) return elementThe VariableDeclarations class creates the VariableDeclarations of OpenScenario (Valid from V1.2).
Attributes
variables:listofVariable- 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 an ElementTree created by the class and returns an instance of the class.
Initializes the VariableDeclarations.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> VariableDeclarations-
Expand source code
@staticmethod def parse(element: ET.Element) -> "VariableDeclarations": """Parses the XML element of VariableDeclarations. Parameters ---------- element : ET.Element A VariableDeclarations element (same as generated by the class itself). Returns ------- 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_declarationsParses the XML element of VariableDeclarations.
Parameters
element:ET.Element- A VariableDeclarations element (same as generated by the class itself).
Returns
VariableDeclarations- A VariableDeclarations object.
Methods
def add_variable(self,
variable: Variable) ‑> VariableDeclarations-
Expand source code
def add_variable(self, variable: Variable) -> "VariableDeclarations": """Adds a Variable to the VariableDeclarations. Parameters ---------- variable : Variable A new variable. Returns ------- VariableDeclarations The updated VariableDeclarations object. """ if not isinstance(variable, Variable): raise TypeError("variable input is not of type Variable") self.variables.append(variable) return selfAdds a Variable to the VariableDeclarations.
Parameters
variable:Variable- A new variable.
Returns
VariableDeclarations- The updated VariableDeclarations object.
def get_element(self) ‑> xml.etree.ElementTree.Element | None-
Expand source code
def get_element(self) -> Optional[ET.Element]: """Returns the ElementTree of the VariableDeclarations. Returns ------- ET.Element or None The ElementTree representation of the VariableDeclarations, or None if no variables exist. """ if self.version_minor < 2: raise OpenSCENARIOVersionError( "Variables were introduced in OSC 1.2" ) element = ET.Element("VariableDeclarations") for p in self.variables: element.append(p.get_element()) return elementReturns the ElementTree of the VariableDeclarations.
Returns
ET.ElementorNone- The ElementTree representation of the VariableDeclarations, or None if no variables exist.
class Weather (cloudstate: CloudState | FractionalCloudCover | None = None,
atmosphericPressure: float | None = None,
temperature: float | None = None,
sun: Sun | None = None,
fog: Fog | None = None,
precipitation: Precipitation | None = None,
wind: Wind | None = None,
dome_image: str | None = None,
dome_azimuth_offset: float | None = None)-
Expand source code
class Weather(VersionBase): """Weather creates a Weather element of OpenScenario. Parameters ---------- cloudstate : Union[CloudState, FractionalCloudCover], optional Cloudstate of the weather (CloudState (V1.0-1.1), FractionalCloudCover (>V1.2)). Default is None. atmosphericPressure : float, optional Atmospheric pressure in Pa (valid from OpenSCENARIO V1.1). Default is None. temperature : float, optional Outside temperature (valid from OpenSCENARIO V1.1). Default is None. sun : Sun, optional The sun position. Default is None. fog : Fog, optional Fog state. Default is None. precipitation : Precipitation, optional The precipitation state. Default is None. wind : Wind, optional The wind (valid from OpenSCENARIO V1.1). Default is None. dome_image : str, optional Image file for the sky (valid from OpenSCENARIO V1.2). Default is None. dome_azimuth_offset : float, optional Offset for dome image (valid from OpenSCENARIO V1.2). Default is None. Attributes ---------- cloudstate : Union[CloudState, FractionalCloudCover], optional Cloudstate of the weather. atmosphericPressure : float, optional Atmospheric pressure in Pa. temperature : float, optional Outside temperature. sun : Sun, optional The sun position. fog : Fog, optional Fog state. precipitation : Precipitation, optional The precipitation state. wind : Wind, optional The wind. dome_image : str, optional Image file for the sky. dome_azimuth_offset : float, optional Offset for dome image. Methods ------- parse(element) Parses an 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: Optional[Union[CloudState, FractionalCloudCover]] = None, atmosphericPressure: Optional[float] = None, temperature: Optional[float] = None, sun: Optional[Sun] = None, fog: Optional[Fog] = None, precipitation: Optional[Precipitation] = None, wind: Optional[Wind] = None, dome_image: Optional[str] = None, dome_azimuth_offset: Optional[float] = None, ) -> None: """Initializes the Weather. Parameters ---------- cloudstate : Union[CloudState, FractionalCloudCover], optional Cloudstate of the weather (CloudState (V1.0-1.1), FractionalCloudCover (>V1.2)). Default is None. atmosphericPressure : float, optional Atmospheric pressure in Pa (valid from OpenSCENARIO V1.1). Default is None. temperature : float, optional Outside temperature (valid from OpenSCENARIO V1.1). Default is None. sun : Sun, optional The sun position. Default is None. fog : Fog, optional Fog state. Default is None. precipitation : Precipitation, optional The precipitation state. Default is None. wind : Wind, optional The wind (valid from OpenSCENARIO V1.1). Default is None. dome_image : str, optional Image file for the sky (valid from OpenSCENARIO V1.2). Default is None. dome_azimuth_offset : float, optional Offset for dome image (valid from OpenSCENARIO V1.2). Default is None. """ try: self.cloudstate = convert_enum(cloudstate, CloudState, True) except (TypeError, ValueError): 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.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: object) -> bool: 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: ET.Element) -> "Weather": """Parses the XML element of Weather. Parameters ---------- element : ET.Element A Weather element (same as generated by the class itself). Returns ------- 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") is not None: sun = Sun.parse(find_mandatory_field(element, "Sun")) if element.find("Fog") is not None: fog = Fog.parse(find_mandatory_field(element, "Fog")) if element.find("Precipitation") is not None: precipitation = Precipitation.parse( find_mandatory_field(element, "Precipitation") ) if element.find("Wind") is not None: wind = Wind.parse(find_mandatory_field(element, "Wind")) if element.find("DomeImage") is not None: dome_file = find_mandatory_field( find_mandatory_field(element, "DomeImage"), "DomeFile" ).attrib["filepath"] if ( "azimuthOffset" in find_mandatory_field(element, "DomeImage").attrib ): dome_azimuth = convert_float( find_mandatory_field(element, "DomeImage").attrib[ "azimuthOffset" ] ) return Weather( cloudstate, atmosphericPressure, temperature, sun, fog, precipitation, wind, dome_file, dome_azimuth, ) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Weather as a dictionary. Returns ------- dict A dictionary of all attributes of the Weather. """ 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) -> ET.Element: """Returns the ElementTree of the Weather. Returns ------- ET.Element The ElementTree representation of the Weather. """ if self.isVersion(minor=0): if self.sun is None: raise OpenSCENARIOVersionError( "In OpenScenario 1.0, Sun is required." ) if self.cloudstate is None: raise OpenSCENARIOVersionError( "In OpenScenario 1.0, CloudState is required." ) if self.fog is None: raise OpenSCENARIOVersionError( "In OpenScenario 1.0, Fog is required." ) if self.precipitation is 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 elementWeather creates a Weather element of OpenScenario.
Parameters
cloudstate:Union[CloudState, FractionalCloudCover], optional- Cloudstate of the weather (CloudState (V1.0-1.1), FractionalCloudCover (>V1.2)). Default is None.
atmosphericPressure:float, optional- Atmospheric pressure in Pa (valid from OpenSCENARIO V1.1). Default is None.
temperature:float, optional- Outside temperature (valid from OpenSCENARIO V1.1). Default is None.
sun:Sun, optional- The sun position. Default is None.
fog:Fog, optional- Fog state. Default is None.
precipitation:Precipitation, optional- The precipitation state. Default is None.
wind:Wind, optional- The wind (valid from OpenSCENARIO V1.1). Default is None.
dome_image:str, optional- Image file for the sky (valid from OpenSCENARIO V1.2). Default is None.
dome_azimuth_offset:float, optional- Offset for dome image (valid from OpenSCENARIO V1.2). Default is None.
Attributes
cloudstate:Union[CloudState, FractionalCloudCover], optional- Cloudstate of the weather.
atmosphericPressure:float, optional- Atmospheric pressure in Pa.
temperature:float, optional- Outside temperature.
sun:Sun, optional- The sun position.
fog:Fog, optional- Fog state.
precipitation:Precipitation, optional- The precipitation state.
wind:Wind, optional- The wind.
dome_image:str, optional- Image file for the sky.
dome_azimuth_offset:float, optional- Offset for dome image.
Methods
parse(element) Parses an 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.
Initializes the Weather.
Parameters
cloudstate:Union[CloudState, FractionalCloudCover], optional- Cloudstate of the weather (CloudState (V1.0-1.1), FractionalCloudCover (>V1.2)). Default is None.
atmosphericPressure:float, optional- Atmospheric pressure in Pa (valid from OpenSCENARIO V1.1). Default is None.
temperature:float, optional- Outside temperature (valid from OpenSCENARIO V1.1). Default is None.
sun:Sun, optional- The sun position. Default is None.
fog:Fog, optional- Fog state. Default is None.
precipitation:Precipitation, optional- The precipitation state. Default is None.
wind:Wind, optional- The wind (valid from OpenSCENARIO V1.1). Default is None.
dome_image:str, optional- Image file for the sky (valid from OpenSCENARIO V1.2). Default is None.
dome_azimuth_offset:float, optional- Offset for dome image (valid from OpenSCENARIO V1.2). Default is None.
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Weather-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Weather": """Parses the XML element of Weather. Parameters ---------- element : ET.Element A Weather element (same as generated by the class itself). Returns ------- 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") is not None: sun = Sun.parse(find_mandatory_field(element, "Sun")) if element.find("Fog") is not None: fog = Fog.parse(find_mandatory_field(element, "Fog")) if element.find("Precipitation") is not None: precipitation = Precipitation.parse( find_mandatory_field(element, "Precipitation") ) if element.find("Wind") is not None: wind = Wind.parse(find_mandatory_field(element, "Wind")) if element.find("DomeImage") is not None: dome_file = find_mandatory_field( find_mandatory_field(element, "DomeImage"), "DomeFile" ).attrib["filepath"] if ( "azimuthOffset" in find_mandatory_field(element, "DomeImage").attrib ): dome_azimuth = convert_float( find_mandatory_field(element, "DomeImage").attrib[ "azimuthOffset" ] ) return Weather( cloudstate, atmosphericPressure, temperature, sun, fog, precipitation, wind, dome_file, dome_azimuth, )Parses the XML element of Weather.
Parameters
element:ET.Element- A Weather element (same as generated by the class itself).
Returns
Weather- A Weather object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Weather as a dictionary. Returns ------- dict A dictionary of all attributes of the Weather. """ 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 retdictReturns the attributes of the Weather as a dictionary.
Returns
dict- A dictionary of all attributes of the Weather.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Weather. Returns ------- ET.Element The ElementTree representation of the Weather. """ if self.isVersion(minor=0): if self.sun is None: raise OpenSCENARIOVersionError( "In OpenScenario 1.0, Sun is required." ) if self.cloudstate is None: raise OpenSCENARIOVersionError( "In OpenScenario 1.0, CloudState is required." ) if self.fog is None: raise OpenSCENARIOVersionError( "In OpenScenario 1.0, Fog is required." ) if self.precipitation is 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 elementReturns the ElementTree of the Weather.
Returns
ET.Element- The ElementTree representation of the Weather.
class Wind (direction: float, speed: float)-
Expand source code
class Wind(VersionBase): """Wind creates a 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 an 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: float, speed: float) -> None: """Initializes the Wind. Parameters ---------- direction : float Wind direction (radians). speed : float Wind speed (m/s). """ self.direction = direction self.speed = speed def __eq__(self, other: object) -> bool: if isinstance(other, Wind): if self.get_attributes() == other.get_attributes(): return True return False @staticmethod def parse(element: ET.Element) -> "Wind": """Parses the XML element of Wind. Parameters ---------- element : ET.Element A Wind element (same as generated by the class itself). Returns ------- Wind A Wind object. """ direction = element.attrib["direction"] speed = element.attrib["speed"] return Wind(direction, speed) def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Wind as a dictionary. Returns ------- dict A dictionary of all attributes of the Wind. """ return {"direction": str(self.direction), "speed": str(self.speed)} def get_element(self) -> ET.Element: """Returns the ElementTree of the Wind. Returns ------- ET.Element The ElementTree representation 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 elementWind creates a 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 an 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.
Initializes the Wind.
Parameters
direction:float- Wind direction (radians).
speed:float- Wind speed (m/s).
Ancestors
Static methods
def parse(element: xml.etree.ElementTree.Element) ‑> Wind-
Expand source code
@staticmethod def parse(element: ET.Element) -> "Wind": """Parses the XML element of Wind. Parameters ---------- element : ET.Element A Wind element (same as generated by the class itself). Returns ------- Wind A Wind object. """ direction = element.attrib["direction"] speed = element.attrib["speed"] return Wind(direction, speed)Parses the XML element of Wind.
Parameters
element:ET.Element- A Wind element (same as generated by the class itself).
Returns
Wind- A Wind object.
Methods
def get_attributes(self) ‑> dict[str, str]-
Expand source code
def get_attributes(self) -> dict[str, str]: """Returns the attributes of the Wind as a dictionary. Returns ------- dict A dictionary of all attributes of the Wind. """ return {"direction": str(self.direction), "speed": str(self.speed)}Returns the attributes of the Wind as a dictionary.
Returns
dict- A dictionary of all attributes of the Wind.
def get_element(self) ‑> xml.etree.ElementTree.Element-
Expand source code
def get_element(self) -> ET.Element: """Returns the ElementTree of the Wind. Returns ------- ET.Element The ElementTree representation 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 elementReturns the ElementTree of the Wind.
Returns
ET.Element- The ElementTree representation of the Wind.