/timm's /charming /python /tricks

lib.py

Download lib.py.
Read more on How to be Charming (in Python).


001: import sys,time,random,re,math
002: sys.dont_write_bytecode=True # don't make .pyc files
003: from the import *
004: from demo import *
005: 
006: #---- Standard maths stuff -------------------------
007: 
008: e = math.e
009: log = math.log
010: any = random.uniform
011: rand = random.random
012: shuffle = random.shuffle
013: 
014: def weibull(x,l,k):
015:   if x <= 0: return 0
016:   k *= 1.0; x *= 1.0; l *= 1.0
017:   return k/l*((x/l)**(k-1))*e**(-1*(x/l)**k)
018: 
019: #---- Collection stuff -----------------------------
020: 
021: def first(x) : return x[0]
022: def second(x): return x[1]
023: 
024: def mostest(d, sortBy=second,reverse=True):
025:   "Return a dictionary string, sorted by values."
026:   l = [(k,v) for k,v in sorted(d.items())]
027:   l = sorted(l,key= sortBy,reverse=reverse)
028:   l = [':%s %s' % (k,v) for k,v in l]
029:   return ' '.join(l)
030: 
031: def median(l,ordered=False):
032:   if not ordered:
033:     lst = sorted(l)
034:   n = len(l)
035:   i = n/2
036:   return l[i] if n % 2 else (l[i] + l[i+1])/2.0
037: 
038: def pairs(lst):
039:   last=lst[0]
040:   for i in lst[1:]:
041:     yield last,i
042:     last = i
043: 
044: class AutoDict(dict):
045:   def __init__(i,default):
046:     i.default= default
047:   def __getitem__(i,key):
048:     if key in i:
049:       return i.get(key)
050:     return i.setdefault(key,i.default())
051: 
052: 
053: class Deep(dict):
054:   def __getitem__(i, item):  
055:     try:
056:       return dict.__getitem__(i, item)
057:     except KeyError:
058:       value = self[item] = type(i)()
059:       return value
060: 
061: #---- timing --------------------------
062: def msecs(f):
063:   t1 = time.time()
064:   f()
065:   return (time.time() - t1)*1000.0
066: 
067: #---- Stochastic sampling --------------------------
068: 
069: def resetSeed(n=The.math.seed): 
070:    """
071:    Important: before running any code
072:    that does any random sampling, reset the
073:    seed (so you can debug crashes)
074:    """
075:    random.seed(n)
076: 
077: def one(lst) :
078:   "Return any one item in a list"
079:   return lst[int(any(0,len(lst)))]
080: 
081: def few(lst,n):
082:   "Return any n items in a list, no repeats."
083:   m = len(lst)
084:   where = []
085:   for _ in range(n*5): # try a few times
086:     x = int(any(0,m))
087:     if not x in where: where += [x]
088:     if len(where) == n: break
089:   return [lst[x] for x in where]
090: 
091: def some(d,enough=10**32):
092:   """
093:   Given a dictionary d{k1=n1, k2=n2, ...},
094:   return enough keys ki at probability 
095:   pi = ni/n where n = n1+n2+..
096:   e.g.
097:      for key in some({'box':30,'circle':20,'line':10},20)
098:          print key
099:   
100:   will return around twice as many boxes as anything else,
101:   circles 1/3rd of the time and lines 1/6th of the time. 
102:   """
103:   n, lst = 0, []
104:   for x in d: 
105:     n   += d[x]
106:     lst += [(d[x],x)]
107:   lst = sorted(lst, reverse=True)
108:   while enough > 0:
109:     r = random.random()
110:     for freq,thing in lst:
111:       r -= freq*1.0/n
112:       if r <= 0:
113:         yield thing
114:         enough -= 1
115:         break
116: 
117: #---- Print stuff ----------------------------------
118: 
119: def gs(lst,f='%4.3f'):
120:   "Print a list of numbers in abbreviated format." 
121:   return ', '.join([f % x for x in lst])
122: 
123: def say(*lst):
124:   """"Write n arguments to standard output with 
125:    no new line at the end."""
126:   sys.stdout.write(','.join(map(str,lst)))
127:   sys.stdout.flush()
128: 
129: #---- Iterators  ---------------------------------
130: 
131: def item(x) : 
132:   "Return all non-list items in a nested list"
133:   if isinstance(x,(tuple,list)):
134:     for y in x:
135:       for z in item(y): yield z
136:   else: yield x
137: 
138: #---- plotting  ---------------------------------
139: 
140: def plot2d(x,y,xlabel="x",ylabel="y",
141:              title="Plot",file=None,
142:              width=3,
143:              height=3):
144:   "Print a 2d plot. If 'file' not given, show on screen"
145:   print title,file
146:   import matplotlib.pyplot as plt
147:   plt.xlabel(xlabel)
148:   plt.ylabel(ylabel)
149:   plt.title(title)
150:   plt.gcf().set_size_inches(width,height)
151:   plt.plot(x, y, 'ro')
152:   plt.subplots_adjust(bottom=0.2,left=0.2)
153:   plt.savefig(file) if file else plt.show()
154: 
155: 

This file is part of Timm's charming Python tricks.
© 2014, Tim Menzies: tim.menzies@gmail.com, http://menzies.us.

Timm's charming Python tricks are free software: you can redistribute it and/or modify it under the terms of the GNU Lesser Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

Timm's charming Python tricks are distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU Lesser Public License along with Foobar. If not, see http://www.gnu.org/licenses.