Exemplo n.º 1
0
    def __init__(self,
                 symbol_type,
                 value,
                 units=None,
                 tags=None,
                 provenance=None,
                 uncertainty=None):
        """
        Parses inputs for constructing a Property object.

        Args:
            symbol_type (Symbol or str): pointer to an existing Symbol
                object in default_symbols or string giving the name
                of a SymbolType object identifies the type of data
                stored in the property.
            value (id): value of the property.
            units: (None): units associated with the quantity's value
            tags (list<str>): list of strings storing metadata from
                Quantity evaluation.
            provenance (ProvenanceElement): provenance associated with the
                object (e. g. inputs, model, see ProvenanceElement)
        """
        # Invoke default symbol if symbol is a string
        if isinstance(symbol_type, str):
            if symbol_type not in DEFAULT_SYMBOLS.keys():
                raise ValueError(
                    "Quantity type {} not recognized".format(symbol_type))
            symbol_type = DEFAULT_SYMBOLS[symbol_type]

        # Set default units if not supplied
        units = units or symbol_type.units

        # Invoke pint quantity if supplied or input is float/int
        if isinstance(value, (float, int, list, np.ndarray)):
            self._value = ureg.Quantity(value, units)
        elif isinstance(value, ureg.Quantity):
            self._value = value.to(units)
        else:
            self._value = value

        if isinstance(uncertainty, (float, int, list, np.ndarray)):
            self._uncertainty = ureg.Quantity(uncertainty, units)
        elif isinstance(uncertainty, ureg.Quantity):
            self._uncertainty = uncertainty.to(units)
        else:
            self._uncertainty = uncertainty

        # TODO: Symbol-level constraints are hacked together atm,
        #       constraints as a whole need to be refactored and
        #       put into a separate module
        if symbol_type.constraint is not None:
            if not symbol_type.constraint(
                    **{symbol_type.name: self.magnitude}):
                raise SymbolConstraintError(
                    "Quantity with {} value does not satisfy {}".format(
                        value, symbol_type.constraint))

        self._symbol_type = symbol_type
        self._tags = tags
        self._provenance = provenance
Exemplo n.º 2
0
    def get_symbol_from_string(name):
        """
        Looks up Symbol from name in DEFAULT_SYMBOLS registry.

        Args:
            name: (str) the name of the Symbol object

        Returns: (Symbol) the Symbol object associated with the name

        """
        # Invoke default symbol if symbol is a string
        if not isinstance(name, str):
            raise TypeError("Expected str, encountered {}".format(type(name)))

        if name not in DEFAULT_SYMBOLS.keys():
            raise ValueError("Symbol type {} not recognized".format(name))

        return DEFAULT_SYMBOLS[name]
Exemplo n.º 3
0
    def as_dict(self):
        """
        Serializes object as a dictionary. Object can be reconstructed with from_dict().

        Returns:
            (dict): representation of object as a dictionary
        """
        symbol = self._symbol_type
        if symbol.name in DEFAULT_SYMBOLS.keys() and symbol == DEFAULT_SYMBOLS[
                symbol.name]:
            symbol = self._symbol_type.name
        else:
            symbol = symbol.as_dict()

        return {
            "symbol_type": symbol,
            "provenance":
            self.provenance.as_dict() if self.provenance else None,
            "tags": self.tags
        }
Exemplo n.º 4
0
    def as_dict(self):
        """
        Gives the dictionary representation of this object, excluding value,
        units, and uncertainty.

        Returns: (dict) dictionary representation of this object for serialization

        """
        symbol = self._symbol_type
        if symbol.name in DEFAULT_SYMBOLS.keys() and symbol == DEFAULT_SYMBOLS[symbol.name]:
            symbol = self._symbol_type.name

        return {
            "@module": self.__class__.__module__,
            "@class": self.__class__.__name__,
            "data_type": self._data_type,
            "symbol_type": symbol,
            "internal_id": self._internal_id,
            "tags": self._tags,
            "provenance": self._provenance
        }
Exemplo n.º 5
0
    def as_dict(self):
        """
        Returns object instance as a dictionary. Object can be reconstituted from this
        dictionary using from_dict().

        Returns: (dict) dictionary representation of the object

        """
        symbol = self._symbol_type
        if symbol.name in DEFAULT_SYMBOLS.keys() and symbol == DEFAULT_SYMBOLS[symbol.name]:
            symbol = self._symbol_type.name

        return {"@module": self.__class__.__module__,
                "@class": self.__class__.__name__,
                "internal_id": self._internal_id,
                "data_type": self._data_type,
                "symbol_type": symbol,
                "value": self._value,
                "units": self._units,
                "provenance": self._provenance,
                "tags": self._tags,
                "uncertainty": self._uncertainty}
Exemplo n.º 6
0
    def __init__(self,
                 symbol_type,
                 value,
                 units=None,
                 tags=None,
                 provenance=None,
                 uncertainty=None,
                 **kwargs):
        """
        Parses inputs for constructing a Property object.

        Args:
            symbol_type (Symbol or str): pointer to an existing Symbol
                object in default_symbols or string giving the name
                of a SymbolType object identifies the type of data
                stored in the property.
            value (id): value of the property.
            units: (None): units associated with the quantity's value
            tags (list<str>): list of strings storing metadata from
                Quantity evaluation.
            provenance (ProvenanceElement): provenance associated with the
                object (e. g. inputs, model, see ProvenanceElement)
        """
        # Invoke default symbol if symbol is a string
        if isinstance(symbol_type, str):
            if symbol_type not in DEFAULT_SYMBOLS.keys():
                raise ValueError(
                    "Quantity type {} not recognized".format(symbol_type))
            symbol_type = DEFAULT_SYMBOLS[symbol_type]

        # Set default units if not supplied
        units = units or symbol_type.units

        # Hid this keyword in kwargs so users don't see it
        # in function code completion display
        if 'internal_id' in kwargs.keys():
            self._internal_id = kwargs['internal_id']
        else:
            self._internal_id = uuid.uuid4().hex

        # Invoke pint quantity if supplied or input is float/int

        if isinstance(value, (np.floating, np.integer, np.complexfloating)):
            self._value = ureg.Quantity(np.asscalar(value), units)
        elif isinstance(value, (float, int, list, complex, np.ndarray)):
            self._value = ureg.Quantity(value, units)
        elif isinstance(value, ureg.Quantity):
            self._value = value.to(units)
        elif isinstance(value, Quantity):
            # TODO: This situation needs a deep copy function
            self._value = value._value
            self._internal_id = value._internal_id
        else:
            self._value = value

        if isinstance(uncertainty,
                      (np.floating, np.integer, np.complexfloating)):
            self._uncertainty = ureg.Quantity(np.asscalar(uncertainty), units)
        elif isinstance(uncertainty, (float, int, list, complex, np.ndarray)):
            self._uncertainty = ureg.Quantity(uncertainty, units)
        elif isinstance(uncertainty, ureg.Quantity):
            self._uncertainty = uncertainty.to(units)
        else:
            self._uncertainty = uncertainty

        # TODO: Symbol-level constraints are hacked together atm,
        #       constraints as a whole need to be refactored and
        #       put into a separate module
        if symbol_type.constraint is not None:
            if not symbol_type.constraint(
                    **{symbol_type.name: self.magnitude}):
                raise SymbolConstraintError(
                    "Quantity with {} value does not satisfy {}".format(
                        value, symbol_type.constraint))

        self._symbol_type = symbol_type
        self._tags = tags
        self._provenance = provenance

        if self._provenance is not None:
            if isinstance(self._provenance.source, dict):
                if 'source_key' not in self._provenance.source.keys() or \
                        self._provenance.source['source_key'] in (None, ""):
                    self._provenance.source['source_key'] = self._internal_id
                if 'date_created' not in self._provenance.source.keys() or \
                        self._provenance.source['date_created'] in (None, ""):
                    self._provenance.source['date_created'] = datetime.now(
                    ).strftime("%Y-%m-%d %H:%M:%S")
            elif self._provenance.source is None:
                self._provenance.source = {
                    "source": "propnet",
                    "source_key": self._internal_id,
                    "date_created":
                    datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                }