Exemplo n.º 1
0
 def _reduceSelf(self):
     """
     Parse our unit and reduce ourselves to the smallest representation
     """
     if isinstance(self.unit, basestring):
         self.unit = self.__findUnit()
     a = self.amount * self.prefix
     self.amount, self.prefix = Prefix.closestPrefix(a)
Exemplo n.º 2
0
    def __findUnit(self):
        """
        Take a string like kV and work out prefix and units, obviously
        there is scope for collision between units and prefixes...

        :return: :mod:`Unit` object
        """
        if not self.unit:
            return NO_UNIT

        if isinstance(self.unit, Unit.Unit):
            return self.unit

        u = self.unit
        if Unit.hasUnit(u):
            return Unit.getUnit(u)

        # Work backwards through the list trying to find a unit that matches
        unit = self.unit = None
        ul = list(u)
        u = ""

        while ul:
            u = (ul.pop() + u)
            if Unit.hasUnit(u):
                unit = Unit.getUnit(u)
                break

        # Nothing left to look at
        if not ul:
            if not unit:
                # Make a temporary unit, since we don't know what this is
                unit = Unit.Unit(u, u, True)
            return unit

        # We have left overs... this should be a prefix...
        ul = ''.join(ul)
        if Prefix.hasPrefix(ul):
            self.amount *= Prefix.getPrefix(ul)
        return unit
Exemplo n.º 3
0
    def to(self, prefix):
        u"""
        Convert to different prefix (i.e. seconds to ms) with no units e.g.

        >>> q = Quantity(1, 'km')
        >>> q
        1.0 km
        >>> q.to('m')
        1000.0
        >>> q.to('mm')
        1000000.0
        >>> q.to('Mm')
        0.001

        :param prefix: A prefix / unit to convert to
        :return: A floating point scalar or None for invalid prefix
        """
        if prefix.endswith(self.unit.unit):
            prefix = prefix[:-len(self.unit.unit)]

        if Prefix.hasPrefix(prefix):
            return int(self) / Prefix.getPrefix(prefix)

        return None
Exemplo n.º 4
0
 def testSimplePrefix(self):
     r = Prefix.closestPrefix(1000)
     assert r == (1.0, Prefix.Prefixes.kilo)
Exemplo n.º 5
0
 def testSmallPrefix(self):
     r = Prefix.closestPrefix(0.05)
     assert r == (50, Prefix.Prefixes.milli)
Exemplo n.º 6
0
 def testNegativePrefix(self):
     r = Prefix.closestPrefix(-1000)
     assert r == (-1.0, Prefix.Prefixes.kilo), r
Exemplo n.º 7
0
 def testComplexPrefix(self):
     r = Prefix.closestPrefix(1024)
     assert r == (1.024, Prefix.Prefixes.kilo)