Ticket #9759: trac_9759_si_prefixes.patch

File trac_9759_si_prefixes.patch, 1.6 KB (added by cousteau, 11 years ago)

Patch that adds components of units.si_prefixes as properties on the UnitExpression? class

  • sage/symbolic/units.py

    # HG changeset patch
    # User Javier Mora <cousteaulecommandant@gmail.com>
    # Date 1282086051 -7200
    # Node ID 23ed5ab243ebe333ba7cccacd8aa8a496ca575a8
    # Parent  5b338f2e484f2065d3d30d47bc204d6e9ed13d12
    Trac 9759: Integration of SI prefixes into other units on units module
    
    diff -r 5b338f2e484f -r 23ed5ab243eb sage/symbolic/units.py
    a b  
    999999        """
    10001000        return unitdocs(self)
    10011001
     1002    def _si_prefix_(self, prefix):
     1003        """
     1004        Returns a unit prefixed with an SI prefix, creating it if it doesn't already exist.
     1005       
     1006        EXAMPLE::
     1007       
     1008            sage: units.length.meter._si_prefix_('kilo')
     1009            kilometer
     1010        """
     1011        from sage.misc.all import sage_eval
     1012        if prefix not in unitdict['si_prefixes']:
     1013            raise ValueError, "Prefix not in units.si_prefixes"
     1014        base = str(self)
     1015        name = prefix+base
     1016        if name not in unit_to_type:
     1017            utype = unit_to_type[base]
     1018            value = str(sage_eval(unitdict['si_prefixes'][prefix]) * sage_eval(unitdict[utype][base]))
     1019            unitdict[utype][name] = value
     1020            unit_to_type[name] = utype
     1021            value_to_unit[utype][value] = name
     1022        return SR.var(name)
     1023
     1024def _add_si_property_(prefix):
     1025    setattr(UnitExpression, prefix, property(lambda self: self._si_prefix_(prefix)))
     1026
     1027for prefix in unitdict['si_prefixes']:
     1028    _add_si_property_(prefix)
     1029
    10021030def str_to_unit(name):
    10031031    """
    10041032    Create the symbolic unit with given name.  A symbolic unit is a