Module scenariogeneration.xosc.parameters

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

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

Copyright (c) 2022 The scenariogeneration Authors.

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

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

  Copyright (c) 2022 The scenariogeneration Authors.

"""
import xml.etree.ElementTree as ET

from .enumerations import VersionBase, XMLNS, XSI, _MINOR_VERSION
from .utils import (
    _StochasticDistributionType,
    FileHeader,
    VersionBase,
    ParameterAssignment,
    Rule,
    convert_float,
)
from .exceptions import (
    NotEnoughInputArguments,
    OpenSCENARIOVersionError,
    NotAValidElement,
)
from ..helpers import prettyprint, printToFile


class _StochasticFactory:
    @staticmethod
    def parse_distribution(element):
        if element.find("NormalDistribution") is not None:
            return NormalDistribution.parse(element.find("NormalDistribution"))
        elif element.find("UniformDistribution") is not None:
            return UniformDistribution.parse(element.find("UniformDistribution"))
        elif element.find("PoissonDistribution") is not None:
            return PoissonDistribution.parse(element.find("PoissonDistribution"))
        elif element.find("Histogram") is not None:
            return Histogram.parse(element.find("Histogram"))
        elif element.find("ProbabilityDistributionSet") is not None:
            return ProbabilityDistributionSet.parse(
                element.find("ProbabilityDistributionSet")
            )
        elif element.find("UserDefinedDistribution") is not None:
            return NotImplementedError(
                "UserDefinedDistribution is not implemented yet."
            )
        else:
            raise NotAValidElement(
                "element ", element, "is not a valid Stochastic distribution"
            )


class _DeterministicFactory:
    @staticmethod
    def parse_distribution(element):
        if element.find("DistributionSet") is not None:
            return DistributionSet.parse(element.find("DistributionSet"))
        elif element.find("DistributionRange") is not None:
            return DistributionRange.parse(element.find("DistributionRange"))
        elif element.find("UserDefinedDistribution") is not None:
            return NotImplementedError(
                "UserDefinedDistribution is not implemented yet."
            )
        else:
            raise NotAValidElement(
                "element ", element, "is not a valid deterministic distribution"
            )


class _HistogramBin(VersionBase):
    """the _HistogramBin is used by Histogram to define the bins

    Parameters
    ----------
        weight (float): the weight of the bin

        range (Range): the range of the bin

    Attributes
    ----------
        weight (float): the weight of the bin

        range (Range): the range of the bin

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

        get_element(elementname)
            Returns the full ElementTree of the class

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

    """

    def __init__(self, weight, range=None):
        """initalizes the Histogram

        Parameters
        ----------
            weight (float): the weight of the bin

            range (Range): the range of the bin

        """
        if range and not isinstance(range, Range):
            raise TypeError("range input is not of type Histogram")
        self.weight = convert_float(weight)
        self.range = range

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

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

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

        Returns
        -------
            histogram (_HistogramBin): a _HistogramBin object

        """
        range_element = element.find("Range")
        if range_element is not None:
            range = Range.parse(range_element)
        else:
            range = None

        return _HistogramBin(convert_float(element.attrib["weight"]), range)

    def get_attributes(self):
        """returns the attributes of the HistogramBin as a dict"""
        retdict = {"weight": str(self.weight)}
        return retdict

    def get_element(self):
        """returns the elementTree of the HistogramBin"""
        element = ET.Element("Bin", self.get_attributes())
        element.append(self.range.get_element())
        return element


class _ProbabilityDistributionSetElement(VersionBase):
    """the _ProbabilityDistributionSetElement is used by ProbabilityDistributionSet to define the elements

    Parameters
    ----------
        value (string): possible value

        weight (float): weight of the value

    Attributes
    ----------
        value (string): possible value

        weight (float): weight of the value

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

        get_element(elementname)
            Returns the full ElementTree of the class

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

    """

    def __init__(self, value, weight):
        """initalizes the Histogram

        Parameters
        ----------
            value (string): possible value

            weight (float): weight of the value

        """
        self.value = value
        self.weight = convert_float(weight)

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

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

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

        Returns
        -------
            pds (_ProbabilityDistributionSetElement): a _ProbabilityDistributionSetElement object

        """

        return _ProbabilityDistributionSetElement(
            element.attrib["value"], convert_float(element.attrib["weight"])
        )

    def get_attributes(self):
        """returns the attributes of the _ProbabilityDistributionSetElement as a dict"""
        retdict = {"value": self.value, "weight": str(self.weight)}
        return retdict

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


class Range(VersionBase):
    """the Range creates a Range used by parameter distributions

    Parameters
    ----------
        lower (float): lower limit of the range

        upper (float): upper limit of the range

    Attributes
    ----------
        lower (float): lower limit of the range

        upper (float): upper limit of the range

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

        get_element(elementname)
            Returns the full ElementTree of the class

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

    """

    def __init__(self, lower, upper):
        """initalizes the Range

        Parameters
        ----------
            lower (float): lower limit of the range

            upper (float): upper limit of the range

        """
        self.lower = convert_float(lower)
        self.upper = convert_float(upper)

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

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

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

        Returns
        -------
            range (Range): a Range object

        """

        return Range(
            convert_float(element.attrib["lowerLimit"]),
            convert_float(element.attrib["upperLimit"]),
        )

    def get_attributes(self):
        """returns the attributes of the Range as a dict"""
        retdict = {"lowerLimit": str(self.lower), "upperLimit": str(self.upper)}
        return retdict

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


## Stochastic distributions
class Stochastic(VersionBase):
    """Creates the Stochastic type of parameter distributions

    Parameters
    ----------
        number_of_tests (int): number of tests to run

        random_seed (float): the seed for the run
            Default: None

    Attributes
    ----------
        number_of_tests (int): number of tests to run

        random_seed (float): the seed for the run

        distributions (dict of *StochasticDistribution): the distributions for the parameters

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

        add_distribution(parametername, distribution)
            Adds a parameter/distribution pair

        get_element(elementname)
            Returns the full ElementTree of the class

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

    """

    def __init__(self, number_of_tests, random_seed=None):
        """initalizes the Stochastic

        Parameters
        ----------
            number_of_tests (int): number of tests to run

            random_seed (float): the seed for the run
                Default: None

        """
        self.number_of_tests = number_of_tests
        self.random_seed = random_seed
        self.distributions = {}

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

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

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

        Returns
        -------
            Stochastic (Stochastic): a Stochastic object

        """

        if "randomSeed" in element.attrib:
            seed = element.attrib["randomSeed"]
        else:
            seed = None
        stoc = Stochastic(element.attrib["numberOfTestRuns"], seed)
        for dist_element in element.findall("StochasticDistribution"):
            name = dist_element.attrib["parameterName"]
            dist = _StochasticFactory.parse_distribution(dist_element)
            stoc.add_distribution(name, dist)
        return stoc

    def add_distribution(self, parametername, distribution):
        """adds a parameter and a related distribution to it

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

            distribution (StochasticDistribution): the distribution of that parameter

        """
        if not isinstance(distribution, _StochasticDistributionType):
            raise TypeError("distribution input is not a valid StochasticDistribution")
        self.distributions[parametername] = distribution
        return self

    def get_attributes(self):
        """returns the attributes of the Stochastic as a dict"""
        retdict = {}
        retdict["numberOfTestRuns"] = str(self.number_of_tests)
        if self.random_seed is not None:
            retdict["randomSeed"] = str(self.random_seed)

        return retdict

    def get_element(self):
        """returns the elementTree of the Stochastic"""
        element = ET.Element("Stochastic", self.get_attributes())
        if not self.distributions:
            raise NotEnoughInputArguments("No distribution has been added")
        for d in self.distributions:
            # dist = ET.SubElement(element,'stochasticDistribution',)
            dist = ET.SubElement(
                element, "StochasticDistribution", attrib={"parameterName": d}
            )
            dist.append(self.distributions[d].get_element())

        return element


class NormalDistribution(_StochasticDistributionType):
    """the NormalDistribution is a Stochastic distribution

    Parameters
    ----------
        expected_value (float): the expected value (mean) of the distribution

        variance (float): variance of the distribution

        range (Range): limit of the values (optional)
            Default: None

    Attributes
    ----------
        expected_value (float): the expected value (mean) of the distribution

        variance (float): variance of the distribution

        range (Range): limit of the values (optional)

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

        get_element(elementname)
            Returns the full ElementTree of the class

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

    """

    def __init__(self, expected_value, variance, range=None):
        """initalizes the NormalDistribution

        Parameters
        ----------
            expected_value (float): the expected value (mean) of the distribution

            variance (float): variance of the distribution

            range (Range): limit of the values (optional)
                Default: None

        """
        if range and not isinstance(range, Range):
            raise TypeError("range input is not of type Range")
        self.expected_value = expected_value
        self.variance = variance
        self.range = range

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

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

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

        Returns
        -------
            nd (NormalDistribution): a NormalDistribution object

        """
        if element.find("Range") is not None:
            range = Range.parse(element.find("Range"))
        else:
            range = None
        nd = NormalDistribution(
            element.attrib["expectedValue"], element.attrib["variance"], range
        )
        return nd

    def get_attributes(self):
        """returns the attributes of the NormalDistribution as a dict"""
        retdict = {
            "expectedValue": str(self.expected_value),
            "variance": str(self.variance),
        }
        return retdict

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


class UniformDistribution(_StochasticDistributionType):
    """the UniformDistribution is a Stochastic distribution

    Parameters
    ----------
        range (Range): limit of the values

    Attributes
    ----------
        range (Range): limit of the values

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

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    def __init__(self, range):
        """initalizes the UniformDistribution

        Parameters
        ----------
            range (Range): limit of the values (optional)


        """
        if not isinstance(range, Range):
            raise TypeError("range input is not of type Range")
        self.range = range

    def __eq__(self, other):
        if isinstance(other, UniformDistribution):
            if self.range == other.range:
                return True
        return False

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

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

        Returns
        -------
            ud (UniformDistribution): a UniformDistribution object

        """

        return UniformDistribution(Range.parse(element.find("Range")))

    def get_element(self):
        """returns the elementTree of the UniformDistribution"""
        element = ET.Element("UniformDistribution")
        element.append(self.range.get_element())
        return element


class PoissonDistribution(_StochasticDistributionType):
    """the PoissonDistribution is a Stochastic distribution

    Parameters
    ----------
        expected_value (float): the expected value of the distribution

        range (Range): limit of the values (optional)
            Default: None

    Attributes
    ----------
        expected_value (float): the expected value of the distribution

        range (Range): limit of the values (optional)

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

        get_element(elementname)
            Returns the full ElementTree of the class

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

    """

    def __init__(self, expected_value, range=None):
        """initalizes the PoissonDistribution

        Parameters
        ----------
            expected_value (float): the expected value of the distribution

            range (Range): limit of the values (optional)
                Default: None

        """
        if range and not isinstance(range, Range):
            raise TypeError("range input is not of type Range")
        self.expected_value = expected_value
        self.range = range

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

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

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

        Returns
        -------
            pd (PoissonDistribution): a PoissonDistribution object

        """
        if element.find("Range") is not None:
            range = Range.parse(element.find("Range"))
        else:
            range = None
        pd = PoissonDistribution(element.attrib["expectedValue"], range)
        return pd

    def get_attributes(self):
        """returns the attributes of the PoissonDistribution as a dict"""
        retdict = {"expectedValue": str(self.expected_value)}
        return retdict

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


class Histogram(_StochasticDistributionType):
    """the Histogram is a Stochastic distribution

    Parameters
    ----------

    Attributes
    ----------
        bins (list of _HistogramBin): the bins defining the histogram

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

        get_element(elementname)
            Returns the full ElementTree of the class

        add_bin(weight,range)
            adds a weight and a range to a bin

    """

    def __init__(self):
        """initalizes the Histogram"""
        self.bins = []

    def __eq__(self, other):
        if isinstance(other, Histogram):
            if self.bins == other.bins:
                return True
        return False

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

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

        Returns
        -------
            histogram (Histogram): a Histogram object

        """
        hist = Histogram()
        for h_element in element.findall("Bin"):
            hist.bins.append(_HistogramBin.parse(h_element))
        return hist

    def add_bin(self, weight, range):
        """returns the attributes of the Histogram as a dict

        Parameters
        ----------
            weight (float): the weight of the bin

            range (Range): the range of the bin

        """
        self.bins.append(_HistogramBin(weight, range))
        return self

    def get_element(self):
        """returns the elementTree of the Histogram"""
        element = ET.Element("Histogram")
        if not self.bins:
            raise NotEnoughInputArguments(
                "The Histogram has no bins, please use add_bin to add atleast one."
            )
        for bin in self.bins:
            element.append(bin.get_element())
        return element


class ProbabilityDistributionSet(_StochasticDistributionType):
    """the ProbabilityDistributionSet is a Stochastic distribution

    Parameters
    ----------

    Attributes
    ----------
        sets (list of _ProbabilityDistributionSetElement): the sets defining the ProbabilityDistributionSet

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

        get_element(elementname)
            Returns the full ElementTree of the class

        add_set(value, weight)
            adds a weight and a range to a bin

    """

    def __init__(self):
        """initalizes the ProbabilityDistributionSet"""
        self.sets = []

    def __eq__(self, other):
        if isinstance(other, ProbabilityDistributionSet):
            if self.sets == other.sets:
                return True
        return False

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

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

        Returns
        -------
            pds (ProbabilityDistributionSet): a ProbabilityDistributionSet object

        """
        pds = ProbabilityDistributionSet()
        for e in element.findall("Element"):
            pds.sets.append(_ProbabilityDistributionSetElement.parse(e))
        return pds

    def add_set(self, value, weight):
        """adds a set element to the ProbabilityDistributionSet

        Parameters
        ----------
            value (string): possible value

            weight (float): weight of the value

        """
        self.sets.append(_ProbabilityDistributionSetElement(value, weight))
        return self

    def get_element(self):
        """returns the elementTree of the ProbabilityDistributionSet"""
        element = ET.Element("ProbabilityDistributionSet")
        if not self.sets:
            raise NotEnoughInputArguments(
                "No sets were added to the ProbabilityDistributionSet, please use add_set"
            )
        for bin in self.sets:
            element.append(bin.get_element())
        return element


### Deterministic


class ParameterValueSet(VersionBase):
    """Creates the ParameterValueSet used by the DeterministicMultiParameterDistribution

    Parameters
    ----------


    Attributes
    ----------

        assignments (list of ParameterAssignment): the the assignments for the ValueSet

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

        add_parameter(parameterref, value)
            Adds a parameter value pair

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    def __init__(self):
        """initalizes the ParameterValueSet"""

        self.sets = []

    def __eq__(self, other):
        if isinstance(other, ParameterValueSet):
            if self.sets == other.sets:
                return True
        return False

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

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

        Returns
        -------
            parameter_value_set (ParameterValueSet): a ParameterValueSet object

        """
        parameter_value_set = ParameterValueSet()
        for pa in element.findall("ParameterAssignment"):
            parameter_value_set.sets.append(ParameterAssignment.parse(pa))

        return parameter_value_set

    def add_parameter(self, parameterref, value):
        """adds a parameter and a value

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

            value (str): value of the parameters

        """

        self.sets.append(ParameterAssignment(parameterref, value))
        return self

    def get_element(self):
        """returns the elementTree of the ParameterValueSet"""
        element = ET.Element("ParameterValueSet")

        if not self.sets:
            raise NotEnoughInputArguments("No sets has been added")
        for s in self.sets:
            element.append(s.get_element())

        return element


class DeterministicMultiParameterDistribution(VersionBase):
    """Creates the DeterministicMultiParameterDistribution type of parameter distributions

    Parameters
    ----------


    Attributes
    ----------

        distributions (list of ParameterValueSet): the distributions for the parameters

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

        add_value_set(parameter_value_set)
            Adds a parameter value set

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    def __init__(self):
        """initalizes the DeterministicMultiParameterDistribution"""

        self.sets = []

    def __eq__(self, other):
        if isinstance(other, DeterministicMultiParameterDistribution):
            if self.sets == other.sets:
                return True
        return False

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

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

        Returns
        -------
            distribution (DeterministicMultiParameterDistribution): a DeterministicMultiParameterDistribution object

        """
        dist = DeterministicMultiParameterDistribution()
        for h_element in element.findall("ValueSetDistribution/ParameterValueSet"):
            dist.sets.append(ParameterValueSet.parse(h_element))
        return dist

    def add_value_set(self, parameter_value_set):
        """adds a parameter and a related distribution to it

        Parameters
        ----------
            parameter_value_set (ParameterValueSet): a set of parameters

        """
        if not isinstance(parameter_value_set, ParameterValueSet):
            raise TypeError("distribution input is not of type ParameterValueSet")
        self.sets.append(parameter_value_set)
        return self

    def get_element(self):
        """returns the elementTree of the DeterministicMultiParameterDistribution"""
        element = ET.Element("DeterministicMultiParameterDistribution")
        value_set_element = ET.SubElement(element, "ValueSetDistribution")
        if not self.sets:
            raise NotEnoughInputArguments("No sets has been added")
        for d in self.sets:
            value_set_element.append(d.get_element())

        return element


class DistributionRange(VersionBase):
    """Creates the DistributionRange used to define a Single parameter distribution

    Parameters
    ----------
        step_width (float): step size of the distribution

        range (Range): the range of the parameter

    Attributes
    ----------

        step_width (float): step size of the distribution

        range (Range): the range of the parameter


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

        get_element(elementname)
            Returns the full ElementTree of the class

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

    """

    def __init__(self, step_width, range):
        """initalizes the DistributionRange

        Parameters
        ----------
            step_width (float): step size of the distribution

            range (Range): the range of the parameter

        """

        self.step_width = step_width
        if not isinstance(range, Range):
            raise TypeError("range is not of type Range.")
        self.range = range

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

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

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

        Returns
        -------
            distribution_range (DistributionRange): a DistributionRange object

        """

        distribution_range = DistributionRange(
            element.attrib["stepWidth"], Range.parse(element.find("Range"))
        )
        return distribution_range

    def get_attributes(self):
        """returns the attributes of the DistributionRange as a dict"""
        retdict = {"stepWidth": str(self.step_width)}
        return retdict

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

        return element


class DistributionSet(VersionBase):
    """Creates the DistributionSet used to define a Single parameter distribution

    Parameters
    ----------

    Attributes
    ----------

        value_elements (list of str double): a list of all values

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

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    def __init__(self):
        """initalizes the DistributionSet"""
        self.value_elements = []

    def __eq__(self, other):
        if isinstance(other, DistributionSet):
            if self.value_elements == other.value_elements:
                return True
        return False

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

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

        Returns
        -------
            dist (DistributionSet): a DistributionSet object

        """
        dist = DistributionSet()
        for v in element.findall("Element"):
            dist.add_value(v.attrib["value"])
        return dist

    def add_value(self, value):
        """adds a value to the DistirbutionSet

        Parameters
        ----------
            value (str): the value to be added to the distribution
        """
        self.value_elements.append(value)
        return self

    def get_element(self):
        """returns the elementTree of the DistributionSet"""
        element = ET.Element("DistributionSet")
        if not self.value_elements:
            raise NotEnoughInputArguments(
                "No values has been added to the DistributionSet"
            )
        for value in self.value_elements:
            ET.SubElement(element, "Element", attrib={"value": value})

        return element


class Deterministic(VersionBase):
    """Creates the Deterministic type of parameter distributions

    Parameters
    ----------


    Attributes
    ----------

        multi_distributions (list of DeterministicMultiParameterDistribution): multi parameter distributions

        single_distributions (dict of DistributionSet/DistributionRange): single parameter distribution

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

        add_multi_distribution(distribution)
            Adds a DeterministicMultiParameterDistribution

        add_single_distribution(parametername,distribution)
            adds a DeterministicSingleParameterDistribution

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    def __init__(self):
        """initalizes the Deterministic"""

        self.multi_distributions = []
        self.single_distributions = {}

    def __eq__(self, other):
        if isinstance(other, Deterministic):
            if (
                self.multi_distributions == other.multi_distributions
                and self.single_distributions == other.single_distributions
            ):
                return True
        return False

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

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

        Returns
        -------
            deterministic (Deterministic): a Deterministic object

        """
        deterministic = Deterministic()
        for single_dist in element.findall("DeterministicSingleParameterDistribution"):
            param_name = single_dist.attrib["parameterName"]
            dist = _DeterministicFactory.parse_distribution(single_dist)
            deterministic.add_single_distribution(param_name, dist)
        for multi_dist in element.findall("DeterministicMultiParameterDistribution"):
            deterministic.add_multi_distribution(
                DeterministicMultiParameterDistribution.parse(multi_dist)
            )

        return deterministic

    def add_multi_distribution(self, distribution):
        """adds a DeterministicMultiParameterDistribution

        Parameters
        ----------
            distribution (DeterministicMultiParameterDistribution): the distribution of that parameter

        """
        if not isinstance(distribution, DeterministicMultiParameterDistribution):
            raise TypeError(
                "distribution input is not of type DeterministicMultiParameterDistribution"
            )
        self.multi_distributions.append(distribution)
        return self

    def add_single_distribution(self, parametername, distribution):
        """adds a parameter and a related distribution to it

        Parameters
        ----------
            parametername (str): reference to the parameter

            distribution (DistributionSet or DistributionRange): the distribution of that parameter

        """
        if not (
            isinstance(distribution, DistributionSet)
            or isinstance(distribution, DistributionRange)
        ):
            raise TypeError(
                "distribution input is not of type DeterministicMultiParameterDistribution"
            )
        self.single_distributions[parametername] = distribution
        return self

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

        element = ET.Element("Deterministic")
        for md in self.multi_distributions:
            element.append(md.get_element())
        for d in self.single_distributions:
            dist = ET.SubElement(
                element,
                "DeterministicSingleParameterDistribution",
                attrib={"parameterName": d},
            )
            dist.append(self.single_distributions[d].get_element())

        return element


## wrapper


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

    Parameters
    ----------
        number_of_tests (int): number of tests to run

        random_seed (float): the seed for the run
            Default: None

    Attributes
    ----------
        number_of_tests (int): number of tests to run

        random_seed (float): the seed for the run

        distributions (dict of *StochasticDistribution): the distributions for the parameters

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

        write_xml(filename)
            write a open scenario xml

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    _XMLNS = XMLNS
    _XSI = XSI

    def __init__(
        self,
        description,
        author,
        scenario_file,
        parameter_distribution,
        osc_minor_version=_MINOR_VERSION,
        header_properties=None,
        license=None,
    ):
        """initalizes the ParameterValueDistribution

        Parameters
        ----------
            description (str): a description of the parameter set

            author (str): the author of the file

            scenario_file (str): path to the scenario that the parameter distribution should set

            parameter_distribution (Stochastic or Deterministic): the parameter distribution

            osc_minor_version (int): the osi version wanted (Note: only available from OpenSCENARIO V1.1.0)

            header_properties (Properties): properties that can be added to the header
                Default: None

            licence (License): optional license to the file header
                Default: None
        """
        self.header = FileHeader(
            author,
            description,
            revMinor=osc_minor_version,
            properties=header_properties,
        )
        if not isinstance(parameter_distribution, Stochastic) and not isinstance(
            parameter_distribution, Deterministic
        ):
            raise TypeError(
                type(parameter_distribution)
                + "is not of type Stochastic or Deterministic"
            )
        self.scenario_file = scenario_file
        self.parameter_distribution = parameter_distribution

    def __eq__(self, other):
        if isinstance(other, ParameterValueDistribution):
            if (
                self.header == other.header
                and self.scenario_file == other.scenario_file
                and self.parameter_distribution == other.parameter_distribution
            ):
                return True
        return False

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

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

        Returns
        -------
            paramvaluedist (ParameterValueDistribution): a ParameterValueDistribution object

        """

        pvd_element = element.find("ParameterValueDistribution")
        if pvd_element.find("Stochastic") is not None:
            dist = Stochastic.parse(pvd_element.find("Stochastic"))
        elif pvd_element.find("Deterministic") is not None:
            dist = Deterministic.parse(pvd_element.find("Deterministic"))
        else:
            raise NotAValidElement(
                "ParameterValueDistribution is missing a distribution"
            )

        pvd = ParameterValueDistribution(
            "", "", pvd_element.find("ScenarioFile").attrib["filepath"], dist
        )
        pvd.header = FileHeader.parse(element.find("FileHeader"))
        return pvd

    def get_element(self):
        """returns the elementTree of the ParameterValueDistribution"""
        if self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "Everything related to ParameterValueDistribution was introduced in OpenSCENARIO V1.1"
            )
        element = ET.Element(
            "OpenSCENARIO",
            attrib={
                "xmlns:xsi": self._XMLNS,
                "xsi:noNamespaceSchemaLocation": self._XSI,
            },
        )
        element.append(self.header.get_element())
        parameterdist = ET.SubElement(element, "ParameterValueDistribution")
        ET.SubElement(
            parameterdist, "ScenarioFile", attrib={"filepath": self.scenario_file}
        )

        parameterdist.append(self.parameter_distribution.get_element())

        return element

    def write_xml(self, filename, prettyprint=True, encoding="utf-8"):
        """write_xml writes the parametervaluedistribution xml file

        Parameters
        ----------
            filename (str): path and filename of the wanted xml file

            prettyprint (bool): pretty print or ugly print?
                Default: True

        """
        printToFile(self.get_element(), filename, prettyprint, encoding)

Classes

class Deterministic

Creates the Deterministic type of parameter distributions

Parameters

Attributes

multi_distributions (list of DeterministicMultiParameterDistribution): multi parameter distributions

single_distributions (dict of DistributionSet/DistributionRange): single parameter distribution

Methods

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

add_multi_distribution(distribution)
    Adds a DeterministicMultiParameterDistribution

add_single_distribution(parametername,distribution)
    adds a DeterministicSingleParameterDistribution

get_element(elementname)
    Returns the full ElementTree of the class

initalizes the Deterministic

Expand source code
class Deterministic(VersionBase):
    """Creates the Deterministic type of parameter distributions

    Parameters
    ----------


    Attributes
    ----------

        multi_distributions (list of DeterministicMultiParameterDistribution): multi parameter distributions

        single_distributions (dict of DistributionSet/DistributionRange): single parameter distribution

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

        add_multi_distribution(distribution)
            Adds a DeterministicMultiParameterDistribution

        add_single_distribution(parametername,distribution)
            adds a DeterministicSingleParameterDistribution

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    def __init__(self):
        """initalizes the Deterministic"""

        self.multi_distributions = []
        self.single_distributions = {}

    def __eq__(self, other):
        if isinstance(other, Deterministic):
            if (
                self.multi_distributions == other.multi_distributions
                and self.single_distributions == other.single_distributions
            ):
                return True
        return False

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

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

        Returns
        -------
            deterministic (Deterministic): a Deterministic object

        """
        deterministic = Deterministic()
        for single_dist in element.findall("DeterministicSingleParameterDistribution"):
            param_name = single_dist.attrib["parameterName"]
            dist = _DeterministicFactory.parse_distribution(single_dist)
            deterministic.add_single_distribution(param_name, dist)
        for multi_dist in element.findall("DeterministicMultiParameterDistribution"):
            deterministic.add_multi_distribution(
                DeterministicMultiParameterDistribution.parse(multi_dist)
            )

        return deterministic

    def add_multi_distribution(self, distribution):
        """adds a DeterministicMultiParameterDistribution

        Parameters
        ----------
            distribution (DeterministicMultiParameterDistribution): the distribution of that parameter

        """
        if not isinstance(distribution, DeterministicMultiParameterDistribution):
            raise TypeError(
                "distribution input is not of type DeterministicMultiParameterDistribution"
            )
        self.multi_distributions.append(distribution)
        return self

    def add_single_distribution(self, parametername, distribution):
        """adds a parameter and a related distribution to it

        Parameters
        ----------
            parametername (str): reference to the parameter

            distribution (DistributionSet or DistributionRange): the distribution of that parameter

        """
        if not (
            isinstance(distribution, DistributionSet)
            or isinstance(distribution, DistributionRange)
        ):
            raise TypeError(
                "distribution input is not of type DeterministicMultiParameterDistribution"
            )
        self.single_distributions[parametername] = distribution
        return self

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

        element = ET.Element("Deterministic")
        for md in self.multi_distributions:
            element.append(md.get_element())
        for d in self.single_distributions:
            dist = ET.SubElement(
                element,
                "DeterministicSingleParameterDistribution",
                attrib={"parameterName": d},
            )
            dist.append(self.single_distributions[d].get_element())

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of Deterministic

Parameters

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

Returns

deterministic (Deterministic): a Deterministic object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Deterministic

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

    Returns
    -------
        deterministic (Deterministic): a Deterministic object

    """
    deterministic = Deterministic()
    for single_dist in element.findall("DeterministicSingleParameterDistribution"):
        param_name = single_dist.attrib["parameterName"]
        dist = _DeterministicFactory.parse_distribution(single_dist)
        deterministic.add_single_distribution(param_name, dist)
    for multi_dist in element.findall("DeterministicMultiParameterDistribution"):
        deterministic.add_multi_distribution(
            DeterministicMultiParameterDistribution.parse(multi_dist)
        )

    return deterministic

Methods

def add_multi_distribution(self, distribution)

adds a DeterministicMultiParameterDistribution

Parameters

distribution (DeterministicMultiParameterDistribution): the distribution of that parameter
Expand source code
def add_multi_distribution(self, distribution):
    """adds a DeterministicMultiParameterDistribution

    Parameters
    ----------
        distribution (DeterministicMultiParameterDistribution): the distribution of that parameter

    """
    if not isinstance(distribution, DeterministicMultiParameterDistribution):
        raise TypeError(
            "distribution input is not of type DeterministicMultiParameterDistribution"
        )
    self.multi_distributions.append(distribution)
    return self
def add_single_distribution(self, parametername, distribution)

adds a parameter and a related distribution to it

Parameters

parametername (str): reference to the parameter

distribution (DistributionSet or DistributionRange): the distribution of that parameter
Expand source code
def add_single_distribution(self, parametername, distribution):
    """adds a parameter and a related distribution to it

    Parameters
    ----------
        parametername (str): reference to the parameter

        distribution (DistributionSet or DistributionRange): the distribution of that parameter

    """
    if not (
        isinstance(distribution, DistributionSet)
        or isinstance(distribution, DistributionRange)
    ):
        raise TypeError(
            "distribution input is not of type DeterministicMultiParameterDistribution"
        )
    self.single_distributions[parametername] = distribution
    return self
def get_element(self)

returns the elementTree of the Deterministic

Expand source code
def get_element(self):
    """returns the elementTree of the Deterministic"""

    element = ET.Element("Deterministic")
    for md in self.multi_distributions:
        element.append(md.get_element())
    for d in self.single_distributions:
        dist = ET.SubElement(
            element,
            "DeterministicSingleParameterDistribution",
            attrib={"parameterName": d},
        )
        dist.append(self.single_distributions[d].get_element())

    return element
class DeterministicMultiParameterDistribution

Creates the DeterministicMultiParameterDistribution type of parameter distributions

Parameters

Attributes

distributions (list of ParameterValueSet): the distributions for the parameters

Methods

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

add_value_set(parameter_value_set)
    Adds a parameter value set

get_element(elementname)
    Returns the full ElementTree of the class

initalizes the DeterministicMultiParameterDistribution

Expand source code
class DeterministicMultiParameterDistribution(VersionBase):
    """Creates the DeterministicMultiParameterDistribution type of parameter distributions

    Parameters
    ----------


    Attributes
    ----------

        distributions (list of ParameterValueSet): the distributions for the parameters

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

        add_value_set(parameter_value_set)
            Adds a parameter value set

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    def __init__(self):
        """initalizes the DeterministicMultiParameterDistribution"""

        self.sets = []

    def __eq__(self, other):
        if isinstance(other, DeterministicMultiParameterDistribution):
            if self.sets == other.sets:
                return True
        return False

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

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

        Returns
        -------
            distribution (DeterministicMultiParameterDistribution): a DeterministicMultiParameterDistribution object

        """
        dist = DeterministicMultiParameterDistribution()
        for h_element in element.findall("ValueSetDistribution/ParameterValueSet"):
            dist.sets.append(ParameterValueSet.parse(h_element))
        return dist

    def add_value_set(self, parameter_value_set):
        """adds a parameter and a related distribution to it

        Parameters
        ----------
            parameter_value_set (ParameterValueSet): a set of parameters

        """
        if not isinstance(parameter_value_set, ParameterValueSet):
            raise TypeError("distribution input is not of type ParameterValueSet")
        self.sets.append(parameter_value_set)
        return self

    def get_element(self):
        """returns the elementTree of the DeterministicMultiParameterDistribution"""
        element = ET.Element("DeterministicMultiParameterDistribution")
        value_set_element = ET.SubElement(element, "ValueSetDistribution")
        if not self.sets:
            raise NotEnoughInputArguments("No sets has been added")
        for d in self.sets:
            value_set_element.append(d.get_element())

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of DeterministicMultiParameterDistribution

Parameters

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

Returns

distribution (DeterministicMultiParameterDistribution): a DeterministicMultiParameterDistribution object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of DeterministicMultiParameterDistribution

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

    Returns
    -------
        distribution (DeterministicMultiParameterDistribution): a DeterministicMultiParameterDistribution object

    """
    dist = DeterministicMultiParameterDistribution()
    for h_element in element.findall("ValueSetDistribution/ParameterValueSet"):
        dist.sets.append(ParameterValueSet.parse(h_element))
    return dist

Methods

def add_value_set(self, parameter_value_set)

adds a parameter and a related distribution to it

Parameters

parameter_value_set (ParameterValueSet): a set of parameters
Expand source code
def add_value_set(self, parameter_value_set):
    """adds a parameter and a related distribution to it

    Parameters
    ----------
        parameter_value_set (ParameterValueSet): a set of parameters

    """
    if not isinstance(parameter_value_set, ParameterValueSet):
        raise TypeError("distribution input is not of type ParameterValueSet")
    self.sets.append(parameter_value_set)
    return self
def get_element(self)

returns the elementTree of the DeterministicMultiParameterDistribution

Expand source code
def get_element(self):
    """returns the elementTree of the DeterministicMultiParameterDistribution"""
    element = ET.Element("DeterministicMultiParameterDistribution")
    value_set_element = ET.SubElement(element, "ValueSetDistribution")
    if not self.sets:
        raise NotEnoughInputArguments("No sets has been added")
    for d in self.sets:
        value_set_element.append(d.get_element())

    return element
class DistributionRange (step_width, range)

Creates the DistributionRange used to define a Single parameter distribution

Parameters

step_width (float): step size of the distribution

range (Range): the range of the parameter

Attributes

step_width (float): step size of the distribution

range (Range): the range of the parameter

Methods

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

get_element(elementname)
    Returns the full ElementTree of the class

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

initalizes the DistributionRange

Parameters

step_width (float): step size of the distribution

range (Range): the range of the parameter
Expand source code
class DistributionRange(VersionBase):
    """Creates the DistributionRange used to define a Single parameter distribution

    Parameters
    ----------
        step_width (float): step size of the distribution

        range (Range): the range of the parameter

    Attributes
    ----------

        step_width (float): step size of the distribution

        range (Range): the range of the parameter


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

        get_element(elementname)
            Returns the full ElementTree of the class

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

    """

    def __init__(self, step_width, range):
        """initalizes the DistributionRange

        Parameters
        ----------
            step_width (float): step size of the distribution

            range (Range): the range of the parameter

        """

        self.step_width = step_width
        if not isinstance(range, Range):
            raise TypeError("range is not of type Range.")
        self.range = range

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

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

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

        Returns
        -------
            distribution_range (DistributionRange): a DistributionRange object

        """

        distribution_range = DistributionRange(
            element.attrib["stepWidth"], Range.parse(element.find("Range"))
        )
        return distribution_range

    def get_attributes(self):
        """returns the attributes of the DistributionRange as a dict"""
        retdict = {"stepWidth": str(self.step_width)}
        return retdict

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

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of DistributionRange

Parameters

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

Returns

distribution_range (DistributionRange): a DistributionRange object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of DistributionRange

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

    Returns
    -------
        distribution_range (DistributionRange): a DistributionRange object

    """

    distribution_range = DistributionRange(
        element.attrib["stepWidth"], Range.parse(element.find("Range"))
    )
    return distribution_range

Methods

def get_attributes(self)

returns the attributes of the DistributionRange as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the DistributionRange as a dict"""
    retdict = {"stepWidth": str(self.step_width)}
    return retdict
def get_element(self)

returns the elementTree of the DistributionRange

Expand source code
def get_element(self):
    """returns the elementTree of the DistributionRange"""
    element = ET.Element("DistributionRange", attrib=self.get_attributes())
    element.append(self.range.get_element())

    return element
class DistributionSet

Creates the DistributionSet used to define a Single parameter distribution

Parameters

Attributes

value_elements (list of str double): a list of all values

Methods

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

get_element(elementname)
    Returns the full ElementTree of the class

initalizes the DistributionSet

Expand source code
class DistributionSet(VersionBase):
    """Creates the DistributionSet used to define a Single parameter distribution

    Parameters
    ----------

    Attributes
    ----------

        value_elements (list of str double): a list of all values

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

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    def __init__(self):
        """initalizes the DistributionSet"""
        self.value_elements = []

    def __eq__(self, other):
        if isinstance(other, DistributionSet):
            if self.value_elements == other.value_elements:
                return True
        return False

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

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

        Returns
        -------
            dist (DistributionSet): a DistributionSet object

        """
        dist = DistributionSet()
        for v in element.findall("Element"):
            dist.add_value(v.attrib["value"])
        return dist

    def add_value(self, value):
        """adds a value to the DistirbutionSet

        Parameters
        ----------
            value (str): the value to be added to the distribution
        """
        self.value_elements.append(value)
        return self

    def get_element(self):
        """returns the elementTree of the DistributionSet"""
        element = ET.Element("DistributionSet")
        if not self.value_elements:
            raise NotEnoughInputArguments(
                "No values has been added to the DistributionSet"
            )
        for value in self.value_elements:
            ET.SubElement(element, "Element", attrib={"value": value})

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of DistributionSet

Parameters

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

Returns

dist (DistributionSet): a DistributionSet object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of DistributionSet

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

    Returns
    -------
        dist (DistributionSet): a DistributionSet object

    """
    dist = DistributionSet()
    for v in element.findall("Element"):
        dist.add_value(v.attrib["value"])
    return dist

Methods

def add_value(self, value)

adds a value to the DistirbutionSet

Parameters

value (str): the value to be added to the distribution
Expand source code
def add_value(self, value):
    """adds a value to the DistirbutionSet

    Parameters
    ----------
        value (str): the value to be added to the distribution
    """
    self.value_elements.append(value)
    return self
def get_element(self)

returns the elementTree of the DistributionSet

Expand source code
def get_element(self):
    """returns the elementTree of the DistributionSet"""
    element = ET.Element("DistributionSet")
    if not self.value_elements:
        raise NotEnoughInputArguments(
            "No values has been added to the DistributionSet"
        )
    for value in self.value_elements:
        ET.SubElement(element, "Element", attrib={"value": value})

    return element
class Histogram

the Histogram is a Stochastic distribution

Parameters

Attributes

bins (list of _HistogramBin): the bins defining the histogram

Methods

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

get_element(elementname)
    Returns the full ElementTree of the class

add_bin(weight,range)
    adds a weight and a range to a bin

initalizes the Histogram

Expand source code
class Histogram(_StochasticDistributionType):
    """the Histogram is a Stochastic distribution

    Parameters
    ----------

    Attributes
    ----------
        bins (list of _HistogramBin): the bins defining the histogram

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

        get_element(elementname)
            Returns the full ElementTree of the class

        add_bin(weight,range)
            adds a weight and a range to a bin

    """

    def __init__(self):
        """initalizes the Histogram"""
        self.bins = []

    def __eq__(self, other):
        if isinstance(other, Histogram):
            if self.bins == other.bins:
                return True
        return False

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

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

        Returns
        -------
            histogram (Histogram): a Histogram object

        """
        hist = Histogram()
        for h_element in element.findall("Bin"):
            hist.bins.append(_HistogramBin.parse(h_element))
        return hist

    def add_bin(self, weight, range):
        """returns the attributes of the Histogram as a dict

        Parameters
        ----------
            weight (float): the weight of the bin

            range (Range): the range of the bin

        """
        self.bins.append(_HistogramBin(weight, range))
        return self

    def get_element(self):
        """returns the elementTree of the Histogram"""
        element = ET.Element("Histogram")
        if not self.bins:
            raise NotEnoughInputArguments(
                "The Histogram has no bins, please use add_bin to add atleast one."
            )
        for bin in self.bins:
            element.append(bin.get_element())
        return element

Ancestors

  • scenariogeneration.xosc.utils._StochasticDistributionType
  • VersionBase

Static methods

def parse(element)

Parses the xml element of Histogram

Parameters

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

Returns

histogram (Histogram): a Histogram object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Histogram

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

    Returns
    -------
        histogram (Histogram): a Histogram object

    """
    hist = Histogram()
    for h_element in element.findall("Bin"):
        hist.bins.append(_HistogramBin.parse(h_element))
    return hist

Methods

def add_bin(self, weight, range)

returns the attributes of the Histogram as a dict

Parameters

weight (float): the weight of the bin

range (Range): the range of the bin
Expand source code
def add_bin(self, weight, range):
    """returns the attributes of the Histogram as a dict

    Parameters
    ----------
        weight (float): the weight of the bin

        range (Range): the range of the bin

    """
    self.bins.append(_HistogramBin(weight, range))
    return self
def get_element(self)

returns the elementTree of the Histogram

Expand source code
def get_element(self):
    """returns the elementTree of the Histogram"""
    element = ET.Element("Histogram")
    if not self.bins:
        raise NotEnoughInputArguments(
            "The Histogram has no bins, please use add_bin to add atleast one."
        )
    for bin in self.bins:
        element.append(bin.get_element())
    return element
class NormalDistribution (expected_value, variance, range=None)

the NormalDistribution is a Stochastic distribution

Parameters

expected_value (float): the expected value (mean) of the distribution

variance (float): variance of the distribution

range (Range): limit of the values (optional)
    Default: None

Attributes

expected_value (float): the expected value (mean) of the distribution

variance (float): variance of the distribution

range (Range): limit of the values (optional)

Methods

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

get_element(elementname)
    Returns the full ElementTree of the class

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

initalizes the NormalDistribution

Parameters

expected_value (float): the expected value (mean) of the distribution

variance (float): variance of the distribution

range (Range): limit of the values (optional)
    Default: None
Expand source code
class NormalDistribution(_StochasticDistributionType):
    """the NormalDistribution is a Stochastic distribution

    Parameters
    ----------
        expected_value (float): the expected value (mean) of the distribution

        variance (float): variance of the distribution

        range (Range): limit of the values (optional)
            Default: None

    Attributes
    ----------
        expected_value (float): the expected value (mean) of the distribution

        variance (float): variance of the distribution

        range (Range): limit of the values (optional)

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

        get_element(elementname)
            Returns the full ElementTree of the class

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

    """

    def __init__(self, expected_value, variance, range=None):
        """initalizes the NormalDistribution

        Parameters
        ----------
            expected_value (float): the expected value (mean) of the distribution

            variance (float): variance of the distribution

            range (Range): limit of the values (optional)
                Default: None

        """
        if range and not isinstance(range, Range):
            raise TypeError("range input is not of type Range")
        self.expected_value = expected_value
        self.variance = variance
        self.range = range

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

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

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

        Returns
        -------
            nd (NormalDistribution): a NormalDistribution object

        """
        if element.find("Range") is not None:
            range = Range.parse(element.find("Range"))
        else:
            range = None
        nd = NormalDistribution(
            element.attrib["expectedValue"], element.attrib["variance"], range
        )
        return nd

    def get_attributes(self):
        """returns the attributes of the NormalDistribution as a dict"""
        retdict = {
            "expectedValue": str(self.expected_value),
            "variance": str(self.variance),
        }
        return retdict

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

Ancestors

  • scenariogeneration.xosc.utils._StochasticDistributionType
  • VersionBase

Static methods

def parse(element)

Parses the xml element of NormalDistribution

Parameters

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

Returns

nd (NormalDistribution): a NormalDistribution object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of NormalDistribution

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

    Returns
    -------
        nd (NormalDistribution): a NormalDistribution object

    """
    if element.find("Range") is not None:
        range = Range.parse(element.find("Range"))
    else:
        range = None
    nd = NormalDistribution(
        element.attrib["expectedValue"], element.attrib["variance"], range
    )
    return nd

Methods

def get_attributes(self)

returns the attributes of the NormalDistribution as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the NormalDistribution as a dict"""
    retdict = {
        "expectedValue": str(self.expected_value),
        "variance": str(self.variance),
    }
    return retdict
def get_element(self)

returns the elementTree of the NormalDistribution

Expand source code
def get_element(self):
    """returns the elementTree of the NormalDistribution"""
    element = ET.Element("NormalDistribution", self.get_attributes())
    if self.range:
        element.append(self.range.get_element())
    return element
class ParameterValueDistribution (description, author, scenario_file, parameter_distribution, osc_minor_version=2, header_properties=None, license=None)

Creates the the ParameterValueDistribution file for open scenario

Parameters

number_of_tests (int): number of tests to run

random_seed (float): the seed for the run
    Default: None

Attributes

number_of_tests (int): number of tests to run

random_seed (float): the seed for the run

distributions (dict of *StochasticDistribution): the distributions for the parameters

Methods

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

write_xml(filename)
    write a open scenario xml

get_element(elementname)
    Returns the full ElementTree of the class

initalizes the ParameterValueDistribution

Parameters

description (str): a description of the parameter set

author (str): the author of the file

scenario_file (str): path to the scenario that the parameter distribution should set

parameter_distribution (Stochastic or Deterministic): the parameter distribution

osc_minor_version (int): the osi version wanted (Note: only available from OpenSCENARIO V1.1.0)

header_properties (Properties): properties that can be added to the header
    Default: None

licence (License): optional license to the file header
    Default: None
Expand source code
class ParameterValueDistribution(VersionBase):
    """Creates the the ParameterValueDistribution file for open scenario

    Parameters
    ----------
        number_of_tests (int): number of tests to run

        random_seed (float): the seed for the run
            Default: None

    Attributes
    ----------
        number_of_tests (int): number of tests to run

        random_seed (float): the seed for the run

        distributions (dict of *StochasticDistribution): the distributions for the parameters

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

        write_xml(filename)
            write a open scenario xml

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    _XMLNS = XMLNS
    _XSI = XSI

    def __init__(
        self,
        description,
        author,
        scenario_file,
        parameter_distribution,
        osc_minor_version=_MINOR_VERSION,
        header_properties=None,
        license=None,
    ):
        """initalizes the ParameterValueDistribution

        Parameters
        ----------
            description (str): a description of the parameter set

            author (str): the author of the file

            scenario_file (str): path to the scenario that the parameter distribution should set

            parameter_distribution (Stochastic or Deterministic): the parameter distribution

            osc_minor_version (int): the osi version wanted (Note: only available from OpenSCENARIO V1.1.0)

            header_properties (Properties): properties that can be added to the header
                Default: None

            licence (License): optional license to the file header
                Default: None
        """
        self.header = FileHeader(
            author,
            description,
            revMinor=osc_minor_version,
            properties=header_properties,
        )
        if not isinstance(parameter_distribution, Stochastic) and not isinstance(
            parameter_distribution, Deterministic
        ):
            raise TypeError(
                type(parameter_distribution)
                + "is not of type Stochastic or Deterministic"
            )
        self.scenario_file = scenario_file
        self.parameter_distribution = parameter_distribution

    def __eq__(self, other):
        if isinstance(other, ParameterValueDistribution):
            if (
                self.header == other.header
                and self.scenario_file == other.scenario_file
                and self.parameter_distribution == other.parameter_distribution
            ):
                return True
        return False

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

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

        Returns
        -------
            paramvaluedist (ParameterValueDistribution): a ParameterValueDistribution object

        """

        pvd_element = element.find("ParameterValueDistribution")
        if pvd_element.find("Stochastic") is not None:
            dist = Stochastic.parse(pvd_element.find("Stochastic"))
        elif pvd_element.find("Deterministic") is not None:
            dist = Deterministic.parse(pvd_element.find("Deterministic"))
        else:
            raise NotAValidElement(
                "ParameterValueDistribution is missing a distribution"
            )

        pvd = ParameterValueDistribution(
            "", "", pvd_element.find("ScenarioFile").attrib["filepath"], dist
        )
        pvd.header = FileHeader.parse(element.find("FileHeader"))
        return pvd

    def get_element(self):
        """returns the elementTree of the ParameterValueDistribution"""
        if self.isVersion(minor=0):
            raise OpenSCENARIOVersionError(
                "Everything related to ParameterValueDistribution was introduced in OpenSCENARIO V1.1"
            )
        element = ET.Element(
            "OpenSCENARIO",
            attrib={
                "xmlns:xsi": self._XMLNS,
                "xsi:noNamespaceSchemaLocation": self._XSI,
            },
        )
        element.append(self.header.get_element())
        parameterdist = ET.SubElement(element, "ParameterValueDistribution")
        ET.SubElement(
            parameterdist, "ScenarioFile", attrib={"filepath": self.scenario_file}
        )

        parameterdist.append(self.parameter_distribution.get_element())

        return element

    def write_xml(self, filename, prettyprint=True, encoding="utf-8"):
        """write_xml writes the parametervaluedistribution xml file

        Parameters
        ----------
            filename (str): path and filename of the wanted xml file

            prettyprint (bool): pretty print or ugly print?
                Default: True

        """
        printToFile(self.get_element(), filename, prettyprint, encoding)

Ancestors

Static methods

def parse(element)

Parses the xml element of ParameterValueDistribution

Parameters

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

Returns

paramvaluedist (ParameterValueDistribution): a ParameterValueDistribution object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of ParameterValueDistribution

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

    Returns
    -------
        paramvaluedist (ParameterValueDistribution): a ParameterValueDistribution object

    """

    pvd_element = element.find("ParameterValueDistribution")
    if pvd_element.find("Stochastic") is not None:
        dist = Stochastic.parse(pvd_element.find("Stochastic"))
    elif pvd_element.find("Deterministic") is not None:
        dist = Deterministic.parse(pvd_element.find("Deterministic"))
    else:
        raise NotAValidElement(
            "ParameterValueDistribution is missing a distribution"
        )

    pvd = ParameterValueDistribution(
        "", "", pvd_element.find("ScenarioFile").attrib["filepath"], dist
    )
    pvd.header = FileHeader.parse(element.find("FileHeader"))
    return pvd

Methods

def get_element(self)

returns the elementTree of the ParameterValueDistribution

Expand source code
def get_element(self):
    """returns the elementTree of the ParameterValueDistribution"""
    if self.isVersion(minor=0):
        raise OpenSCENARIOVersionError(
            "Everything related to ParameterValueDistribution was introduced in OpenSCENARIO V1.1"
        )
    element = ET.Element(
        "OpenSCENARIO",
        attrib={
            "xmlns:xsi": self._XMLNS,
            "xsi:noNamespaceSchemaLocation": self._XSI,
        },
    )
    element.append(self.header.get_element())
    parameterdist = ET.SubElement(element, "ParameterValueDistribution")
    ET.SubElement(
        parameterdist, "ScenarioFile", attrib={"filepath": self.scenario_file}
    )

    parameterdist.append(self.parameter_distribution.get_element())

    return element
def write_xml(self, filename, prettyprint=True, encoding='utf-8')

write_xml writes the parametervaluedistribution xml file

Parameters

filename (str): path and filename of the wanted xml file

prettyprint (bool): pretty print or ugly print?
    Default: True
Expand source code
def write_xml(self, filename, prettyprint=True, encoding="utf-8"):
    """write_xml writes the parametervaluedistribution xml file

    Parameters
    ----------
        filename (str): path and filename of the wanted xml file

        prettyprint (bool): pretty print or ugly print?
            Default: True

    """
    printToFile(self.get_element(), filename, prettyprint, encoding)
class ParameterValueSet

Creates the ParameterValueSet used by the DeterministicMultiParameterDistribution

Parameters

Attributes

assignments (list of ParameterAssignment): the the assignments for the ValueSet

Methods

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

add_parameter(parameterref, value)
    Adds a parameter value pair

get_element(elementname)
    Returns the full ElementTree of the class

initalizes the ParameterValueSet

Expand source code
class ParameterValueSet(VersionBase):
    """Creates the ParameterValueSet used by the DeterministicMultiParameterDistribution

    Parameters
    ----------


    Attributes
    ----------

        assignments (list of ParameterAssignment): the the assignments for the ValueSet

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

        add_parameter(parameterref, value)
            Adds a parameter value pair

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    def __init__(self):
        """initalizes the ParameterValueSet"""

        self.sets = []

    def __eq__(self, other):
        if isinstance(other, ParameterValueSet):
            if self.sets == other.sets:
                return True
        return False

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

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

        Returns
        -------
            parameter_value_set (ParameterValueSet): a ParameterValueSet object

        """
        parameter_value_set = ParameterValueSet()
        for pa in element.findall("ParameterAssignment"):
            parameter_value_set.sets.append(ParameterAssignment.parse(pa))

        return parameter_value_set

    def add_parameter(self, parameterref, value):
        """adds a parameter and a value

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

            value (str): value of the parameters

        """

        self.sets.append(ParameterAssignment(parameterref, value))
        return self

    def get_element(self):
        """returns the elementTree of the ParameterValueSet"""
        element = ET.Element("ParameterValueSet")

        if not self.sets:
            raise NotEnoughInputArguments("No sets has been added")
        for s in self.sets:
            element.append(s.get_element())

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of ParameterValueSet

Parameters

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

Returns

parameter_value_set (ParameterValueSet): a ParameterValueSet object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of ParameterValueSet

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

    Returns
    -------
        parameter_value_set (ParameterValueSet): a ParameterValueSet object

    """
    parameter_value_set = ParameterValueSet()
    for pa in element.findall("ParameterAssignment"):
        parameter_value_set.sets.append(ParameterAssignment.parse(pa))

    return parameter_value_set

Methods

def add_parameter(self, parameterref, value)

adds a parameter and a value

Parameters

parameterref (str): name of the parameters

value (str): value of the parameters
Expand source code
def add_parameter(self, parameterref, value):
    """adds a parameter and a value

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

        value (str): value of the parameters

    """

    self.sets.append(ParameterAssignment(parameterref, value))
    return self
def get_element(self)

returns the elementTree of the ParameterValueSet

Expand source code
def get_element(self):
    """returns the elementTree of the ParameterValueSet"""
    element = ET.Element("ParameterValueSet")

    if not self.sets:
        raise NotEnoughInputArguments("No sets has been added")
    for s in self.sets:
        element.append(s.get_element())

    return element
class PoissonDistribution (expected_value, range=None)

the PoissonDistribution is a Stochastic distribution

Parameters

expected_value (float): the expected value of the distribution

range (Range): limit of the values (optional)
    Default: None

Attributes

expected_value (float): the expected value of the distribution

range (Range): limit of the values (optional)

Methods

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

get_element(elementname)
    Returns the full ElementTree of the class

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

initalizes the PoissonDistribution

Parameters

expected_value (float): the expected value of the distribution

range (Range): limit of the values (optional)
    Default: None
Expand source code
class PoissonDistribution(_StochasticDistributionType):
    """the PoissonDistribution is a Stochastic distribution

    Parameters
    ----------
        expected_value (float): the expected value of the distribution

        range (Range): limit of the values (optional)
            Default: None

    Attributes
    ----------
        expected_value (float): the expected value of the distribution

        range (Range): limit of the values (optional)

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

        get_element(elementname)
            Returns the full ElementTree of the class

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

    """

    def __init__(self, expected_value, range=None):
        """initalizes the PoissonDistribution

        Parameters
        ----------
            expected_value (float): the expected value of the distribution

            range (Range): limit of the values (optional)
                Default: None

        """
        if range and not isinstance(range, Range):
            raise TypeError("range input is not of type Range")
        self.expected_value = expected_value
        self.range = range

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

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

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

        Returns
        -------
            pd (PoissonDistribution): a PoissonDistribution object

        """
        if element.find("Range") is not None:
            range = Range.parse(element.find("Range"))
        else:
            range = None
        pd = PoissonDistribution(element.attrib["expectedValue"], range)
        return pd

    def get_attributes(self):
        """returns the attributes of the PoissonDistribution as a dict"""
        retdict = {"expectedValue": str(self.expected_value)}
        return retdict

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

Ancestors

  • scenariogeneration.xosc.utils._StochasticDistributionType
  • VersionBase

Static methods

def parse(element)

Parses the xml element of PoissonDistribution

Parameters

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

Returns

pd (PoissonDistribution): a PoissonDistribution object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of PoissonDistribution

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

    Returns
    -------
        pd (PoissonDistribution): a PoissonDistribution object

    """
    if element.find("Range") is not None:
        range = Range.parse(element.find("Range"))
    else:
        range = None
    pd = PoissonDistribution(element.attrib["expectedValue"], range)
    return pd

Methods

def get_attributes(self)

returns the attributes of the PoissonDistribution as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the PoissonDistribution as a dict"""
    retdict = {"expectedValue": str(self.expected_value)}
    return retdict
def get_element(self)

returns the elementTree of the PoissonDistribution

Expand source code
def get_element(self):
    """returns the elementTree of the PoissonDistribution"""
    element = ET.Element("PoissonDistribution", self.get_attributes())
    if self.range:
        element.append(self.range.get_element())
    return element
class ProbabilityDistributionSet

the ProbabilityDistributionSet is a Stochastic distribution

Parameters

Attributes

sets (list of _ProbabilityDistributionSetElement): the sets defining the ProbabilityDistributionSet

Methods

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

get_element(elementname)
    Returns the full ElementTree of the class

add_set(value, weight)
    adds a weight and a range to a bin

initalizes the ProbabilityDistributionSet

Expand source code
class ProbabilityDistributionSet(_StochasticDistributionType):
    """the ProbabilityDistributionSet is a Stochastic distribution

    Parameters
    ----------

    Attributes
    ----------
        sets (list of _ProbabilityDistributionSetElement): the sets defining the ProbabilityDistributionSet

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

        get_element(elementname)
            Returns the full ElementTree of the class

        add_set(value, weight)
            adds a weight and a range to a bin

    """

    def __init__(self):
        """initalizes the ProbabilityDistributionSet"""
        self.sets = []

    def __eq__(self, other):
        if isinstance(other, ProbabilityDistributionSet):
            if self.sets == other.sets:
                return True
        return False

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

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

        Returns
        -------
            pds (ProbabilityDistributionSet): a ProbabilityDistributionSet object

        """
        pds = ProbabilityDistributionSet()
        for e in element.findall("Element"):
            pds.sets.append(_ProbabilityDistributionSetElement.parse(e))
        return pds

    def add_set(self, value, weight):
        """adds a set element to the ProbabilityDistributionSet

        Parameters
        ----------
            value (string): possible value

            weight (float): weight of the value

        """
        self.sets.append(_ProbabilityDistributionSetElement(value, weight))
        return self

    def get_element(self):
        """returns the elementTree of the ProbabilityDistributionSet"""
        element = ET.Element("ProbabilityDistributionSet")
        if not self.sets:
            raise NotEnoughInputArguments(
                "No sets were added to the ProbabilityDistributionSet, please use add_set"
            )
        for bin in self.sets:
            element.append(bin.get_element())
        return element

Ancestors

  • scenariogeneration.xosc.utils._StochasticDistributionType
  • VersionBase

Static methods

def parse(element)

Parses the xml element of ProbabilityDistributionSet

Parameters

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

Returns

pds (ProbabilityDistributionSet): a ProbabilityDistributionSet object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of ProbabilityDistributionSet

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

    Returns
    -------
        pds (ProbabilityDistributionSet): a ProbabilityDistributionSet object

    """
    pds = ProbabilityDistributionSet()
    for e in element.findall("Element"):
        pds.sets.append(_ProbabilityDistributionSetElement.parse(e))
    return pds

Methods

def add_set(self, value, weight)

adds a set element to the ProbabilityDistributionSet

Parameters

value (string): possible value

weight (float): weight of the value
Expand source code
def add_set(self, value, weight):
    """adds a set element to the ProbabilityDistributionSet

    Parameters
    ----------
        value (string): possible value

        weight (float): weight of the value

    """
    self.sets.append(_ProbabilityDistributionSetElement(value, weight))
    return self
def get_element(self)

returns the elementTree of the ProbabilityDistributionSet

Expand source code
def get_element(self):
    """returns the elementTree of the ProbabilityDistributionSet"""
    element = ET.Element("ProbabilityDistributionSet")
    if not self.sets:
        raise NotEnoughInputArguments(
            "No sets were added to the ProbabilityDistributionSet, please use add_set"
        )
    for bin in self.sets:
        element.append(bin.get_element())
    return element
class Range (lower, upper)

the Range creates a Range used by parameter distributions

Parameters

lower (float): lower limit of the range

upper (float): upper limit of the range

Attributes

lower (float): lower limit of the range

upper (float): upper limit of the range

Methods

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

get_element(elementname)
    Returns the full ElementTree of the class

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

initalizes the Range

Parameters

lower (float): lower limit of the range

upper (float): upper limit of the range
Expand source code
class Range(VersionBase):
    """the Range creates a Range used by parameter distributions

    Parameters
    ----------
        lower (float): lower limit of the range

        upper (float): upper limit of the range

    Attributes
    ----------
        lower (float): lower limit of the range

        upper (float): upper limit of the range

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

        get_element(elementname)
            Returns the full ElementTree of the class

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

    """

    def __init__(self, lower, upper):
        """initalizes the Range

        Parameters
        ----------
            lower (float): lower limit of the range

            upper (float): upper limit of the range

        """
        self.lower = convert_float(lower)
        self.upper = convert_float(upper)

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

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

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

        Returns
        -------
            range (Range): a Range object

        """

        return Range(
            convert_float(element.attrib["lowerLimit"]),
            convert_float(element.attrib["upperLimit"]),
        )

    def get_attributes(self):
        """returns the attributes of the Range as a dict"""
        retdict = {"lowerLimit": str(self.lower), "upperLimit": str(self.upper)}
        return retdict

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

Ancestors

Static methods

def parse(element)

Parses the xml element of Range

Parameters

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

Returns

range (Range): a Range object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Range

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

    Returns
    -------
        range (Range): a Range object

    """

    return Range(
        convert_float(element.attrib["lowerLimit"]),
        convert_float(element.attrib["upperLimit"]),
    )

Methods

def get_attributes(self)

returns the attributes of the Range as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Range as a dict"""
    retdict = {"lowerLimit": str(self.lower), "upperLimit": str(self.upper)}
    return retdict
def get_element(self, elementname='Range')

returns the elementTree of the Range

Expand source code
def get_element(self, elementname="Range"):
    """returns the elementTree of the Range"""
    element = ET.Element(elementname, self.get_attributes())
    return element
class Stochastic (number_of_tests, random_seed=None)

Creates the Stochastic type of parameter distributions

Parameters

number_of_tests (int): number of tests to run

random_seed (float): the seed for the run
    Default: None

Attributes

number_of_tests (int): number of tests to run

random_seed (float): the seed for the run

distributions (dict of *StochasticDistribution): the distributions for the parameters

Methods

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

add_distribution(parametername, distribution)
    Adds a parameter/distribution pair

get_element(elementname)
    Returns the full ElementTree of the class

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

initalizes the Stochastic

Parameters

number_of_tests (int): number of tests to run

random_seed (float): the seed for the run
    Default: None
Expand source code
class Stochastic(VersionBase):
    """Creates the Stochastic type of parameter distributions

    Parameters
    ----------
        number_of_tests (int): number of tests to run

        random_seed (float): the seed for the run
            Default: None

    Attributes
    ----------
        number_of_tests (int): number of tests to run

        random_seed (float): the seed for the run

        distributions (dict of *StochasticDistribution): the distributions for the parameters

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

        add_distribution(parametername, distribution)
            Adds a parameter/distribution pair

        get_element(elementname)
            Returns the full ElementTree of the class

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

    """

    def __init__(self, number_of_tests, random_seed=None):
        """initalizes the Stochastic

        Parameters
        ----------
            number_of_tests (int): number of tests to run

            random_seed (float): the seed for the run
                Default: None

        """
        self.number_of_tests = number_of_tests
        self.random_seed = random_seed
        self.distributions = {}

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

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

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

        Returns
        -------
            Stochastic (Stochastic): a Stochastic object

        """

        if "randomSeed" in element.attrib:
            seed = element.attrib["randomSeed"]
        else:
            seed = None
        stoc = Stochastic(element.attrib["numberOfTestRuns"], seed)
        for dist_element in element.findall("StochasticDistribution"):
            name = dist_element.attrib["parameterName"]
            dist = _StochasticFactory.parse_distribution(dist_element)
            stoc.add_distribution(name, dist)
        return stoc

    def add_distribution(self, parametername, distribution):
        """adds a parameter and a related distribution to it

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

            distribution (StochasticDistribution): the distribution of that parameter

        """
        if not isinstance(distribution, _StochasticDistributionType):
            raise TypeError("distribution input is not a valid StochasticDistribution")
        self.distributions[parametername] = distribution
        return self

    def get_attributes(self):
        """returns the attributes of the Stochastic as a dict"""
        retdict = {}
        retdict["numberOfTestRuns"] = str(self.number_of_tests)
        if self.random_seed is not None:
            retdict["randomSeed"] = str(self.random_seed)

        return retdict

    def get_element(self):
        """returns the elementTree of the Stochastic"""
        element = ET.Element("Stochastic", self.get_attributes())
        if not self.distributions:
            raise NotEnoughInputArguments("No distribution has been added")
        for d in self.distributions:
            # dist = ET.SubElement(element,'stochasticDistribution',)
            dist = ET.SubElement(
                element, "StochasticDistribution", attrib={"parameterName": d}
            )
            dist.append(self.distributions[d].get_element())

        return element

Ancestors

Static methods

def parse(element)

Parses the xml element of Stochastic

Parameters

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

Returns

Stochastic (Stochastic): a Stochastic object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of Stochastic

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

    Returns
    -------
        Stochastic (Stochastic): a Stochastic object

    """

    if "randomSeed" in element.attrib:
        seed = element.attrib["randomSeed"]
    else:
        seed = None
    stoc = Stochastic(element.attrib["numberOfTestRuns"], seed)
    for dist_element in element.findall("StochasticDistribution"):
        name = dist_element.attrib["parameterName"]
        dist = _StochasticFactory.parse_distribution(dist_element)
        stoc.add_distribution(name, dist)
    return stoc

Methods

def add_distribution(self, parametername, distribution)

adds a parameter and a related distribution to it

Parameters

parametername (str): name of the parameter

distribution (StochasticDistribution): the distribution of that parameter
Expand source code
def add_distribution(self, parametername, distribution):
    """adds a parameter and a related distribution to it

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

        distribution (StochasticDistribution): the distribution of that parameter

    """
    if not isinstance(distribution, _StochasticDistributionType):
        raise TypeError("distribution input is not a valid StochasticDistribution")
    self.distributions[parametername] = distribution
    return self
def get_attributes(self)

returns the attributes of the Stochastic as a dict

Expand source code
def get_attributes(self):
    """returns the attributes of the Stochastic as a dict"""
    retdict = {}
    retdict["numberOfTestRuns"] = str(self.number_of_tests)
    if self.random_seed is not None:
        retdict["randomSeed"] = str(self.random_seed)

    return retdict
def get_element(self)

returns the elementTree of the Stochastic

Expand source code
def get_element(self):
    """returns the elementTree of the Stochastic"""
    element = ET.Element("Stochastic", self.get_attributes())
    if not self.distributions:
        raise NotEnoughInputArguments("No distribution has been added")
    for d in self.distributions:
        # dist = ET.SubElement(element,'stochasticDistribution',)
        dist = ET.SubElement(
            element, "StochasticDistribution", attrib={"parameterName": d}
        )
        dist.append(self.distributions[d].get_element())

    return element
class UniformDistribution (range)

the UniformDistribution is a Stochastic distribution

Parameters

range (Range): limit of the values

Attributes

range (Range): limit of the values

Methods

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

get_element(elementname)
    Returns the full ElementTree of the class

initalizes the UniformDistribution

Parameters

range (Range): limit of the values (optional)
Expand source code
class UniformDistribution(_StochasticDistributionType):
    """the UniformDistribution is a Stochastic distribution

    Parameters
    ----------
        range (Range): limit of the values

    Attributes
    ----------
        range (Range): limit of the values

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

        get_element(elementname)
            Returns the full ElementTree of the class

    """

    def __init__(self, range):
        """initalizes the UniformDistribution

        Parameters
        ----------
            range (Range): limit of the values (optional)


        """
        if not isinstance(range, Range):
            raise TypeError("range input is not of type Range")
        self.range = range

    def __eq__(self, other):
        if isinstance(other, UniformDistribution):
            if self.range == other.range:
                return True
        return False

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

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

        Returns
        -------
            ud (UniformDistribution): a UniformDistribution object

        """

        return UniformDistribution(Range.parse(element.find("Range")))

    def get_element(self):
        """returns the elementTree of the UniformDistribution"""
        element = ET.Element("UniformDistribution")
        element.append(self.range.get_element())
        return element

Ancestors

  • scenariogeneration.xosc.utils._StochasticDistributionType
  • VersionBase

Static methods

def parse(element)

Parses the xml element of UniformDistribution

Parameters

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

Returns

ud (UniformDistribution): a UniformDistribution object
Expand source code
@staticmethod
def parse(element):
    """Parses the xml element of UniformDistribution

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

    Returns
    -------
        ud (UniformDistribution): a UniformDistribution object

    """

    return UniformDistribution(Range.parse(element.find("Range")))

Methods

def get_element(self)

returns the elementTree of the UniformDistribution

Expand source code
def get_element(self):
    """returns the elementTree of the UniformDistribution"""
    element = ET.Element("UniformDistribution")
    element.append(self.range.get_element())
    return element