def matches(pattern, expr, repl_dict={}, evaluate=False): Basic.matches.__doc__ if evaluate: pat = pattern for old,new in repl_dict.items(): pat = pat.subs(old, new) if pat!=pattern: return pat.matches(expr, repl_dict) expr = Basic.sympify(expr) b, e = expr.as_base_exp() # special case, pattern = 1 and expr.exp can match to 0 if isinstance(expr, Basic.One): d = repl_dict.copy() d = pattern.exp.matches(Basic.Integer(0), d, evaluate=False) if d is not None: return d d = repl_dict.copy() d = pattern.base.matches(b, d, evaluate=False) if d is None: return None d = pattern.exp.matches(e, d, evaluate=True) if d is None: return Basic.matches(pattern, expr, repl_dict, evaluate) return d
def __init__(self, content): Basic.__init__(self, False, None, False) self.dialogues = [] # Remember, content is assumed to be the section we are editing # therefore, if given a whole article, it will behave strange. self.content = content self.parse()
def __init__(s, game, options, position, image, group, initdirection = None, colliders = []): Basic.__init__(s, game, options, position, image, group, initdirection, colliders) s.instances.append(s) s._behaviour = options['behaviour'] s._target = s._game.subject
def set_params(self, **kwargs): Basic.set_params(self, **kwargs) self.p = kwargs.get('p', 0.6) self.tau = kwargs.get('tau', [0.001, 0.09]) self.epsilon = kwargs.get('epsilon', 0.005) self.partition_min_pts = 2 self.min_pts = 5 self.SCORE_ID = kwargs['SCORE_ID'] self.inf_bounds = None self.min_improvement = kwargs.get('min_improvement', .01) self.err_funcs = kwargs.get('err_funcs', None) self.max_wait = kwargs.get('max_wait', 2*60*60) self.start_time = None self.sampler = Sampler(self.SCORE_ID) self.seen = set() self.is_done = False self.roots = [] if self.err_funcs is None: raise RuntimeError("errfuncs is none")
def __new__(cls, expr, *symbols, **assumptions): expr = Basic.sympify(expr) if not symbols: return expr symbols = map(Basic.sympify, symbols) if not assumptions.get("evaluate", True): obj = Basic.__new__(cls, expr, *symbols) return obj for s in symbols: assert isinstance(s, Basic.Symbol),`s` if not expr.has(s): return Basic.Zero() unevaluated_symbols = [] for s in symbols: obj = expr._eval_derivative(s) if obj is None: unevaluated_symbols.append(s) else: expr = obj if not unevaluated_symbols: return expr return Basic.__new__(cls, expr, *unevaluated_symbols)
def __new__(cls, expr, *symbols, **assumptions): expr = sympify(expr) if not symbols: return expr symbols = Derivative._symbolgen(*symbols) if not assumptions.get("evaluate", False) and not isinstance( expr, Derivative): obj = Basic.__new__(cls, expr, *symbols) return obj unevaluated_symbols = [] for s in symbols: s = sympify(s) if not isinstance(s, Symbol): raise ValueError( 'Invalid literal: %s is not a valid variable' % s) if not expr.has(s): return S.Zero obj = expr._eval_derivative(s) if obj is None: unevaluated_symbols.append(s) elif obj is S.Zero: return S.Zero else: expr = obj if not unevaluated_symbols: return expr return Basic.__new__(cls, expr, *unevaluated_symbols)
def __init__(self, **kwargs): Basic.__init__(self, **kwargs) self.all_clusters = [] self.cost_split = 0. self.cost_partition_bad = 0. self.cost_partition_good = 0. self.cache = None self.use_mtuples = kwargs.get('use_mtuples', False)
def setup_tables(self, full_table, bad_tables, good_tables, **kwargs): Basic.setup_tables(self, full_table, bad_tables, good_tables, **kwargs) self.grouper = Grouper(full_table, self) self.SCORE_ID = add_meta_column( chain([full_table], bad_tables, good_tables), 'SCOREVAR' )
def __init__(self, debug, api, verbose, poolapi): Basic.__init__(self, debug, api, verbose) self.imageapi = poolapi if self.imageapi.login(userdata.username, userdata.password): self.log("Logged in to Pool wiki succesful.") self.usable = True else: self.log("Failed to log into Pool wiki; image operations will not be available in this run.")
def get(self): file_id = request.args.get('id') if not file_id: file_id = 'hazrat_kth_se' basic = Basic(file_id) channels = basic.get_channel_names() print('BASIC Flask channels :', channels) return channels
def __init__(self, *args, **kwargs): Basic.__init__(self, *args, **kwargs) self.start = time.time() self.max_wait = kwargs.get('max_wait', 60*60*2) # 2 hours default self.n_rules_checked = 0 self.stop = False self.cs = kwargs.get('cs', None) self.checkpoints_per_c = defaultdict(list)
def __new__(cls, *args, **options): # NOTE: this __new__ is twofold: # # 1 -- it can create another *class*, which can then be instantiated by # itself e.g. Function('f') creates a new class f(Function) # # 2 -- on the other hand, we instantiate -- that is we create an # *instance* of a class created earlier in 1. # # So please keep, both (1) and (2) in mind. # (1) create new function class # UC: Function('f') if cls is Function: #when user writes Function("f"), do an equivalent of: #taking the whole class Function(...): #and rename the Function to "f" and return f, thus: #In [13]: isinstance(f, Function) #Out[13]: False #In [14]: isinstance(f, FunctionClass) #Out[14]: True if len(args) == 1 and isinstance(args[0], str): #always create Function return FunctionClass(Function, *args) return FunctionClass(Function, *args, **options) else: print args print type(args[0]) raise Exception("You need to specify exactly one string") # (2) create new instance of a class created in (1) # UC: Function('f')(x) # UC: sin(x) args = map(sympify, args) # these lines should be refactored for opt in [ "nargs", "dummy", "comparable", "noncommutative", "commutative" ]: if opt in options: del options[opt] # up to here. if options.get('evaluate') is False: return Basic.__new__(cls, *args, **options) r = cls.canonize(*args) if isinstance(r, Basic): return r elif r is None: # Just undefined functions have nargs == None if not cls.nargs and hasattr(cls, 'undefined_Function'): r = Basic.__new__(cls, *args, **options) r.nargs = len(args) return r pass elif not isinstance(r, tuple): args = (r, ) return Basic.__new__(cls, *args, **options)
def __init__(self, **kwargs): Basic.__init__(self, **kwargs) self.all_clusters = [] self.cost_split = 0. self.cost_partition_bad = 0. self.cost_partition_good = 0. self.cache = None self.use_mtuples = kwargs.get('use_mtuples', False) self.max_wait = kwargs.get('max_wait', None)
def __new__(cls, lhs, rhs, rop=None, **assumptions): lhs = Basic.sympify(lhs) rhs = Basic.sympify(rhs) if cls is not Relational: rop_cls = cls else: rop_cls, swap = Relational.get_relational_class(rop) if swap: lhs, rhs = rhs, lhs obj = Basic.__new__(rop_cls, lhs, rhs, **assumptions) return obj
def main(debug: bool = False) -> None: basic = Basic() while True: text = input("basic > ") try: results = basic.run(text, "<stdin>", True, debug) for result in results: print(result) except Error as err: print_error(err)
def __init__(s, game, options, position, image, group = 'power', initdirection = None, colliders = ['player']): Basic.__init__(s, game, options, position, group, initdirection, colliders) s.instances.append(s) if options['type'] == 'money': s.value = options['value'] s.halflife = options['halflife'] elif options['type'] == 'powerup': pass
def main(file_name: str) -> None: with open(file_name, "r") as f: code = f.read() basic = Basic() try: results = basic.run(code, file_name) for result in results: print(result) except Error as err: print_error(err)
def __new__(cls, *args, **options): # NOTE: this __new__ is twofold: # # 1 -- it can create another *class*, which can then be instantiated by # itself e.g. Function('f') creates a new class f(Function) # # 2 -- on the other hand, we instantiate -- that is we create an # *instance* of a class created earlier in 1. # # So please keep, both (1) and (2) in mind. # (1) create new function class # UC: Function('f') if cls is Function: #when user writes Function("f"), do an equivalent of: #taking the whole class Function(...): #and rename the Function to "f" and return f, thus: #In [13]: isinstance(f, Function) #Out[13]: False #In [14]: isinstance(f, FunctionClass) #Out[14]: True if len(args) == 1 and isinstance(args[0], str): #always create Function return FunctionClass(Function, *args) return FunctionClass(Function, *args, **options) else: print args print type(args[0]) raise Exception("You need to specify exactly one string") # (2) create new instance of a class created in (1) # UC: Function('f')(x) # UC: sin(x) args = map(sympify, args) # these lines should be refactored for opt in ["nargs", "dummy", "comparable", "noncommutative", "commutative"]: if opt in options: del options[opt] # up to here. if options.get('evaluate') is False: return Basic.__new__(cls, *args, **options) r = cls.eval(*args) if isinstance(r, Basic): return r elif r is None: # Just undefined functions have nargs == None if not cls.nargs and hasattr(cls, 'undefined_Function'): r = Basic.__new__(cls, *args, **options) r.nargs = len(args) return r pass elif not isinstance(r, tuple): args = (r,) return Basic.__new__(cls, *args, **options)
def __new__(cls, a, b, **assumptions): a = Basic.sympify(a) b = Basic.sympify(b) if isinstance(b, Basic.Zero): return S.One if isinstance(b, Basic.One): return a obj = a._eval_power(b) if obj is None: obj = Basic.__new__(cls, a, b, **assumptions) return obj
def __init__(self, *args, **kwargs): Basic.__init__(self, *args, **kwargs) self.start = time.time() self.max_wait = kwargs.get('max_wait', 60*60*2) # 2 hours default self.n_rules_checked = 0 self.clauses_til_checkpoint = 0 self.stop = False self.cs = kwargs.get('cs', None) self.bests_per_c = defaultdict(list) self.checkpoints_per_c = defaultdict(list)
def delOnePurchaser(self): pur_no=input("请输入要移除的售货员的编号:").strip() pur=Basic.queryOnePurchase(pur_no) if pur==[]: print("不存在该员工.") return cmd=input("确认移除该员工?(移除后所有与该员工有关的进货记录都会删除.y/n)").strip() if cmd[0]=='y'or cmd[0]=='Y': Basic.delOnePurchase(pur_no) print("操作成功.") else: print("操作失败.")
def delOneCashier(self): '''''' cash_no=input("请输入要移除的售货员的编号:").strip() cash=Basic.queryOneCashier(cash_no) if cash==[]: print("不存在该员工.") return cmd=input("确认移除该员工?(移除后所有与该员工有关的售货记录都会删除.y/n)").strip() if cmd[0]=='y'or cmd[0]=='Y': Basic.delOneCashier(cash_no) print("操作成功.") else: print("操作失败.")
def delOneCommodity(self): '''''' com_no=input("请输入要移除的商品的编号:").strip() com=Basic.queryOneCommodity(com_no) if com==[]: print("不存在该商品.") return cmd=input("确认移除该商品?(移除后所有与该商品有关的进出货记录都会删除.y/n)").strip() if cmd[0]=='y'or cmd[0]=='Y': Basic.delOneCommodity(com_no) print("操作成功.") else: print("操作失败.")
def __new__(cls, a, b, **assumptions): a = _sympify(a) b = _sympify(b) if assumptions.get('evaluate') is False: return Basic.__new__(cls, a, b, **assumptions) if b is S.Zero: return S.One if b is S.One: return a obj = a._eval_power(b) if obj is None: obj = Basic.__new__(cls, a, b, **assumptions) obj.is_commutative = (a.is_commutative and b.is_commutative) return obj
def __new__(cls, b, e, **assumptions): b = _sympify(b) e = _sympify(e) if assumptions.get('evaluate') is False: return Basic.__new__(cls, b, e, **assumptions) if e is S.Zero: return S.One if e is S.One: return b obj = b._eval_power(e) if obj is None: obj = Basic.__new__(cls, b, e, **assumptions) obj.is_commutative = (b.is_commutative and e.is_commutative) return obj
def setEnvironment(self, SCENARIO): if SCENARIO == 'Basic': self.Parser = csim.Parser("Basic") elif SCENARIO == 'Corridor': self.Parser = csim.Parser("Corridor") elif SCENARIO == 'Bottleneck': self.Parser = csim.Parser("Bottleneck") elif SCENARIO == 'Crossway': self.Parser = csim.Parser("Crossway") obs = self.Observe() if SCENARIO == 'Basic': self.Scenario = Basic(obs)
def __init__(self, *args, **kwargs): Basic.__init__(self, *args, **kwargs) self.best = [] self.max_wait = kwargs.get('max_wait', 2 * 60 * 60) # 2 hours self.start = None self.stop = False self.n_rules_checked = 0 self.naive = kwargs.get('naive', False) self.max_bests = 50 self.max_complexity = kwargs.get('max_complexity', 3) self.checkpoints = [] self.cost_clique = 0
def __new__(cls, a, b, **assumptions): a = _sympify(a) b = _sympify(b) if assumptions.get("evaluate") is False: return Basic.__new__(cls, a, b, **assumptions) if b is S.Zero: return S.One if b is S.One: return a obj = a._eval_power(b) if obj is None: obj = Basic.__new__(cls, a, b, **assumptions) obj.is_commutative = a.is_commutative and b.is_commutative return obj
def __new__(cls, b, e, **assumptions): b = _sympify(b) e = _sympify(e) if assumptions.get("evaluate") is False: return Basic.__new__(cls, b, e, **assumptions) if e is S.Zero: return S.One if e is S.One: return b obj = b._eval_power(e) if obj is None: obj = Basic.__new__(cls, b, e, **assumptions) obj.is_commutative = b.is_commutative and e.is_commutative return obj
def __new__(cls, *args): def flatten(arg): if is_flattenable(arg): return sum(map(flatten, arg), []) return [arg] args = flatten(list(args)) # Sympify Arguments args = map(sympify, args) # Turn tuples into Tuples args = [Tuple(*arg) if arg.__class__ is tuple else arg for arg in args] if len(args) == 0: return EmptySet() try: if all([arg.is_real and arg.is_number for arg in args]): cls = RealFiniteSet except AttributeError: pass elements = frozenset(map(sympify, args)) obj = Basic.__new__(cls, elements) obj.elements = elements return obj
def test_fib_naive() -> None: basic = Basic() run_test( basic, """ let fib = let fib_pom a b n = if n == 0 then a else fib_pom b (a+b) (n-1) in fib_pom 0 1 """, "test_fib_part1", LangFunction, None, ) for i in range(42): run_test( basic, f"let _ = fib {i}", f"test_fib_in_part{i + 1}", LangNumber, None, fib(i), )
def test_division_by_zero() -> None: basic = Basic() run_test(basic, " let _ = 42/0", "test_integer division by zero", None, RTError) run_test(basic, " let _ = 42.5/0", "test_float division by zero", None, RTError)
def POST(self): try: token = Basic().get_access_token() print(token) webData = web.data() recMsg = receive.parse_xml(webData) if isinstance(recMsg, receive.Msg): toUser = recMsg.FromUserName fromUser = recMsg.ToUserName if recMsg.MsgType == 'text': content = "欢迎光临!" replyMsg = reply.TextMsg(toUser, fromUser, content) return replyMsg.send() if recMsg.MsgType == 'image': mediaId = recMsg.MediaId replyImageMsg = reply.ImageMsg(toUser, fromUser, mediaId) return replyImageMsg.send() else: return reply.Msg().send() else: print("暂且不处理") return reply.Msg().send() except Exception as Argment: print(Argment) return Argment
def matches(pattern, expr, repl_dict={}, evaluate=False): # this method needs a cleanup. #print "? :",pattern, expr, repl_dict, evaluate #if repl_dict: # return repl_dict for p,v in repl_dict.items(): if p==pattern: if v==expr: return repl_dict return None assert isinstance(pattern, Derivative) if isinstance(expr, Derivative): if len(expr.symbols) == len(pattern.symbols): #print "MAYBE:",pattern, expr, repl_dict, evaluate return Basic.matches(pattern, expr, repl_dict, evaluate) #print "NONE:",pattern, expr, repl_dict, evaluate return None #print pattern, expr, repl_dict, evaluate stop if pattern.nargs is not None: if pattern.nargs != expr.nargs: return None repl_dict = repl_dict.copy() repl_dict[pattern] = expr return repl_dict
def _eval_evalf(self, prec): # Lookup mpmath function based on name fname = self.func.__name__ try: if not hasattr(mpmath, fname): from sympy.utilities.lambdify import MPMATH_TRANSLATIONS fname = MPMATH_TRANSLATIONS[fname] func = getattr(mpmath, fname) except (AttributeError, KeyError): return # Convert all args to mpf or mpc try: args = [arg._to_mpmath(prec) for arg in self.args] except ValueError: return # Set mpmath precision and apply. Make sure precision is restored # afterwards orig = mpmath.mp.prec try: mpmath.mp.prec = prec v = func(*args) finally: mpmath.mp.prec = orig return Basic._from_mpmath(v, prec)
def matches(pattern, expr, repl_dict={}, evaluate=False): # this method needs a cleanup. #print "? :",pattern, expr, repl_dict, evaluate #if repl_dict: # return repl_dict for p, v in repl_dict.items(): if p == pattern: if v == expr: return repl_dict return None assert isinstance(pattern, Derivative) if isinstance(expr, Derivative): if len(expr.symbols) == len(pattern.symbols): #print "MAYBE:",pattern, expr, repl_dict, evaluate return Basic.matches(pattern, expr, repl_dict, evaluate) #print "NONE:",pattern, expr, repl_dict, evaluate return None #print pattern, expr, repl_dict, evaluate stop if pattern.nargs is not None: if pattern.nargs != expr.nargs: return None repl_dict = repl_dict.copy() repl_dict[pattern] = expr return repl_dict
def run_test( basic: Basic, code: str, name: str, res_type: type_res = None, err_type: type_err = None, value: type_value = None, repl: bool = True, ) -> None: if not isinstance(res_type, list): res_type = [res_type] if res_type else [] if not isinstance(value, list): value = [value] if value is not None else [] try: results = basic.run(code, name, repl) assert len(results) == len(res_type) for i, res in enumerate(results): assert res_type and isinstance(res, res_type[i]) if value and value[i] is not Ellipsis: if res.value != value[i]: print(res.value, value[i]) assert res.value == value[i] except Error as err: assert err_type and isinstance(err, err_type) else: assert err_type is None
def test_integer_arithmetic_operator() -> None: basic = Basic() for name, operator in OPERATORS.items(): run_test( basic, " let _ = 4 " + operator + " +2", "test_positive_integer" + name, LangNumber, None, (eval("4 " + py_op(operator) + " +2")), ) run_test( basic, " let _ = -4 " + operator + " -2", "test_positive_integer_" + name, LangNumber, None, (eval("-4 " + py_op(operator) + " -2")), ) run_test( basic, " let _ = 4 " + operator + " -2", "test_negative_" + name, LangNumber, None, (eval("4 " + py_op(operator) + " -2")), )
def matches(pattern, expr, repl_dict={}, evaluate=False): expr = sympify(expr) if pattern.is_commutative and expr.is_commutative: return AssocOp._matches_commutative(pattern, expr, repl_dict, evaluate) # todo for commutative parts, until then use the default matches method for non-commutative products return Basic.matches(pattern, expr, repl_dict, evaluate)
def __new__(cls, start, end, left_open=False, right_open=False): start = _sympify(start) end = _sympify(end) # Only allow real intervals (use symbols with 'is_real=True'). if not start.is_real or not end.is_real: raise ValueError("Only real intervals are supported") # Make sure that the created interval will be valid. if end.is_comparable and start.is_comparable: if end < start: return S.EmptySet if end == start and (left_open or right_open): return S.EmptySet if end == start and not (left_open or right_open): return FiniteSet(end) # Make sure infinite interval end points are open. if start == S.NegativeInfinity: left_open = True if end == S.Infinity: right_open = True return Basic.__new__(cls, start, end, left_open, right_open)
def test_float_assignment() -> None: basic = Basic() run_test(basic, "let a1 = 0.7", "test_positive_float_assignment", LangNumber, None, 0.7) run_test(basic, "let a2 = -0.7", "test_negative_float_assignment", LangNumber, None, -0.7)
def test_mixed_logic_operator() -> None: basic = Basic() for name, operator in OPERATORS.items(): run_test( basic, " let _ = 4.5 " + operator + " 5", "test_positive_mixed_" + name, LangBool, None, (eval("4.5 " + operator + " 5")), ) run_test( basic, " let _ = -4.5 " + operator + " -2", "test_negative_mixed_" + name, LangBool, None, (eval("-4.5 " + operator + " -2")), ) run_test( basic, " let _ = -4.0 " + operator + " -4", "test_negative_mixed_" + name, LangBool, None, (eval("-4.0 " + operator + " -4")), )
def __le__(self, other): other = Basic.sympify(other) if self is other: return True if other.is_comparable: other = other.evalf() if isinstance(other, Number): return self.evalf()<=other return RelMeths.__le__(self, other)
def test_wrong_logic_operator() -> None: basic = Basic() for name, operator in OPERATORS.items(): run_test( basic, " let _ = 42" + operator, "test_wrong_order_" + name, None, InvalidSyntaxError, ) run_test( basic, " let _ = 42.5" + operator, "test_wrong_order_" + name + "_float", None, InvalidSyntaxError, ) run_test( basic, " let _ = " + operator + "42", "test_wrong_order_" + name, None, InvalidSyntaxError, ) run_test( basic, " let _ = " + operator + "42.5", "test_wrong_order_" + name + "_float", None, InvalidSyntaxError, )
def test_mixed_arithmetic_operator() -> None: basic = Basic() for name, operator in OPERATORS.items(): run_test( basic, " let _ = 4.5 " + operator + " +5", "test_positive_mixed_" + name, LangNumber, None, (eval("4.5 " + py_op(operator) + " +5")), ) run_test( basic, " let _ = -4.5 " + operator + " -2", "test_negative_mixed_" + name, LangNumber, None, (eval("-4.5 " + py_op(operator) + " -2")), ) run_test( basic, " let _ = -4.0 " + operator + " -4", "test_negative_mixed_" + name, LangNumber, None, (eval("-4.0 " + py_op(operator) + " -4")), )
def __new__(cls, expr, *args): expr = Basic.sympify(expr) args = tuple(map(Basic.sympify, args)) #if isinstance(expr, Apply): # if expr[:]==args: # return expr.func dummy_args = [] for a in args: if not isinstance(a, Basic.Symbol): raise TypeError("%s %s-th argument must be Symbol instance (got %r)" \ % (cls.__name__, len(dummy_args)+1,a)) d = a.as_dummy() expr = expr.subs(a, d) dummy_args.append(d) obj = Basic.__new__(cls, expr, *dummy_args, **expr._assumptions) return obj
def __init__(self): self.robot = Robot() self.basic = Basic() self.material = Material() self.dao = Dao() self.dao.connect() self.spider = Spider()
def matches(pattern, expr, repl_dict={}, evaluate=False): if evaluate: pat = pattern for old, new in repl_dict.items(): pat = pat.subs(old, new) if pat != pattern: return pat.matches(expr, repl_dict) expr = _sympify(expr) b, e = expr.as_base_exp() # special case, pattern = 1 and expr.exp can match to 0 if expr is S.One: d = repl_dict.copy() d = pattern.exp.matches(S.Zero, d, evaluate=False) if d is not None: return d d = repl_dict.copy() d = pattern.base.matches(b, d, evaluate=False) if d is None: return None d = pattern.exp.matches(e, d, evaluate=True) if d is None: return Basic.matches(pattern, expr, repl_dict, evaluate) return d
def user_list(self, next_openid): accessToken = Basic().get_access_token() postUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=%s" % ( accessToken, next_openid) urlResp = urllib.urlopen(postUrl) urlResp = json.loads(urlResp.read()) return urlResp
def __add__(self, other): other = Basic.sympify(other) if isinstance(other, NaN) or isinstance(self, NaN): return S.NaN if isinstance(other, Number): return Real(self.num + other._as_decimal()) return Number.__add__(self, other)
def batch_user_info(self, list): accessToken = Basic().get_access_token() postUrl = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=%s" % accessToken print list urlResp = urllib.urlopen(postUrl, list) urlResp = json.loads(urlResp.read()) return urlResp
def __new__(cls, p, q = None): if q is None: if isinstance(p, str): p, q = _parse_rational(p) else: return Integer(p) if q==0: if p==0: if _errdict["divide"]: raise Exception("Indeterminate 0/0") else: return S.NaN if p<0: return S.NegativeInfinity return S.Infinity if q<0: q = -q p = -p n = igcd(abs(p), q) if n>1: p //= n q //= n if q==1: return Integer(p) if p==1 and q==2: return S.Half obj = Basic.__new__(cls) obj.p = int(p) obj.q = int(q) #obj._args = (p, q) return obj
def _new(cls, _mpf_, _prec): if _mpf_ == mlib.fzero: return S.Zero obj = Basic.__new__(cls) obj._mpf_ = _mpf_ obj._prec = _prec return obj
def __new__(cls, *args): # Flatten out Iterators and Unions to form one list of sets args = list(args) def flatten(arg): if arg == S.EmptySet: return [] if isinstance(arg, Set): if arg.is_Union: return sum(map(flatten, arg.args), []) else: return [arg] if is_flattenable(arg): # and not isinstance(arg, Set) (implicit) return sum(map(flatten, arg), []) raise TypeError("Input must be Sets or iterables of Sets") args = flatten(args) if len(args) == 0: return S.EmptySet # Only real parts? Return a RealUnion if all(arg.is_real for arg in args): return RealUnion(args) # Lets find and merge real elements if we have them # Separate into finite, real and other sets finite_set = sum([s for s in args if s.is_FiniteSet], S.EmptySet) real_sets = [s for s in args if s.is_real] other_sets = [s for s in args if not s.is_FiniteSet and not s.is_real] # Separate finite_set into real and other part real_finite = RealFiniteSet(i for i in finite_set if i.is_real) other_finite = FiniteSet(i for i in finite_set if not i.is_real) # Merge real part of set real_union = RealUnion(real_sets+[real_finite]) if not real_union: # Real part was empty sets = other_sets + [other_finite] elif real_union.is_FiniteSet: # Real part was just a FiniteSet sets = other_sets + [real_union+other_finite] elif real_union.is_Interval: # Real part was just an Interval sets = [real_union] + other_sets + [other_finite] # If is_RealUnion then separate elif real_union.is_Union and real_union.is_real: intervals = [s for s in real_union.args if s.is_Interval] finite_set = sum([s for s in real_union.args if s.is_FiniteSet] + [other_finite], S.EmptySet) # Join FiniteSet back together sets = intervals + [finite_set] + other_sets # Clear out Empty Sets sets = [set for set in sets if set != S.EmptySet] # If a single set is left over, don't create a new Union object but # rather return the single set. if len(sets) == 1: return sets[0] return Basic.__new__(cls, *sets)
def __le__(self, other): other = Basic.sympify(other) if isinstance(other, NumberSymbol): return other.__gt__(self) if other.is_comparable: other = other.evalf() if isinstance(other, Number): return bool(self._as_decimal()<=other._as_decimal()) return RelMeths.__le__(self, other)
def __new__(cls, expr, *symbols, **assumptions): expr = sympify(expr) if not symbols: return expr symbols = Derivative._symbolgen(*symbols) if expr.is_commutative: assumptions["commutative"] = True if "evaluate" in assumptions: evaluate = assumptions["evaluate"] del assumptions["evaluate"] else: evaluate = False if not evaluate and not isinstance(expr, Derivative): obj = Basic.__new__(cls, expr, *symbols, **assumptions) return obj unevaluated_symbols = [] for s in symbols: s = sympify(s) if not isinstance(s, Symbol): raise ValueError('Invalid literal: %s is not a valid variable' % s) if not expr.has(s): return S.Zero obj = expr._eval_derivative(s) if obj is None: unevaluated_symbols.append(s) elif obj is S.Zero: return S.Zero else: expr = obj if not unevaluated_symbols: return expr return Basic.__new__(cls, expr, *unevaluated_symbols, **assumptions)
def set_params(self, **kwargs): Basic.set_params(self, **kwargs) self.p = kwargs.get('p', 0.6) self.tau = kwargs.get('tau', [0.001, 0.05]) self.epsilon = kwargs.get('epsilon', 0.005) self.min_pts = 5 self.samp_rate = 1. self.SCORE_ID = kwargs['SCORE_ID'] self.inf_bounds = [inf, -inf] self.sampler = Sampler(self.SCORE_ID)