def apply_to_curve(self, verts, u_set, set_len=None, inc_pos=None): """ Apply this color scheme to a set of vertices over a single independent variable u. """ bounds = create_bounds() cverts = list() if callable(set_len): set_len(len(u_set)*2) # calculate f() = r,g,b for each vert # and find the min and max for r,g,b for _u in xrange(len(u_set)): if verts[_u] is None: cverts.append(None) else: x,y,z = verts[_u] u,v = u_set[_u], None c = self(x,y,z,u,v) if c is not None: c = list(c) update_bounds(bounds, c) cverts.append(c) if callable(inc_pos): inc_pos() # scale and apply gradient for _u in xrange(len(u_set)): if cverts[_u] is not None: for _c in xrange(3): # scale from [f_min, f_max] to [0,1] cverts[_u][_c] = rinterpolate(bounds[_c][0], bounds[_c][1], cverts[_u][_c]) # apply gradient cverts[_u] = self.gradient(*cverts[_u]) if callable(inc_pos): inc_pos() return cverts
def apply_to_curve(self, verts, u_set, set_len=None, inc_pos=None): """ Apply this color scheme to a set of vertices over a single independent variable u. """ bounds = create_bounds() cverts = list() if callable(set_len): set_len(len(u_set) * 2) # calculate f() = r,g,b for each vert # and find the min and max for r,g,b for _u in xrange(len(u_set)): if verts[_u] is None: cverts.append(None) else: x, y, z = verts[_u] u, v = u_set[_u], None c = self(x, y, z, u, v) if c is not None: c = list(c) update_bounds(bounds, c) cverts.append(c) if callable(inc_pos): inc_pos() # scale and apply gradient for _u in xrange(len(u_set)): if cverts[_u] is not None: for _c in xrange(3): # scale from [f_min, f_max] to [0,1] cverts[_u][_c] = rinterpolate(bounds[_c][0], bounds[_c][1], cverts[_u][_c]) # apply gradient cverts[_u] = self.gradient(*cverts[_u]) if callable(inc_pos): inc_pos() return cverts
def _calculate_verts(self): if self._calculating_verts.isSet(): return self._calculating_verts.set() try: self._on_calculate_verts() finally: self._calculating_verts.clear() if callable(self.bounds_callback): self.bounds_callback()
def check(a, check_attr=True): """ Check that pickling and copying round-trips. """ # The below hasattr() check will warn about is_Real in Python 2.5, so # disable this to keep the tests clean warnings.filterwarnings("ignore", ".*is_Real.*") protocols = [0, 1, 2, copy.copy, copy.deepcopy] # Python 2.x doesn't support the third pickling protocol if sys.version_info[0] > 2: protocols.extend([3]) for protocol in protocols: if callable(protocol): if isinstance(a, BasicType): # Classes can't be copied, but that's okay. return b = protocol(a) else: b = pickle.loads(pickle.dumps(a, protocol)) d1 = dir(a) d2 = dir(b) assert d1==d2 if not check_attr: continue def c(a, b, d): for i in d: if not hasattr(a, i) or i in excluded_attrs: continue attr = getattr(a, i) if not hasattr(attr, "__call__"): assert hasattr(b,i), i assert getattr(b,i) == attr c(a,b,d1) c(b,a,d2)
def check(a, check_attr=True): """ Check that pickling and copying round-trips. """ #FIXME-py3k: Add support for protocol 3. for protocol in [0, 1, 2, copy.copy, copy.deepcopy]: if callable(protocol): if isinstance(a, BasicType): # Classes can't be copied, but that's okay. return b = protocol(a) else: b = pickle.loads(pickle.dumps(a, protocol)) d1 = dir(a) d2 = dir(b) assert d1 == d2 if not check_attr: continue def c(a, b, d): for i in d: if not hasattr(a, i): continue attr = getattr(a, i) if not hasattr(attr, "__call__"): assert hasattr(b, i), i assert getattr(b, i) == attr c(a, b, d1) c(b, a, d2)
def check(a, check_attr=True): """ Check that pickling and copying round-trips. """ # The below hasattr() check will warn about is_Real in Python 2.5, so # disable this to keep the tests clean warnings.filterwarnings("ignore", ".*is_Real.*", DeprecationWarning) #FIXME-py3k: Add support for protocol 3. for protocol in [0, 1, 2, copy.copy, copy.deepcopy]: if callable(protocol): if isinstance(a, BasicType): # Classes can't be copied, but that's okay. return b = protocol(a) else: b = pickle.loads(pickle.dumps(a, protocol)) d1 = dir(a) d2 = dir(b) assert d1 == d2 if not check_attr: continue def c(a, b, d): for i in d: if not hasattr(a, i): continue attr = getattr(a, i) if not hasattr(attr, "__call__"): assert hasattr(b, i), i assert getattr(b, i) == attr c(a, b, d1) c(b, a, d2)
def check(a, check_attr = True): """ Check that pickling and copying round-trips. """ for protocol in [0, 1, 2, copy.copy, copy.deepcopy]: if callable(protocol): if isinstance(a, BasicType): # Classes can't be copied, but that's okay. return b = protocol(a) else: b = pickle.loads(pickle.dumps(a, protocol)) d1 = dir(a) d2 = dir(b) assert d1==d2 if not check_attr: continue def c(a,b,d): for i in d: if not hasattr(a,i): continue attr = getattr(a,i) if not hasattr(attr, "__call__"): assert hasattr(b,i), i assert getattr(b,i)==attr c(a,b,d1) c(b,a,d2)
def check(a, check_attr = True): """ Check that pickling and copying round-trips. """ # The below hasattr() check will warn about is_Real in Python 2.5, so # disable this to keep the tests clean warnings.filterwarnings("ignore", ".*is_Real.*", DeprecationWarning) #FIXME-py3k: Add support for protocol 3. for protocol in [0, 1, 2, copy.copy, copy.deepcopy]: if callable(protocol): if isinstance(a, BasicType): # Classes can't be copied, but that's okay. return b = protocol(a) else: b = pickle.loads(pickle.dumps(a, protocol)) d1 = dir(a) d2 = dir(b) assert d1==d2 if not check_attr: continue def c(a,b,d): for i in d: if not hasattr(a,i): continue attr = getattr(a,i) if not hasattr(attr, "__call__"): assert hasattr(b,i), i assert getattr(b,i)==attr c(a,b,d1) c(b,a,d2)
def _test_color_function(self): if not callable(self.f): raise ValueError("Color function is not callable.") try: result = self.f(0, 0, 0, 0, 0) assert len(result) == 3 except TypeError, te: raise ValueError("Color function needs to accept x,y,z,u,v, " "as arguments even if it doesn't use all of them.")
def example(i): if callable(i): p.clear() i() elif i >= 0 and i < len(examples): p.clear() examples[i]() else: print "Not a valid example.\n" print p
def draw(self): for f in self.predraw: if callable(f): f() if self.style_override: style = self.styles[self.style_override] else: style = self.styles[self._style] # Draw solid component if style includes solid if style & 2: dl = self._render_stack_top(self._draw_solid) if dl > 0 and GL_TRUE == glIsList(dl): self._draw_solid_display_list(dl) # Draw wireframe component if style includes wireframe if style & 1: dl = self._render_stack_top(self._draw_wireframe) if dl > 0 and GL_TRUE == glIsList(dl): self._draw_wireframe_display_list(dl) for f in self.postdraw: if callable(f): f()
def push_solid(self, function): """ Push a function which performs gl commands used to build a display list. (The list is built outside of the function) """ assert callable(function) self._draw_solid.append(function) if len(self._draw_solid) > self._max_render_stack_size: del self._draw_solid[1] # leave marker element
def _eval_args(cls, args): if len(args) != 2: raise QuantumError( 'Insufficient/excessive arguments to Oracle. Please ' + 'supply the number of qubits and an unknown function.') sub_args = args[0], sub_args = UnitaryOperator._eval_args(sub_args) if not sub_args[0].is_Integer: raise TypeError('Integer expected, got: %r' % sub_args[0]) if not callable(args[1]): raise TypeError('Callable expected, got: %r' % args[1]) sub_args = UnitaryOperator._eval_args(tuple(range(args[0]))) return (sub_args, args[1])
def _test_color_function(self): if not callable(self.f): raise ValueError("Color function is not callable.") try: result = self.f(0, 0, 0, 0, 0) assert len(result) == 3 except TypeError as te: raise ValueError("Color function needs to accept x,y,z,u,v, " "as arguments even if it doesn't use all of them.") except AssertionError as ae: raise ValueError("Color function needs to return 3-tuple r,g,b.") except Exception as ie: pass # color function probably not valid at 0,0,0,0,0
def _test_color_function(self): if not callable(self.f): raise ValueError("Color function is not callable.") try: result = self.f(0, 0, 0, 0, 0) assert len(result) == 3 except TypeError as te: raise ValueError( "Color function needs to accept x,y,z,u,v, " "as arguments even if it doesn't use all of them.") except AssertionError as ae: raise ValueError("Color function needs to return 3-tuple r,g,b.") except Exception as ie: pass # color function probably not valid at 0,0,0,0,0
def _render_stack_top(self, render_stack): top = render_stack[-1] if top == -1: return -1 # nothing to display elif callable(top): dl = self._create_display_list(top) render_stack[-1] = (dl, top) return dl # display newly added list elif len(top) == 2: if GL_TRUE == glIsList(top[0]): return top[0] # display stored list dl = self._create_display_list(top[1]) render_stack[-1] = (dl, top[1]) return dl # display regenerated list
def _eval_args(cls, args): if len(args) != 2: raise QuantumError( 'Insufficient/excessive arguments to Oracle. Please ' + 'supply the number of qubits and an unknown function.' ) sub_args = args[0], sub_args = UnitaryOperator._eval_args(sub_args) if not sub_args[0].is_Integer: raise TypeError('Integer expected, got: %r' % sub_args[0]) if not callable(args[1]): raise TypeError('Callable expected, got: %r' % args[1]) sub_args = UnitaryOperator._eval_args(tuple(range(args[0]))) return (sub_args, args[1])
def get_class(lookup_view): """ Convert a string version of a class name to the object. For example, get_class('sympy.core.Basic') will return class Basic located in module sympy.core """ if isinstance(lookup_view, str): lookup_view = lookup_view mod_name, func_name = get_mod_func(lookup_view) if func_name != "": lookup_view = getattr(__import__(mod_name, {}, {}, [""]), func_name) if not callable(lookup_view): raise AttributeError("'%s.%s' is not a callable." % (mod_name, func_name)) return lookup_view
def get_class(lookup_view): """ Convert a string version of a class name to the object. For example, get_class('sympy.core.Basic') will return class Basic located in module sympy.core """ if isinstance(lookup_view, str): lookup_view = lookup_view mod_name, func_name = get_mod_func(lookup_view) if func_name != '': lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name) if not callable(lookup_view): raise AttributeError("'%s.%s' is not a callable." % (mod_name, func_name)) return lookup_view
def get_class(lookup_view): """ Convert a string version of a class name to the object. For example, get_class('sympy.core.Basic') will return class Basic located in module sympy.core """ if isinstance(lookup_view, str): # Bail early for non-ASCII strings (they can't be functions). lookup_view = lookup_view.encode('ascii') mod_name, func_name = get_mod_func(lookup_view) if func_name != '': lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name) if not callable(lookup_view): raise AttributeError("'%s.%s' is not a callable." % (mod_name, func_name)) return lookup_view
def __init__(self, *args, **kwargs): self.args = args self.f, self.gradient = None, ColorGradient() if len(args) == 1 and not isinstance(args[0], Basic) and callable(args[0]): self.f = args[0] elif len(args) == 1 and isinstance(args[0], str): if args[0] in default_color_schemes: cs = default_color_schemes[args[0]] self.f, self.gradient = cs.f, cs.gradient.copy() else: self.f = lambdify('x,y,z,u,v', args[0]) else: self.f, self.gradient = self._interpret_args(args, kwargs) self._test_color_function() if not isinstance(self.gradient, ColorGradient): raise ValueError("Color gradient not properly initialized. " "(Not a ColorGradient instance.)")
def atom_name(self, nodelist): name, lineno = nodelist[0][1:] if name in self.local_dict: name_obj = self.local_dict[name] return Const(name_obj, lineno=lineno) elif name in self.global_dict: name_obj = self.global_dict[name] if isinstance(name_obj, (Basic, type)) or callable(name_obj): return Const(name_obj, lineno=lineno) elif name in ['True', 'False']: return Const(eval(name), lineno=lineno) symbol_obj = Symbol(name) self.local_dict[name] = symbol_obj return Const(symbol_obj, lineno=lineno)
def check(a, exclude=[], check_attr=True): """ Check that pickling and copying round-trips. """ # The below hasattr() check will warn about is_Real in Python 2.5, so # disable this to keep the tests clean # XXX: Really? It *does* warn in 2.7.2 too. warnings.filterwarnings("ignore", category=SymPyDeprecationWarning) protocols = [0, 1, 2, copy.copy, copy.deepcopy] # Python 2.x doesn't support the third pickling protocol if sys.version_info[0] > 2: protocols.extend([3]) for protocol in protocols: if protocol in exclude: continue if callable(protocol): if isinstance(a, BasicType): # Classes can't be copied, but that's okay. return b = protocol(a) else: b = pickle.loads(pickle.dumps(a, protocol)) d1 = dir(a) d2 = dir(b) assert set(d1) == set(d2) if not check_attr: continue def c(a, b, d): for i in d: if not hasattr(a, i) or i in excluded_attrs: continue attr = getattr(a, i) if not hasattr(attr, "__call__"): assert hasattr(b, i), i assert getattr( b, i) == attr, "%s != %s" % (getattr(b, i), attr) c(a, b, d1) c(b, a, d2) warnings.filterwarnings("default", category=SymPyDeprecationWarning)
def check(a, exclude=[], check_attr=True): """ Check that pickling and copying round-trips. """ # The below hasattr() check will warn about is_Real in Python 2.5, so # disable this to keep the tests clean # XXX: Really? It *does* warn in 2.7.2 too. warnings.filterwarnings("ignore", category=SymPyDeprecationWarning) protocols = [0, 1, 2, copy.copy, copy.deepcopy] # Python 2.x doesn't support the third pickling protocol if sys.version_info[0] > 2: protocols.extend([3]) for protocol in protocols: if protocol in exclude: continue if callable(protocol): if isinstance(a, BasicType): # Classes can't be copied, but that's okay. return b = protocol(a) else: b = pickle.loads(pickle.dumps(a, protocol)) d1 = dir(a) d2 = dir(b) assert set(d1) == set(d2) if not check_attr: continue def c(a, b, d): for i in d: if not hasattr(a, i) or i in excluded_attrs: continue attr = getattr(a, i) if not hasattr(attr, "__call__"): assert hasattr(b, i), i assert getattr(b, i) == attr, "%s != %s" % (getattr(b, i), attr) c(a, b, d1) c(b, a, d2) warnings.filterwarnings("default", category=SymPyDeprecationWarning)
def check(a, check_attr=True): """ Check that pickling and copying round-trips. """ # The below hasattr() check will warn about is_Real in Python 2.5, so # disable this to keep the tests clean warnings.filterwarnings("ignore", ".*is_Real.*") protocols = [0, 1, 2, copy.copy, copy.deepcopy] # Python 2.x doesn't support the third pickling protocol if sys.version_info[0] > 2: protocols.extend([3]) for protocol in protocols: if callable(protocol): if isinstance(a, BasicType): # Classes can't be copied, but that's okay. return b = protocol(a) else: b = pickle.loads(pickle.dumps(a, protocol)) d1 = dir(a) d2 = dir(b) assert d1 == d2 if not check_attr: continue def c(a, b, d): for i in d: if not hasattr(a, i) or i in excluded_attrs: continue attr = getattr(a, i) if not hasattr(attr, "__call__"): assert hasattr(b, i), i assert getattr(b, i) == attr c(a, b, d1) c(b, a, d2)
def replace(self, query, value, map=False): """ Replace matching subexpressions of ``self`` with ``value``. If map=True then also return the mapping {old: new} where `old`` was a sub-expression found with query and ``new`` is the replacement value for it. Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree. The list of possible combinations of queries and replacement values is listed below: 1.1. type -> type obj.replace(sin, tan) 1.2. type -> func obj.replace(sin, lambda expr, arg: ...) 2.1. expr -> expr obj.replace(sin(a), tan(a)) 2.2. expr -> func obj.replace(sin(a), lambda a: ...) 3.1. func -> func obj.replace(lambda expr: ..., lambda expr: ...) Examples: >>> from sympy import log, sin, cos, tan, Wild >>> from sympy.abc import x >>> f = log(sin(x)) + tan(sin(x**2)) >>> f.replace(sin, cos) log(cos(x)) + tan(cos(x**2)) >>> f.replace(sin, lambda arg: sin(2*arg)) log(sin(2*x)) + tan(sin(2*x**2)) >>> sin(x).replace(sin, cos, map=True) (cos(x), {sin(x): cos(x)}) >>> a = Wild('a') >>> f.replace(sin(a), cos(a)) log(cos(x)) + tan(cos(x**2)) >>> f.replace(sin(a), lambda a: sin(2*a)) log(sin(2*x)) + tan(sin(2*x**2)) >>> g = 2*sin(x**3) >>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2) 4*sin(x**9) """ if isinstance(query, type): _query = lambda expr: isinstance(expr, query) if isinstance(value, type): _value = lambda expr, result: value(*expr.args) elif callable(value): _value = lambda expr, result: value(*expr.args) else: raise TypeError("given a type, replace() expects another type or a callable") elif isinstance(query, Basic): _query = lambda expr: expr.match(query) if isinstance(value, Basic): _value = lambda expr, result: value.subs(result) elif callable(value): _value = lambda expr, result: value(**dict([ (str(key)[:-1], val) for key, val in result.iteritems() ])) else: raise TypeError("given an expression, replace() expects another expression or a callable") elif callable(query): _query = query if callable(value): _value = lambda expr, result: value(expr) else: raise TypeError("given a callable, replace() expects another callable") else: raise TypeError("first argument to replace() must be a type, an expression or a callable") mapping = {} def rec_replace(expr): args, construct = [], False for arg in expr.args: result = rec_replace(arg) if result is not None: construct = True else: result = arg args.append(result) if construct: return expr.__class__(*args) else: result = _query(expr) if result: value = _value(expr, result) if map: mapping[expr] = value return value else: return None result = rec_replace(self) if result is None: result = self if not map: return result else: return result, mapping
def replace(self, query, value, map=False): """ Replace matching subexpressions of ``self`` with ``value``. If ``map = True`` then also return the mapping {old: new} where ``old`` was a sub-expression found with query and ``new`` is the replacement value for it. Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree. The list of possible combinations of queries and replacement values is listed below: Examples ======== Initial setup >>> from sympy import log, sin, cos, tan, Wild >>> from sympy.abc import x, y >>> f = log(sin(x)) + tan(sin(x**2)) 1.1. type -> type obj.replace(sin, tan) >>> f.replace(sin, cos) log(cos(x)) + tan(cos(x**2)) >>> sin(x).replace(sin, cos, map=True) (cos(x), {sin(x): cos(x)}) 1.2. type -> func obj.replace(sin, lambda arg: ...) >>> f.replace(sin, lambda arg: sin(2*arg)) log(sin(2*x)) + tan(sin(2*x**2)) 2.1. expr -> expr obj.replace(sin(a), tan(a)) >>> a = Wild('a') >>> f.replace(sin(a), tan(a)) log(tan(x)) + tan(tan(x**2)) 2.2. expr -> func obj.replace(sin(a), lambda a: ...) >>> f.replace(sin(a), cos(a)) log(cos(x)) + tan(cos(x**2)) >>> f.replace(sin(a), lambda a: sin(2*a)) log(sin(2*x)) + tan(sin(2*x**2)) 3.1. func -> func obj.replace(lambda expr: ..., lambda expr: ...) >>> g = 2*sin(x**3) >>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2) 4*sin(x**9) See Also ======== subs: substitution of subexpressions as defined by the objects themselves. xreplace: exact node replacement in expr tree; also capable of using matching rules """ if isinstance(query, type): _query = lambda expr: isinstance(expr, query) if isinstance(value, type): _value = lambda expr, result: value(*expr.args) elif callable(value): _value = lambda expr, result: value(*expr.args) else: raise TypeError( "given a type, replace() expects another type or a callable" ) elif isinstance(query, Basic): _query = lambda expr: expr.match(query) if isinstance(value, Basic): _value = lambda expr, result: value.subs(result) elif callable(value): _value = lambda expr, result: value(**dict( [(str(key)[:-1], val) for key, val in result.iteritems()])) else: raise TypeError( "given an expression, replace() expects another expression or a callable" ) elif callable(query): _query = query if callable(value): _value = lambda expr, result: value(expr) else: raise TypeError( "given a callable, replace() expects another callable") else: raise TypeError( "first argument to replace() must be a type, an expression or a callable" ) mapping = {} def rec_replace(expr): args, construct = [], False for arg in expr.args: result = rec_replace(arg) if result is not None: construct = True else: result = arg args.append(result) if construct: return expr.__class__(*args) else: result = _query(expr) if result: value = _value(expr, result) if map: mapping[expr] = value return value else: return None result = rec_replace(self) if result is None: result = self if not map: return result else: return result, mapping