SIfloat.py 2.03 KB
Newer Older
1 2 3 4 5
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

6 7
import os
import re
8
import pykat.exceptions as pkex
9
import numpy as np
10
import pykat
11

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
__suffix = {'y': 'e-24',  # yocto
            'z': 'e-21',  # zepto
            'a': 'e-18',  # atto
            'f': 'e-15',  # femto
            'p': 'e-12',  # pico
            'n': 'e-9',   # nano
            'u': 'e-6',   # micro
            'm': 'e-3',   # mili
            'c': 'e-2',   # centi
            'd': 'e-1',   # deci
            'k': 'e3',    # kilo
            'M': 'e6',    # mega
            'G': 'e9',    # giga
            'T': 'e12',   # tera
            'P': 'e15'   # peta
            }
            
29 30
__exceptions = ["$fs", "$mfs"]

31
def SIfloat(value):
32 33 34
    if isinstance(value, pykat.commands.Constant):
        return '$' + value.name
        
35 36 37
    if str(value).startswith('$'):
        return value
        
38 39 40
    if value is None: 
        return value
    
41
    if str(value) in __exceptions:
42
        return value
43 44 45 46 47 48 49 50 51
        
    value = np.array(value)
    
    v = np.vectorize(convertToFloat)
    
    if value.size == 1:
        return float(v(value))
        
    a = v(value)
52
    
53 54
    if len(a) == 1:
        return a[0]
55
    else:
56
        return a
57 58
    
def convertToFloat(value):
59
    
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
    try:
        # first just try and convert the value
        return float(value)
        
    except ValueError as ex:
        # Catch any casting exeception
        value = value.strip()
        
        # only the last value can be an SI scaling letter 
        last = value[-1]

        if last in __suffix:
            # remove last character and append the SI scaling
            value = value[0:-1] + __suffix[last]
        else:
            raise pkex.BasePyKatException("Could not convert SI scaling in '{0}' to a float".format(value))
76
        
77 78 79 80
        try:   
            return float(value)
        except ValueError as ex:
            raise pkex.BasePyKatException("Unable to convert '{0}' into a float".format(value))