From 5fb3ea060025241105dc8e9a174513c112f9a133 Mon Sep 17 00:00:00 2001 From: rcoh Date: Thu, 27 Jan 2011 16:50:59 -0500 Subject: A metric $#%$-ton of changes. Added doc-strings to EVERYTHING. Phew. Fixed a massive bug that increases performance in by up to a factor of 60. A bunch of new behaviors for the class. --- util/ColorOps.py | 5 +++++ util/Config.py | 26 ++++++++++++++++---------- util/Geo.py | 9 +++++++-- util/NetworkOps.py | 1 - util/PacketComposition.py | 9 ++++++++- util/Search.py | 6 +++--- util/TimeOps.py | 1 + 7 files changed, 40 insertions(+), 17 deletions(-) (limited to 'util') diff --git a/util/ColorOps.py b/util/ColorOps.py index 143444f..037957a 100644 --- a/util/ColorOps.py +++ b/util/ColorOps.py @@ -2,13 +2,17 @@ import random from util.TimeOps import Stopwatch def randomColor(): return [random.randint(0,255) for i in range(3)] + def chooseRandomColor(colorList): + """Given a list of colors, pick one at random""" return random.choice(colorList) def safeColor(c): + """Ensures that a color is valid""" c[0] = c[0] if c[0] < 255 else 255 c[1] = c[1] if c[1] < 255 else 255 c[2] = c[2] if c[2] < 255 else 255 return c + def combineColors(colors): result = [0,0,0] for c in colors: @@ -16,5 +20,6 @@ def combineColors(colors): result[1] += c[1] result[2] += c[2] return safeColor(result) + def multiplyColor(color, percent): return safeColor([channel*(percent) for channel in color]) diff --git a/util/Config.py b/util/Config.py index c2d8806..6fdb0d4 100644 --- a/util/Config.py +++ b/util/Config.py @@ -8,12 +8,14 @@ from logger import main_log, exception_log classArgsMem = {} CONFIG_PATH = 'config/' DEFAULT_OVERRIDE_MODE = 'Merge' + def loadParamRequirementDict(className): if not className in classArgsMem: #WOO CACHING classArgsMem[className] = fileToDict(CONFIG_PATH + className) return classArgsMem[className] -#Loads a config file. If its an xml file, inheritances are automatically resolved. + def loadConfigFile(fileName): #TODO: error handling etc. + """Loads a config file. If its an xml file, inheritances are automatically resolved.""" try: if '.params' in fileName: return fileToDict(fileName) @@ -26,17 +28,17 @@ def loadConfigFile(fileName): #TODO: error handling etc. main_log.error('Error loading config file ' + fileName)#, inst) TODO: log exception too main_log.error(str(inst)) return None -#Takes an Element or an ElementTree. If it is a tree, it returns its root. Otherwise, just returns -#it def getElement(el): + """Takes an Element or an ElementTree. If it is a tree, it returns its root. Otherwise, just returns + it""" if xml.etree.ElementTree.iselement(el): return el elif el.__class__ == ElementTree: return el.getroot() -#XML tree composition. Returns the resulting tree, but happens in-place in the overriding tree. -def compositeXMLTrees(parentTree, overridingTree): #TODO: break up into sub-methods, change it to -#use .find() - #type checking -- convert ElementTrees to their root elements +def compositeXMLTrees(parentTree, overridingTree): + """XML tree composition. Returns the resulting tree, but happens in-place in the overriding + tree.""" + #TODO: break up into sub-methods, change it to use .find() if parentTree == None: return overridingTree if overridingTree == None: @@ -75,8 +77,10 @@ def compositeXMLTrees(parentTree, overridingTree): #TODO: break up into sub-meth overrideItems.insert(-1, child) overrideItems.remove(item) return overridingTree + def findElementsByTag(tag, eList): return [el for el in eList if el.tag == tag] + def fileToDict(fileName): fileText = '' try: @@ -95,8 +99,9 @@ def fileToDict(fileName): except: exception_log.info(fileName + ' is not a well formed python dict. Parsing failed') return eval(fileText) -#parses arguments into python objects if possible, otherwise leaves as strings + def pullArgsFromItem(parentNode): + """Parses arguments into python objects if possible, otherwise leaves as strings""" attribArgs = {} for arg in parentNode.attrib: #automatically pull attributes into the argdict attribArgs[arg] = attemptEval(parentNode.attrib[arg]) @@ -112,6 +117,7 @@ def attemptEval(val): except (NameError, SyntaxError): val = str(val) return val + def generateArgDict(parentNode, recurse=False): args = {} for arg in parentNode.getchildren(): @@ -131,13 +137,13 @@ def generateArgDict(parentNode, recurse=False): if len(args.keys()) == 1 and recurse: return args[args.keys()[0]] return args -#In place resolution of document inheritances. Doesn't return anything. def resolveDocumentInheritances(el): + """In place resolution of document inheritances. Doesn't return anything.""" abstractMembers = Search.parental_tree_search(el, '.getchildren()', '.tag==\'InheritsFrom\'') for subel in abstractMembers: subel = resolveInheritance(subel) -#In place resolution of inheritence. Doesn't return anything. def resolveInheritance(el): + """In place resolution of inheritence. Doesn't return anything.""" parentClass = el.find('InheritsFrom') if parentClass != None: parentTree = loadConfigFile(parentClass.text) diff --git a/util/Geo.py b/util/Geo.py index be3e93e..05ea9fe 100644 --- a/util/Geo.py +++ b/util/Geo.py @@ -4,20 +4,25 @@ from bisect import * import random def pointWithinBoundingBox(point, bb): #this could be in 4 lines, but I'm lazy. return sum([(point[i % 2] <= bb[i]) == (i>1) for i in range(4)]) == 4 + def addLocations(l1,l2): return tuple([l1[i]+l2[i] for i in range(len(l1))]) + def gaussian(x,height,center,width): a=height b=center c=width return a*math.exp(-((x-b)**2)/(2*c**2)) + def dist(l1, l2): - return math.sqrt((l1[0]-l2[0])**2+(l1[1]-l2[1])**2) - #return math.sqrt(sum([(l1[i]-l2[i])**2 for i in range(len(l1))])) + return math.sqrt((l1[0]-l2[0])**2+(l1[1]-l2[1])**2) #For speed + def randomLoc(boundingBox): #TODO: make less shitty loc = [] loc.append(random.randint(0, boundingBox[0])) loc.append(random.randint(0, boundingBox[1])) return tuple(loc) + def approxexp(x): + """Approximates exp with a 3 term Taylor Series.""" return 1+x+x**2/2+x**3/6 diff --git a/util/NetworkOps.py b/util/NetworkOps.py index 6c50c6d..8894b78 100644 --- a/util/NetworkOps.py +++ b/util/NetworkOps.py @@ -8,4 +8,3 @@ def getConnectedSocket(ip,port): except Exception as inst: main_log.error('Network down. All network based renderers and sensors will not function.', inst) - print (ip, port) diff --git a/util/PacketComposition.py b/util/PacketComposition.py index c4fcdc3..7b4fe95 100644 --- a/util/PacketComposition.py +++ b/util/PacketComposition.py @@ -6,6 +6,7 @@ UNI = 0 import pdb import util.TimeOps as timeops argDict = {'flags': 0, 'startcode': 0, 'pad':0} + def composePixelStripData(pixelStrip,currentTime=timeops.time()): packet = bytearray() for light in pixelStrip: @@ -19,6 +20,7 @@ def composePixelStripData(pixelStrip,currentTime=timeops.time()): #color = pixelStrip.pixels[i].state() #packet[i:i+2] = color # return bytearray(packet) + cache = {} def memoize(f): def helper(x): @@ -26,6 +28,7 @@ def memoize(f): cache[x] = f(x) return cache[x] return helper + @memoize def cachePacketHeader(port): packet = bytearray() @@ -35,11 +38,13 @@ def cachePacketHeader(port): packet.extend(portOutPacket(subDict)) packet.append(0x0) return packet + def composePixelStripPacket(pixelStrip,port, currentTime): packet = bytearray(cachePacketHeader(port)) data = composePixelStripData(pixelStrip, currentTime) packet.extend(data) return packet + def packheader(): header = bytearray() header.extend(struct.pack('L', MAGIC)) @@ -47,18 +52,20 @@ def packheader(): header.extend(struct.pack('H', PORTOUT)) header.extend(struct.pack('L', 0)) return header + def portOut(): header = packheader() header.extend(struct.pack('L', UNI)) return header + def portOutPayload(argDict): payload = bytearray() payload.extend(struct.pack('B', argDict['port'])) payload.extend(struct.pack('H', argDict['flags'])) - #payload.append(0x00) #somepadding? lolwtf. payload.extend(struct.pack('H', argDict['len'])) payload.extend(struct.pack('H', argDict['startcode'])) return payload + def portOutPacket(payloadArgs): packet = bytearray() packet.extend(portOut()) diff --git a/util/Search.py b/util/Search.py index f7e4b81..1499e23 100644 --- a/util/Search.py +++ b/util/Search.py @@ -1,13 +1,13 @@ from bisect import * def find_le(a, x): - 'Find rightmost value less than or equal to x' + """Find rightmost value less than or equal to x""" return bisect_right(a, x)-1 def find_ge(a, x): - 'Find leftmost value greater than x' + """Find leftmost value greater than x""" return bisect_left(a, x) -#returns parents of nodes that meed a given condition def parental_tree_search(root, childrenstr, conditionstr): + """Returns parents of nodes that meed a given condition""" ret = [] queue = [root] while queue: diff --git a/util/TimeOps.py b/util/TimeOps.py index dcd5038..841efab 100644 --- a/util/TimeOps.py +++ b/util/TimeOps.py @@ -1,6 +1,7 @@ import time as clock def time(): return clock.time()*1000 #all times in MS + class Stopwatch: def __init__(self): self.running = False -- cgit v1.2.3