util.py

Go to the documentation of this file.
00001 ##
00002 # 
00003 # Miscellaneous routines in python:
00004 # 
00005 # Ruler                 Return a ruler
00006 # TensRuler             10's ruler to go along with Ruler()
00007 # WindChillInDegF       Calculate wind chill given OAT & wind speed
00008 # Deg2Rad               Converts degrees to radians
00009 # Rad2Deg               Converts radians to degrees
00010 # SpellCheck            Checks that a list of words is in a dictionary
00011 # Keep                  Keep only specified characters in a string
00012 # Remove                Remove a specified set of characters from a string
00013 # ListInColumns         Produce a listing like ls
00014 # Debug                 A class that helps with debugging
00015 # Time                  Returns a string giving local time and date
00016 # AWG                   Returns wire diam in inches for AWG gauge number
00017 # NiceRound             Rounds a floating pt to nearest 1, 2, or 5.
00018 # SignificantFiguresS   Rounds to specified num of sig figures (returns string)
00019 # SignificantFigures    Rounds to specified num of sig figures (returns float)
00020 # SignMantissaExponent  Returns tuple of sign, mantissa, exponent
00021 # 
00022 # Copyright (C) 2002 GDS Software
00023 # 
00024 # This program is free software; you can redistribute it and/or
00025 # modify it under the terms of the GNU General Public License as
00026 # published by the Free Software Foundation; either version 2 of
00027 # the License, or (at your option) any later version.
00028 # 
00029 # This program is distributed in the hope that it will be useful,
00030 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00031 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00032 # GNU General Public License for more details.
00033 # 
00034 # You should have received a copy of the GNU General Public
00035 # License along with this program; if not, write to the Free
00036 # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
00037 # MA  02111-1307  USA
00038 # 
00039 # See http://www.gnu.org/licenses/licenses.html for more details.
00040 # 
00041 
00042 import sys
00043 __version__ = "$Id: util.py,v 1.1 2002/08/21 12:42:53 donp Exp $"
00044 
00045 ##
00046 # 
00047 #     Function to return a ruler string.
00048 # 
00049 #     Type 1 ruler:
00050 #              1         2         3         4         5         6         7
00051 #     1234567890123456789012345678901234567890123456789012345678901234567890
00052 # 
00053 #     Type 2 ruler:
00054 #              1         2         3         4         5         6         7
00055 #     ----+----|----+----|----+----|----+----|----+----|----+----|----+----|
00056 # 
00057 #     Type 3 ruler:
00058 # 
00059 #     ----+----|----+----|----+----|----+----|----+----|----+----|----+----|
00060 # 
00061 #     Type 4 ruler:
00062 #     ---------|---------|---------|---------|---------|---------|---------|
00063 #     
00064 def Ruler(size = 79, type = 1):
00065     if size < 1:
00066         raise "Bad data", "Ruler:  size < 1"
00067     str = ""
00068     if type == 1:
00069         str = TensRuler(size)
00070         base = "1234567890"
00071     elif type == 2:
00072         str = TensRuler(size)
00073         base = "----+----|"
00074         pass
00075     elif type == 3:
00076         base = "----+----|"
00077     elif type == 4:
00078         base = "---------|"
00079     else:
00080         raise "Bad data", "Ruler:  type not between 1 and 3"
00081     num_repeats = (size/10 + 2) * 10
00082     tmpstr = base * num_repeats
00083     str = str + tmpstr[:size]
00084     return str
00085 
00086 def TensRuler(size):
00087     if size >= 10:
00088         str = ""
00089         for ix in range(1, 1 + size/10):
00090             str = str + "%10d" % (ix * 10)
00091         str = str + "\n"
00092     return str
00093 
00094 ##
00095 # Wind Chill for exposed human skin, expressed as a function of 
00096 #     wind speed in Miles per Hour and temperature in degrees Fahrenheit.
00097 #     Gotten from the Snippets collection.
00098 #     
00099 def WindChillInDegF(wind_speed_in_mph, air_temp_deg_F):
00100     import math
00101     if wind_speed_in_mph < 4:
00102         return air_temp_deg_F * 1.0
00103     return (((10.45 + (6.686112 * math.sqrt(1.0*wind_speed_in_mph))            - (.447041 * wind_speed_in_mph)) / 22.034 *            (air_temp_deg_F - 91.4)) + 91.4)
00104 
00105 def Deg2Rad(degrees):
00106     import math
00107     return degrees/180.0 * math.pi
00108 
00109 def Rad2Deg(radians):
00110     import math
00111     return radians/math.pi * 180.0
00112 
00113 ##
00114 # 
00115 #     This module provides the function SpellCheck(), which takes as its
00116 #     input the list of words to spell check in input_list and the
00117 #     dictionary word_dictionary (it's a dictionary rather than a list to
00118 #     allow fast access; the dictionary values can be null strings --
00119 #     all that's important is that the key be there).  It returns any
00120 #     words in input_list that are not in word_dictionary.
00121 #     
00122 def SpellCheck(input_list, word_dictionary, case_is_not_important = 1):
00123     import string
00124     misspelled = []
00125     if len(input_list) == 0:
00126         return []
00127     if len(word_dictionary) == 0:
00128         raise "SpellCheck:  word_dictionary parameter is empty"
00129     for ix in xrange(len(input_list)):
00130         if case_is_not_important:
00131             word = string.lower(input_list[ix])
00132         if not word_dictionary.has_key(word):
00133             misspelled.append(word)
00134     return misspelled
00135 
00136 def Keep(str, keep_chars):
00137     "Keep only specified characters in a string"
00138     strlength = len(str)
00139     if strlength == 0 or len(keep_chars) == 0:  
00140         return ""
00141     count = 0
00142     outstring = ""
00143     while count < strlength:
00144         if str[count] in keep_chars:
00145             outstring = outstring + str[count]
00146         count = count + 1
00147     return outstring
00148 
00149 def Remove(str, remove_chars):
00150     "Remove specified characters from a string"
00151     strlength = len(str)
00152     if strlength == 0:  
00153         return ""
00154     if len(remove_chars) == 0:  
00155         return str
00156     count = 0
00157     outstring = ""
00158     while count < strlength:
00159         if str[count] not in remove_chars:
00160             outstring = outstring + str[count]
00161         count = count + 1
00162     return outstring
00163 
00164 
00165 ##
00166 # Returns a list of strings with the elements of list (must be 
00167 #     strings) printed in columnar format.  Elements of list that won't
00168 #     fit in a column either generate an exception if truncate is 0
00169 #     or get truncated if truncate is nonzero.  The number of spaces 
00170 #     between columns is space_betw.
00171 # 
00172 #     Caveat:  if there are a small number of elements in the list, you
00173 #     may not get what you expect.  For example, try a list size of 1 to
00174 #     10 with num_columns equal to 4:  for lists of 1, 2, 3, 5, 6, and 9,
00175 #     you'll get fewer than four columns.
00176 #     
00177 def ListInColumns(list, col_width, num_columns, space_betw=0, truncate=0):
00178     lines = []
00179     N = len(list)
00180     if col_width < 1 or num_columns < 1 or space_betw < 0:
00181         raise "Error", "invalid parameters"
00182     if N == 0:
00183         return [""]
00184     num_rows = N / num_columns + (N % num_columns != 0)
00185     for row in xrange(num_rows):
00186         str = ""
00187         for column in xrange(num_columns):
00188             ix = num_rows * column + row
00189             if 0 <= ix <= (N-1):
00190                 if len(list[ix]) > col_width:
00191                     if truncate:
00192                         str = str + list[ix][:col_width] + " "*space_betw
00193                     else:
00194                         raise "Error", "element %d too long" % ix
00195                 else:
00196                     str = str + list[ix] + " " * (col_width - len(list[ix]))                           + " " * space_betw
00197         lines.append(str) 
00198     assert(len(lines) == num_rows)
00199     return lines
00200 
00201 ##
00202 # 
00203 #     Implements a debug class that can be useful in printing debugging
00204 #     information.
00205 #     
00206 class Debug:
00207 
00208     def __init__(self, fd=sys.stderr, add_nl=1, prefix=" + "):
00209         self.fd = fd
00210         self.debug_on = 1
00211         self.add_nl = add_nl
00212         self.prefix = prefix
00213 
00214     def Print(self, str):
00215         if self.debug_on:
00216             str = self.prefix + str
00217             if self.add_nl:
00218                 str = str + "\n"
00219             self.fd.write(str)
00220         else:
00221             pass
00222 
00223     def on(self):
00224         self.debug_on = 1
00225         
00226     def off(self):
00227         self.debug_on = 0
00228 
00229 def Time():
00230     import time
00231     return time.ctime(time.time())
00232 
00233 ##
00234 # Returns the wire diameter in inches given the AWG gauge 
00235 #     number (Brown and Sharpe gauge).
00236 #     
00237 def AWG(n):
00238     import math
00239     if n < 0 or n > 40:
00240         raise "AWG argument out of range"
00241     return 1000*(.46/math.pow(92, (n+3.)/39))
00242 
00243 ##
00244 # Rounds a floating point number up or down (default) so that
00245 #     the mantissa is 1, 2, or 5.  Returns 0.0 if the number is 0.  Taken
00246 #     from a HP200 series computer algorithm I wrote in June of 1984.
00247 #     
00248 def NiceRound(X, Up=0):
00249     x = float(X)
00250     s = "%13.11e" % abs(x)
00251     a = float(s[0:13])
00252     exp = float("1.0" + s[13:18])
00253     sgn = 1.0 - 2*(X < 0)
00254     towards_zero = 0
00255     if (x > 0 and not Up) or (x < 0 and Up):
00256         towards_zero = 1
00257     if towards_zero == 0:
00258         if a == 1:
00259             pass
00260         elif a <= 2.0:
00261             a = 2.0
00262         elif a <= 5.0:
00263             a = 5.0
00264         elif a < 10.0:
00265             a = 10.0
00266     else:
00267         if a == 10:
00268             pass
00269         elif a >= 5.0:
00270             a = 5.0
00271         elif a >= 2.0:
00272             a = 2.0
00273         elif a > 1.0:
00274             a = 1.0
00275     return sgn * a * exp
00276 
00277 ##
00278 # Returns a tuple (sign, mantissa, exponent) of a floating point
00279 #     number.
00280 #     
00281 def SignMantissaExponent(X):
00282     digits = 15
00283     str = ("%%.%de" % digits) % abs(float(X))
00284     return (1-2*(X<0), float(str[0:digits+2]), int(str[digits+3:]))
00285 
00286 ##
00287 # Returns a string representing the number value rounded to
00288 #     a specified number of significant figures.  The number is
00289 #     converted to a string, then rounded and returned as a string.
00290 #     If you want it back as a number, use float() on the string.
00291 #     
00292 def SignificantFiguresS(value, figures=3):
00293     if figures < 1 or figures >15:
00294         raise "Number of significant figures must be >= 1 and <= 15"
00295     sign, mantissa, exponent = SignMantissaExponent(float(value))
00296     fmt = "%%.%df" % (figures-1)
00297     str = ""
00298     if sign < 0:
00299         str = "-"
00300     return str + (fmt % mantissa) + ("e%+04d" % exponent)
00301 
00302 ##
00303 # Rounds a value to specified number of significant figures.
00304 #     This function returns a float.
00305 #     
00306 def SignificantFigures(value, figures=3):
00307     return float(SignificantFiguresS(value, figures))
00308 
00309 ##
00310 # Converts degrees C to degrees F.
00311 #     
00312 def C2F(c):
00313     if c <= -273.15:
00314         raise "Temperature too low"
00315     return 9./5*c + 32
00316 
00317 ##
00318 # Converts degrees C to degrees F.
00319 #     
00320 def F2C(f):
00321     c = (f-32.)*5/9
00322     if c <= -273.15:
00323         raise "Temperature too low"
00324     return c
00325 
00326 
00327 

© Copyright 2008-2009 Vyper Logix Corp., All Right Reserved; If you reference this document or any part of this document you must use the citation verbatim (including the link) "© Copyright 2008-2009 Vyper Logix Corp., All Right Reserved."

Notice: This source code contained in this document is NOT open source and is NOT being distributed as open source.

122,241 lines of code and growing...