def checkAdaptTrapsTypeErrorsOnConform(self): class Conformer: def __conform__(self, ob): return [] assert adapt(Conformer, list, None) is None assert adapt(Conformer(), list, None) == []
def chainLinker(obj, proto, default=None): """ A function that generates a chain used by, for instance invoke to get at all verb methods in an object. We can add more functionality here but it's probably best to keep it to a minimum. """ # First loop through the obj to see if it has any components adapted = adapt(obj, ISymbol, None) if adapted is not None: for com in adapted.components: for adapted in chainLinker(com, proto): yield adapted # Second try to adapt those components to the relevant protocol # This is the function that builds the chain even though it get's # passed through the above. adapted = adapt(obj, proto, None) if adapted is not None: yield adapted # Third add a default method. if default is not None: yield default
def chainLinker(obj, proto, default=None): """ A function that generates a chain used by, for instance invoke to get at all verb methods in an object. We can add more functionality here but it's probably best to keep it to a minimum. obj can be either a list or something that provides IDynamicComponentRack. """ # First loop through the obj to see if it has any components if type(obj) == type([]): for item in obj: adapted = adapt(item, IDynamicComponentRack, None) if adapted is not None: for com in adapted.components: for adapted in chainLinker(com, proto): yield adapted # Second try to adapt those components to the relevant protocol # This is the function that builds the chain even though it get's # passed through the above. else: adapted = adapt(obj, proto, None) if adapted is not None: yield adapted # Third add a default method. if default is not None: yield default
def insert(self, item): """Insert an item into the scene.""" protocols.adapt(item, ISceneItem) # if isinstance(item, worldobject.WorldObject): if isinstance(item, _core.WorldObject): self._worldroot.addChild(item) else: self.items.append(item)
def checkSimpleAdaptation(self): class Conformer: def __conform__(self,protocol): if protocol==42: return "hitchhiker",self class AdaptingProtocol: def __adapt__(klass,ob): return "adapted", ob __adapt__ = classmethod(__adapt__) c = Conformer() assert adapt(c,42,None) == ("hitchhiker",c) assert adapt(c,AdaptingProtocol,None) == ("adapted",c) assert adapt(42,AdaptingProtocol,None) == ("adapted",42) assert adapt(42,42,None) is None
def returns(check): '''Typecheck the returned value from a function. In python 2.4+, the typical use is in function decorators: >>> from typecheck import * >>> @returns(tupleOf(int, size=3)) ... def f(x): ... y = x+x; z = x*2 ... return y,z,y==z >>> f(5) (10, 10, True) >>> f([5]) Traceback (most recent call last): (...) TypeError: container<int> expected (([5, 5], [5, 5], True) given) @param check: L{TypeCheck}, type or class. @return: A higher-level function that accepts a function f for argument and returns a proxy of f that performs runtime type checking on f's returned value. ''' if not __debug__: return lambda func: func check = adapt(check, TypeCheck) def closure(func): def typecheckedFunc(*args, **kwds): r = func(*args, **kwds) check(r) return r return typecheckedFunc return closure
def __or__(self, other): ''' Make a new composite L{TypeCheck} that expresses the logical OR of its components (self and other). For example, a "number" pseudo-type can be defined as:: instanceOf(int) | instanceOf(float) | instanceOf(complex) @param other: The other L{TypeCheck} component. @type other: L{TypeCheck} @return: A L{TypeCheck} that accepts an object if and only if either component accepts it. @rtype: L{TypeCheck} ''' other = adapt(other, TypeCheck) class CompositeCheck(TypeCheck): def __call__(my, obj): try: self(obj) except TypeError: try: other(obj) except TypeError: raise TypeError("%s or %s expected (%s given)" % (self, other, _typename(obj))) def __str__(my): return "%s | %s" % (self, other) return CompositeCheck()
def _computeRules(self, memo=None): obs = [adapt(ob, IRule) for ob in self.initArgs] obs.reverse() closeAll = self.closingChars closeCtx = '' syn = [] self.__dict__.setdefault('rules', syn) if not memo: memo = {(id(self), closeAll): (self, self)} if obs: self.openingChars = obs[-1].getOpening('', memo) for ob in obs: terms = uniquechars(closeAll + closeCtx) key = id(ob), terms if key in memo: ob = memo[key][0] else: ob = ob.withTerminators(terms, memo) memo[key] = ob, self closeCtx = ob.getOpening(closeCtx, memo) syn.append(ob) self.openingChars = closeCtx syn.reverse() self.rules = syn return syn
def __init__(self, key=object, value=object): ''' @param key: The check for the mapping's keys. @param value: The check for the mapping's values. @type key,value: L{TypeCheck}, type or class. ''' keyCheck, valueCheck = [ adapt(check, TypeCheck) for check in key, value ] typesStr = ["*", "*"] if value is object: # 1. check only keys typesStr[0] = str(keyCheck) verify = containerOf(key).__call__ self._verify = lambda mapping: verify(mapping.iterkeys()) else: typesStr[1] = str(valueCheck) if key is object: # 2. check only values verify = containerOf(value).__call__ self._verify = lambda mapping: verify(mapping.itervalues()) else: # 3. check both keys and values typesStr[0] = str(keyCheck) def verify(obj): for k, v in obj.iteritems(): keyCheck(k) valueCheck(v) self._verify = verify self._itemTypeStr = ",".join(typesStr)
def getListing(dir=None): """ a function that returns a generator of language modules. Each item returned consists of a language name and a module. """ lang = pub.interfaces.ILangMod if dir == None: pubdir = os.path.split(os.path.abspath(pub.__file__))[0] dir = os.path.join(pubdir, "lang/") if pub.debugging: print dir dirlist = os.walk(dir).next()[1] # a list of dirs if pub.debugging: print dirlist for item in dirlist: if pub.debugging: print item if item[-4:] == 'Lang': x = "pub/lang/" + item if pub.debugging: print x i = adapt(__import__(x, globals, locals), lang, None) if i != None: if pub.debugging: print i yield i.name, i
def getListing(dir=None): """ a function that returns a generator of language modules. Each item returned consists of a language name and a module. """ lang = pub.interfaces.ILangMod if dir == None: pubdir = os.path.split(os.path.abspath(pub.__file__))[0] dir = os.path.join(pubdir, "lang/") if pub.debugging: print dir dirlist = os.walk(dir).next()[1] # a list of dirs if pub.debugging: print dirlist for item in dirlist: if pub.debugging: print item if item[-4:] == 'Lang': x = "pub/lang/"+item if pub.debugging: print x i = adapt(__import__(x, globals, locals), lang, None) if i != None: if pub.debugging: print i yield i.name, i
def obtain(obj,proto,default=None): """ Minimal interface to chainLinker that simply finds out if an object has a component that matches the protocol and returns it. If there are more or less than one an error is raised. """ adapted = adapt(obj, IDynamicComponentRack, default) if adapted is not None: for com in adapted.components: com = adapt(com, proto, None) if com is not None: # The first match is returned return com else: return False else: return False
def _add(self, obj, categorybits, collidebits): if isinstance(obj, ODEJointBase): obj.activate(self) self.joints.append(obj) return try: obj = protocols.adapt(obj, IRigidBody) except NotImplementedError: print 'Object "%s" is not a rigid body.'%obj.name return # Should the object be ignored? if not obj.dynamics: return # print "#####################",obj.name,"#########################" # print "Old center of gravity:",obj.cog # print "Old inertiatensor:" # print obj.inertiatensor # print "Old Offset transform:" P = obj.getOffsetTransform() # print P obj.pivot = P*obj.cog # print "Setting pivot to", obj.pivot # print "New center of gravity:", obj.cog # print "Intermediate inertia tensor:" # print obj.inertiatensor # I = obj.inertiatensor # a = numarray.array([I.getRow(0), I.getRow(1), I.getRow(2)], type=numarray.Float64) # vals, vecs = numarray.linear_algebra.eigenvectors(a) # print "Eigenvalues:",vals # Eigenvektoren sind ungenau! (bei cube_base_cog grosse Abweichungen) # b1 = vec3(vecs[0]).normalize() # b2 = vec3(vecs[1]).normalize() # b3 = vec3(vecs[2]).normalize() # P = obj.getOffsetTransform() # Pnull = P*vec3(0,0,0) # b1 = P*b1 - Pnull # b2 = P*b2 - Pnull # b3 = P*b3 - Pnull # I2 = mat3(b1,b2,b3) # print I2 # if I2.determinant()<0: # I2.setColumn(0, -I2.getColumn(0)) # print "Det of new basis",I2.determinant() # P = obj.getOffsetTransform() # P.setMat3(I2) # obj.setOffsetTransform(P) # print "New offset transform:" # print P # print "New center of gravity:",obj.cog # print "New inertia tensor:" # print obj.inertiatensor body = ODEBody(obj, self, categorybits=categorybits, collidebits=collidebits) self.bodies.append(body) self.body_dict[obj] = body
def __init__(self, *__args, **__kw): if len(__args) <> 1: return self.__init__(Sequence(*__args), **__kw) self.__dict__.update(__kw) self.initArgs = __args self.sep = adapt(self.separator, IRule) if 'closingChars' not in self.__dict__: self.closingChars = self.sep.getOpening('', {})
def checkSimpleAdaptation(self): class Conformer: def __conform__(self, protocol): if protocol == 42: return "hitchhiker", self class AdaptingProtocol: def __adapt__(klass, ob): return "adapted", ob __adapt__ = classmethod(__adapt__) c = Conformer() assert adapt(c, 42, None) == ("hitchhiker", c) assert adapt(c, AdaptingProtocol, None) == ("adapted", c) assert adapt(42, AdaptingProtocol, None) == ("adapted", 42) assert adapt(42, 42, None) is None
def __init__(self, *itemChecks): ''' @param itemChecks: Each itemCheck specifies the check for the respective field of the record. @type itemChecks: Sequence of L{typechecks <TypeCheck>}, types or classes. ''' self._itemChecks = [adapt(check, TypeCheck) for check in itemChecks]
def obtain(obj, proto, default=None): """ Minimal interface to chainLinker that simply finds out if an object has a component that matches the protocol and returns it. If there are more or less than one an error is raised. """ adapted = adapt(obj, IDynamicComponentRack, default) if adapted is not None: for com in adapted.components: com = adapt(com, proto, None) if com is not None: # The first match is returned return com else: return False else: return False
def checkStickyAdapter(self): class T: pass t = T() class I(Interface): pass from protocols.adapters import StickyAdapter class A(StickyAdapter): attachForProtocols = I, advise(instancesProvide=[I], asAdapterForTypes=[T]) a = I(t) assert adapt(t, I) is a assert a.subject is t n = T() a2 = I(n) assert a2 is not a assert a2.subject is n assert adapt(n, I) is a2
def __init__(self, itemCheck, size=None): ''' @param itemCheck: The check for the container's items. @type itemCheck: L{TypeCheck}, type or class. @param size: If not None, constrains the container's size. @type size: None, int (for exact size) or a predicate f(n) that returns True if a container of size n is valid. ''' self._itemCheck = adapt(itemCheck, TypeCheck) self._size = size
def checkAdaptFiltersTypeErrors(self): class Nonconformist: def __conform__(self, ob): raise TypeError("You got me!") class Unadaptive: def __adapt__(self, ob): raise TypeError("You got me!") # These will get a type errors calling __conform__/__adapt__ # but should be ignored since the error is at calling level assert adapt(None, Unadaptive, None) is None assert adapt(Nonconformist, None, None) is None # These will get type errors internally, and the error should # bleed through to the caller self.assertTypeErrorPassed(None, Unadaptive(), None) self.assertTypeErrorPassed(Nonconformist(), None, None) self.assertRaises(AdaptationFailure, adapt, None, None)
def typecheck(vars=None, **checkedVars): '''Typecheck a set of named variables. Example: >>> from typecheck import * >>> def f(x,y): ... typecheck(x=str, y=listOf(int)) >>> f('1',[2,3]) >>> f(1,[2,3]) Traceback (most recent call last): (...) TypeError: str expected (int given) >>> f('1',(2,3)) Traceback (most recent call last): (...) TypeError: list expected (tuple given) >>> f('1',[2,'3']) Traceback (most recent call last): (...) TypeError: container<int> expected ([2, '3'] given) @param vars: Dictionary of a scope's variables, with the variables' names for keys and the respective variable values for values. By default, it is set to the locals of the caller's frame. @param checkedVars: A set of C{var=typecheck} keyword arguments for the variables to be typechecked. @raise TypeError: If any L{TypeCheck} fails. @raise ValueError: If a variable in checkedVars is not in vars. ''' if vars is None: import sys vars = sys._getframe(1).f_locals for var, check in checkedVars.iteritems(): try: value = vars[var] except KeyError: raise ValueError("Unknown variable '%s'" % var) else: adapt(check, TypeCheck)(value)
def parse(input, rule): out = [] input = adapt(input, IInput) state = rule.parse(input, out.append, input.startState()) if isinstance(state, ParseError): raise state if not input.finished(state): raise ParseError("Expected EOF, found %r at position %d in %r" % (input[state:], state, input)) return dict(out)
def autoAdd(self): scene = getScene() # Add all rigid bodies first... for obj in scene.worldRoot().iterChilds(): if obj not in self.body_dict: try: obj = protocols.adapt(obj, IRigidBody) self.add(obj) except NotImplementedError: pass # Then add all joints... for obj in scene.worldRoot().iterChilds(): if obj not in self.joints: if isinstance(obj, cgkit.odedynamics.ODEJointBase): self.add(obj)
def lingo(lang, cls, args = []): """ method to access a couple of dictionaries and dig out a language and subsequently a specific class. lang should be a string like 'english' or 'swedish' cls should be a string containing something like 'parser' """ try: temp = pub.lang.mods[lang.lower()] # a language module except KeyError: raise pub.errors.PubError, "Language doesn't exist." if adapt(temp, ILangMod, None) != None: try: out = temp.get[cls.lower()] # get the named class except KeyError: raise pub.errors.PubError, "Can't find class" return out(*args) # if args is not empty args will be passed.
def _computeRule(self, memo=None): rule = self.rule = adapt(self.initArgs[0], IRule) closeAll = uniquechars(self.closingChars) if not memo: memo = {(id(self), closeAll): (self, self)} key = id(rule), closeAll if key in memo: rule = memo[key][0] else: rule = rule.withTerminators(closeAll, memo) memo[key] = rule, self return rule
def lingo(lang, cls, args=[]): """ method to access a couple of dictionaries and dig out a language and subsequently a specific class. lang should be a string like 'english' or 'swedish' cls should be a string containing something like 'parser' """ try: temp = pub.lang.mods[lang.lower()] # a language module except KeyError: raise pub.errors.PubError, "Language doesn't exist." if adapt(temp, ILangMod, None) != None: try: out = temp.get[cls.lower()] # get the named class except KeyError: raise pub.errors.PubError, "Can't find class" return out(*args) # if args is not empty args will be passed.
def _boostedMeta(meta, name, cdict): classAttrs = dict([(k, v.binding) for (k, v) in cdict.items() if v is not None and adapt(v, classAttr, None) is v]) if not classAttrs: return meta, None stdAttrs = dict(cdict) map(stdAttrs.__delitem__, classAttrs) classAttrs['__module__'] = stdAttrs.get('__module__') if meta is ClassType: meta = type metameta = type(meta) if metameta is type: metameta = Activator # Ensure that all subclasses are activated, too meta = metameta(name + 'Class', (meta, ), classAttrs) return meta, stdAttrs
def __and__(self, other): ''' Make a new composite L{TypeCheck} that expresses the logical AND of its components (self and other). For example, a "list of strings" pseudo-type could be defined as:: instanceOf(list) & containerOf(str) @param other: The other L{TypeCheck} component. @type other: L{TypeCheck} @return: A L{TypeCheck} that accepts an object if and only if both components accept it. @rtype: L{TypeCheck} ''' other = adapt(other, TypeCheck) class CompositeCheck(TypeCheck): def __call__(my, obj): self(obj) other(obj) def __str__(my): return "%s & %s" % (self, other) return CompositeCheck()
def _add(self, obj, categorybits, collidebits): if isinstance(obj, ODEJointBase): obj.activate(self) self.joints.append(obj) return try: obj = protocols.adapt(obj, IRigidBody) except NotImplementedError: print 'Object "%s" is not a rigid body.' % obj.name return # Should the object be ignored? if not obj.dynamics: return # print "#####################",obj.name,"#########################" # print "Old center of gravity:",obj.cog # print "Old inertiatensor:" # print obj.inertiatensor # print "Old Offset transform:" P = obj.getOffsetTransform() # print P obj.pivot = P * obj.cog # print "Setting pivot to", obj.pivot # print "New center of gravity:", obj.cog # print "Intermediate inertia tensor:" # print obj.inertiatensor # I = obj.inertiatensor # a = numarray.array([I.getRow(0), I.getRow(1), I.getRow(2)], type=numarray.Float64) # vals, vecs = numarray.linear_algebra.eigenvectors(a) # print "Eigenvalues:",vals # Eigenvektoren sind ungenau! (bei cube_base_cog grosse Abweichungen) # b1 = vec3(vecs[0]).normalize() # b2 = vec3(vecs[1]).normalize() # b3 = vec3(vecs[2]).normalize() # P = obj.getOffsetTransform() # Pnull = P*vec3(0,0,0) # b1 = P*b1 - Pnull # b2 = P*b2 - Pnull # b3 = P*b3 - Pnull # I2 = mat3(b1,b2,b3) # print I2 # if I2.determinant()<0: # I2.setColumn(0, -I2.getColumn(0)) # print "Det of new basis",I2.determinant() # P = obj.getOffsetTransform() # P.setMat3(I2) # obj.setOffsetTransform(P) # print "New offset transform:" # print P # print "New center of gravity:",obj.cog # print "New inertia tensor:" # print obj.inertiatensor body = ODEBody(obj, self, categorybits=categorybits, collidebits=collidebits) self.bodies.append(body) self.body_dict[obj] = body
def checkAdaptHandlesIsInstance(self): assert adapt([1,2,3],list,None) == [1,2,3] assert adapt('foo',str,None) == 'foo' assert adapt('foo',list,None) is None
def __init__(self, *alternatives): self.alternatives = [adapt(a, IRule) for a in alternatives]
def assertTypeErrorPassed(self, *args): try: # This should raise TypeError internally, and be caught adapt(*args) except TypeError, v: assert v.args == ("You got me!", )
def checkAdaptHandlesIsInstance(self): assert adapt([1, 2, 3], list, None) == [1, 2, 3] assert adapt('foo', str, None) == 'foo' assert adapt('foo', list, None) is None
def getPositionalArgs(ob): return adapt(ob, ISignature).getPositionalArgs()
def __init__(self, ob): self.funcSig = adapt(ob.im_func, ISignature) self.offset = ob.im_self is not None self.subject = ob
def __init__(self, name="ODEDynamics", gravity = 9.81, substeps = 1, cfm = None, erp = None, defaultcontactproperties = None, enabled = True, show_contacts = False, contactmarkersize = 0.1, contactnormalsize = 1.0, collision_events = False, auto_add = False, auto_insert=True): """Constructor. \param name (\c str) Component name \param auto_add (\c bool) Automatically add the world objects to the simulation \param auto_insert (\c bool) Automatically add the component to the scene """ Component.__init__(self, name=name, auto_insert=auto_insert) scene = getScene() self.substeps = substeps self.collision_events = collision_events self.world = ode.World() g = -gravity*scene.up self.world.setGravity(g) if cfm!=None: self.world.setCFM(cfm) if erp!=None: self.world.setERP(erp) # self.world.setAutoDisableFlag(True) self.enabled = enabled self.eventmanager = eventManager() self.eventmanager.connect(STEP_FRAME, self) self.eventmanager.connect(RESET, self.reset) # Space object self.space = ode.Space() # Joint group for the contact joints self.contactgroup = ode.JointGroup() # A dictionary with WorldObjects as keys and ODEBodies as values self.body_dict = {} # A list of all bodies self.bodies = [] # A list of all joints self.joints = [] # A dictionary with contact properties # Key is a 2-tuple (material1, material2). Value is a # ODEContactProperties object. # The value of (mat1, mat2) should always be the same than # the value of (mat2, mat1). self.contactprops = {} # Default contact properties if defaultcontactproperties==None: defaultcontactproperties = ODEContactProperties() self.defaultcontactprops = defaultcontactproperties self.show_contacts = show_contacts self.contactmarkersize = contactmarkersize self.contactnormalsize = contactnormalsize # A list of weakrefs to body manipulators self.body_manips = [] # Debug statistics (the number of contacts per simulation step) self.numcontacts = 0 # Automatically add world objects if auto_add: # Add all rigid bodies first... for obj in scene.worldRoot().iterChilds(): try: obj = protocols.adapt(obj, IRigidBody) self.add(obj) except NotImplementedError: pass # Then add all joints... for obj in scene.worldRoot().iterChilds(): if isinstance(obj, ODEJointBase): self.add(obj)
def __init__(self, name="ODEDynamics", gravity=9.81, substeps=1, cfm=None, erp=None, defaultcontactproperties=None, enabled=True, show_contacts=False, contactmarkersize=0.1, contactnormalsize=1.0, collision_events=False, auto_add=False, auto_insert=True): """Constructor. \param name (\c str) Component name \param auto_add (\c bool) Automatically add the world objects to the simulation \param auto_insert (\c bool) Automatically add the component to the scene """ Component.__init__(self, name=name, auto_insert=auto_insert) scene = getScene() self.substeps = substeps self.collision_events = collision_events self.world = ode.World() g = -gravity * scene.up self.world.setGravity(g) if cfm != None: self.world.setCFM(cfm) if erp != None: self.world.setERP(erp) # self.world.setAutoDisableFlag(True) self.enabled = enabled self.eventmanager = eventManager() self.eventmanager.connect(STEP_FRAME, self) self.eventmanager.connect(RESET, self.reset) # Space object self.space = ode.Space() # Joint group for the contact joints self.contactgroup = ode.JointGroup() # A dictionary with WorldObjects as keys and ODEBodies as values self.body_dict = {} # A list of all bodies self.bodies = [] # A list of all joints self.joints = [] # A dictionary with contact properties # Key is a 2-tuple (material1, material2). Value is a # ODEContactProperties object. # The value of (mat1, mat2) should always be the same than # the value of (mat2, mat1). self.contactprops = {} # Default contact properties if defaultcontactproperties == None: defaultcontactproperties = ODEContactProperties() self.defaultcontactprops = defaultcontactproperties self.show_contacts = show_contacts self.contactmarkersize = contactmarkersize self.contactnormalsize = contactnormalsize # A list of weakrefs to body manipulators self.body_manips = [] # Debug statistics (the number of contacts per simulation step) self.numcontacts = 0 # Automatically add world objects if auto_add: # Add all rigid bodies first... for obj in scene.worldRoot().iterChilds(): try: obj = protocols.adapt(obj, IRigidBody) self.add(obj) except NotImplementedError: pass # Then add all joints... for obj in scene.worldRoot().iterChilds(): if isinstance(obj, ODEJointBase): self.add(obj)
def checkAdaptHandlesIsInstance(self): assert adapt([1, 2, 3], list, None) == [1, 2, 3] assert adapt("foo", str, None) == "foo" assert adapt("foo", list, None) is None
def assertTypeErrorPassed(self, *args): try: # This should raise TypeError internally, and be caught adapt(*args) except TypeError, v: assert v.args == ("You got me!",)