def calculate(self): out_stack = [] op_stack = [] expr = self.expression.split() for token in expr: if token.isnumeric(): out_stack.append(float(token)) elif token in self.operators: op = self.operators[token] while op_stack and op_stack[-1] != '(' and op.ready( op_stack[-1]): op_stack.pop()(out_stack) op_stack.append(op) elif token == '(': op_stack.append(token) elif token == ')': while op_stack and op_stack[-1] != '(': op_stack.pop()(out_stack) if out_stack[-1] == '(': out_stack.pop() while op_stack: op = op_stack.pop() if op != '(': op(out_stack) return ", ".join(map(str, out_stack))
def _reval_impl(self, node, variables): if isinstance(node, ast.Num): return node.n elif isinstance(node, ast.BinOp): op = self.operators[type(node.op)] return op(self._reval_impl(node.left, variables), self._reval_impl(node.right, variables)) elif isinstance(node, ast.UnaryOp): op = self.operators[type(node.op)] return op(self._reval_impl(node.operand, variables)) elif isinstance(node, ast.Call) and node.func.id in self.functions: func = self.functions[node.func.id] args = [self._reval_impl(n, variables) for n in node.args] return func(*args) elif isinstance(node, ast.Name) and node.id in variables: return variables[node.id] elif isinstance(node, ast.Subscript) and node.value.id in variables: var = variables[node.value.id] idx = node.slice.value.n try: return var[idx] except IndexError: raise IndexError("Variable '%s' out of range: %d >= %d" % (node.value.id, idx, len(var))) else: raise TypeError("Unsupported operation: %s" % node)
def test_negative_rhs(op): for n in range(-5, 0): f = op(_1, n) g = op(_1, _2) for m in range(-5, 6): assert f(m) == op(m, n) assert g(m, n) == op(m, n)
def test_arithmetic(op): for n in range(1, 6): # many ops fail with rhs <= 0 f = op(_1, n) g = op(_1, _2) for m in range(-5, 6): assert f(m) == op(m, n) assert g(m, n) == op(m, n)
def _(self, other): if isiterable(other): if len(self) != len(other): raise ValueError( f"{self.__class__.__name__} requires other data to contain same number of elements (or a scalar)." ) return self.__class__(op(o, s) for s, o in zip(self, other)) return self.__class__(op(other, s) for s in self)
def op(self, y, op): if isinstance(y, numbers.Number): out = [op(i, y) for i in self] else: if len(y) == 1: out = [op(i, y[0]) for i in self] elif len(self) == 1: out = [op(self[0], j) for j in y] elif len(y) == len(self): out = [op(i, j) for i, j in zip(self, y)] else: print('Opeartion failed. Assure y is a number, singleton or iterable of matching length') return Vec(out)
def chown(path, uid=-1, gid=-1, recursive=False, dereference=True): '''Does not check for recursion-loops (although link-recursion will be avoided with dereference=False)''' uid, gid = resolve_ids(uid, gid) op = os.chown if dereference else os.lchown if not recursive: op(path, uid, gid) else: for path in walk(path, follow_links=dereference): if dereference and islink(path): os.lchown(path, uid, gid) # chown the link as well op(path, uid, gid)
def _(self, other): if isiterable(other): if len(self) != len(other): raise ValueError(f"{self.__class__.__name__} requires other data to contain same number of elements (or a scalar).") for i in range(len(self)): # pylint: disable=C0200 self[i] = op(self[i], other[i]) else: for i in range(len(self)): # pylint: disable=C0200 self[i] = op(self[i], other) return self
def bytes_compare(x, y): lx = len(x) ly = len(y) length = min(lx, ly) for i in range(length): xi, yi = x[i], y[i] if xi == yi: continue return op(xi, yi) return op(lx, ly)
def _chance_of(self, source, op): ''' .5 + (1/6*.5) + (1/(6*6) *.5) + (1/(6*6*6) * .5) + (1/(6*6*6*6) * .5) ... approaches .6 ''' if (source is not Source.success): return super(SpecDie, self)._chance_of(source, op) else: return [(op(0, 1), 0.5), (op(0, 2), 1.0/6 *.5), (op(0, 3), 1.0/(6*6) * .5), (op(0, 4), 1.0/(6*6*6) * .5), (op(0, 5), 1.0/(6*6*6*6) * .5)]
def eval_ptree(x, env): fmap = {'#t': True, '#f': False, 'nil': None} if x in ('#t', '#f', 'nil'): return fmap[x] elif isinstance(x, Symbol): # variable lookup return env.lookup(x)[0] elif not isinstance(x, list): # constant return x elif len(x) == 0: # noop return None elif x[0] == 'if': (_, predicate, truexpr, falseexpr) = x if eval_ptree(predicate, env): expression = truexpr else: expression = falseexpr return eval_ptree(expression, env) elif x[0] == 'def': # variable definition (_, var, expression) = x # postorder traversal by nested eval is needed below env.extend(var, eval_ptree(expression, env)) elif x[0] == 'store': # (set! var exp) (_, var, exp) = x env.lookup(var)[1].extend(var, eval_ptree(exp, env)) elif x[0] == 'func': (_, parameters, parsedbody) = x return Function(parameters, parsedbody, env) else: # operator op = eval_ptree(x[0], env) # postorder traversal to get subexpressione before running the op args = [eval_ptree(arg, env) for arg in x[1:]] return op(*args)
def op_fun(x): if isinstance(x, RandomProcess): return x.apply(op_fun) elif isinstance(x, RV): return x.apply(op) else: return op(x)
def eval_ptree(x, env): fmap = {'#t': True, '#f': False, 'nil': None} if x in ('#t', '#f', 'nil'): return fmap[x] elif isinstance(x, Symbol): # variable lookup return env.lookup(x)[0] elif not isinstance(x, list): # constant return x elif len(x) == 0: #noop return None elif x[0] == 'if': (_, predicate, truexpr, falseexpr) = x if eval_ptree(predicate, env): expression = truexpr else: expression = falseexpr return eval_ptree(expression, env) elif x[0] == 'def': # variable definition (_, var, expression) = x #postorder traversal by nested eval is needed below # your code here env.extend(var, eval_ptree(expression, env)) elif x[0] == 'store': # (set! var exp) (_, var, exp) = x env.lookup(var)[1].extend(var, eval_ptree(exp, env)) elif x[0] == 'func': (_, parameters, parsedbody) = x return Function(parameters, parsedbody, env) else: # operator op = eval_ptree(x[0], env) #postorder traversal to get subexpressione before running the op args = [eval_ptree(arg, env) for arg in x[1:]] return op(*args)
def parse_args(self, data, query=None): if isinstance(data, (tuple, list)): op = self.args_method_table[data[0]] args = [self.parse_args(e, query=query) for e in data[1:]] return op(*args) else: return self.handler.handle(data)
def compte(digits): """ Recursive auxiliary function to solve the problem """ for digit in digits: if digit.n == self.total: # Terminal case : if the total is in the list, it's ok return digit elif self.best is None or abs(self.total - digit.n) < abs(self.total - self.best.n): # We keep trace of the closest result found self.best = digit for idg, g in enumerate(digits): for idh, h in enumerate(digits[idg + 1:]): # We test all the combinations (not permutations). All we miss are # not commutative operations (- and /), but only the case where g > h # are significative, so we reorder them. We also copy the digit list and remove # the two digits we are working on, as they will be replaced by the result of their operation new_digits = digits[:] new_digits.pop(idg) new_digits.pop(idg + idh) # There is an hidden +1-1 (-1 because we have removed one before) i, j = max(g, h, key=lambda x: x.n), min(g, h, key=lambda x: x.n) # Iterate over operators and recursion for astop, op in operators.iteritems(): try: r = compte(new_digits + [digit_ast(n=op(i.n, j.n), ast=ast.BinOp(i.ast, astop, j.ast))]) # Stop if we have found a solution if r: return r except CalcError: pass return None
def operator(self, mo, bop, op=op.add, op_squared=False): """Computes the values of an opearator applied to the procuts of determinant Args: mo (torch.tensor): matrix of MO vals(Nbatch, Nelec, Nmo) bkin (torch.tensor): kinetic operator (Nbatch, Nelec, Nmo) op (operator): how to combine the up/down contribution op_squared (bool, optional) return the trace of the square of the product if True Returns: torch.tensor: kinetic energy """ # get the values of the operator if self.config_method == 'ground_state': op_vals = self.operator_ground_state(mo, bop, op_squared) elif self.config_method.startswith('single'): op_vals = self.operator_single_double(mo, bop, op_squared) elif self.config_method.startswith('cas('): op_vals = self.operator_explicit(mo, bop, op_squared) else: raise ValueError( 'Configuration %s not recognized' % self.config_method) # combine the values is necessary if op is not None: return op(*op_vals) else: return op_vals
def calculation(x): # Variables to be stored for calculation val1 = 0 val2 = 0 op = operation(x) # Input operator # 'raised' is 1 if exception raised at 'val1' assignment, else 0 raised = 0 # If stack empty, error message printed try: val1 = int(stackNum.pop()) except Exception: print("Stack underflow.") raised = 1 # If stack empty after 1st 'pop()', error message printed try: val2 = int(stackNum.pop()) # If dividing by 0, error message printed as operation cannot be done if (val1 == 0 and x == "/"): print("Divide by 0.") stackAdd(val2) stackAdd(val1) # If NOT dividing by 0, operation carried out else: result = int(op(val2, val1)) result = saturation(result) # Handling saturation of 'result' stackAdd(result) except Exception: # Error message only if exception NOT raised for 'val1' if (raised != 1): stackAdd(val1) print("Stack underflow.")
def eval(x, env=global_env): "Evaluate an expression in an environment." while True: tx = type(x) if tx is Symbol: # variable reference return env.find(x)[x] elif tx is not list: # constant literal return x opname = x[0] try: op = ops.get(opname, None) except TypeError: op = None if op: x = op(env, *x[1:]) if opname in tail_call: env, x = x continue return x else: # (proc exp*) exps = [eval(exp, env) for exp in x] proc = exps.pop(0) if type(proc) is Procedure: x = proc.exp env = Env(proc.parms, exps, proc.env) continue return proc(*exps)
def executeStep(self, op, inputs, _values, new_value): print inputs print _values _inputs = [] for i in inputs: if type(i) == str: if i == "y": _inputs.append(_values[i]) else: if (new_value.has_key(i)): ##using as param, use new value _inputs.append(new_value[i]) else: _inputs.append(_values[i]) elif isinstance(i, Expr): print "Expr! Expr=", i _inputs.append( self.executeStep(i.operator, i.inputs, _values, new_value)) else: _inputs.append(i) print "op =" + str(op) + " inputs=" + str(_inputs) if type(op) == int: return op elif type(op) == str: ##use as op, should use origin value return _values[op] else: return op().forward(_inputs)
def binop(x, y): if isinstance(y, Maybe): if x.just and y.just: return Just(op(x.value, y.value)) else: return Nothing else: return NotImplemented
def test_it_can_build_a_trigger(sprite, op): health = TriggerAttr('health') trigger = op(health, 10) with pytest.raises(NotImplementedError): trigger.check(10) sprite.health = 10 trigger.bake(sprite) assert isinstance(trigger.check(10), bool)
def binop(x, y): if isinstance(y, Result): if x.ok and y.ok: return Ok(op(x.value, y.value)) else: return y if x.ok else x else: return NotImplemented
def _operate( self, op: Union[UnaryOp, BinaryOp, ConditionalN], *operands: Sequence[Union[numbers.Real, vs.VideoNode, "_VideoNode", ExprIR]] ) -> "_ArithmeticExpr": unwrap = lambda x: x._expr if isinstance(x, type(self)) else x result = op(*map(unwrap, operands)) return type(self)(result)
def _chance_of(self, source, op): source_sides = self.sides_with_only(source) def summarize_side(summary, side): summary.update({len(side) : (summary.get(len(side), 0) + 1)}) return summary summary_of_sides = reduce(summarize_side, source_sides, {}) return [(op(0, x), float(y)/self.num_sides()) for x, y in summary_of_sides.items()]
def f(string): """ Recurses through stream by breaking up each expression if it is not an int Applies operators to their leaf integer arguments Args : string to parse Returns : computed single integer """ y = splitstream(string) e1 = checkint(y[2]) e2 = checkint(y[3]) op = getop(y[1]) if e1 == e2: if e1: return op(int(y[2]), int(y[3])) else: return op(f(y[2]), f(y[3])) else: if e1: return op(int(y[2]), f(y[3])) else: return op(f(y[2]), int(y[3]))
def test_selection_by_datetimelike(self, datetimelike, op, expected): # GH issue #17965, test for ability to compare datetime64[ns] columns # to datetimelike df = DataFrame({'A': [pd.Timestamp('20120101'), pd.Timestamp('20130101'), np.nan, pd.Timestamp('20130103')]}) result = op(df.A, datetimelike) expected = Series(expected, name='A') tm.assert_series_equal(result, expected)
def method(self, other): if self is _: acc = partial(op, other) else: f = self._acc acc = lambda x: op(other, f(x)) ast = BinOp(op, Cte(other), self._ast) return placeholder(ast, acc)
def method(self): if self is _: acc = op else: f = self._acc acc = lambda x: op(f(x)) ast = SingleOp(op, self) return placeholder(ast, acc)
def ret(*args, **kwargs): if not args: return True if len(args) == 1: raise Exception('only one argument for assert') prev = args[0] for i in args[1:]: if not op(prev, i, **kwargs): raise AssertionError(f'{prev} {n_mes} {i}') prev = i
def binary_op(self, other): if isinstance(other, Value): fn = (lambda *args: self._combine_binop(other, op, args)) name = f'{self.name} {symbol} {other.name}' return Value(fn, name) else: transform = lambda x: op(x, other) fn = (lambda *args: self._transform(transform, args)) name = f'{self.name} {symbol} {repr(other)}' return Value(fn, name)
def compare_instance(op, self, other): hash1 = self.__hash__() if other.__hash__ is not None: hash2 = hash(other) else: hash2 = other try: return op(hash1, hash2) except Exception as ex: import utool as ut ut.printex(ex, 'could not compare hash1 to hash2', keys=['hash1', 'hash2']) raise
def maximize_value(nums, ops): assert len(nums) == len(ops) + 1 n = len(nums) dp_max = [[float('-inf') for _ in xrange(n)] for _ in xrange(n)] dp_min = [[float('inf') for _ in xrange(n)] for _ in xrange(n)] for i in xrange(n): dp_max[i][i] = dp_min[i][i] = nums[i] for l in xrange(2, n+1): for i in xrange(n-l+1): j = i + l - 1 for k in xrange(i, j): op = ops[k] options = [ op(dp_max[i][k], dp_max[k+1][j]), op(dp_max[i][k], dp_min[k+1][j]), op(dp_min[i][k], dp_max[k+1][j]), op(dp_min[i][k], dp_min[k+1][j]) ] dp_max[i][j] = max(dp_max[i][j], max(options)) dp_min[i][j] = min(dp_min[i][j], min(options)) return dp_max[0][n-1]
def fun(self, value): raise NotImplementedError() original_value = value if isinstance(value, Expression): value = value.expression else: value = nl.Constant(value) return Operation(self.query_builder, op(self.expression, value), op, (self, original_value), infix=True)
def comp(args): if len(args) < 2: raise SchemeException(name + ": requires at least 2 arguments") head, tail = args[0], args[1:] if not isinstance(head, W_String): raise SchemeException(name + ": not given a string") for t in tail: if not isinstance(t, W_String): raise SchemeException(name + ": not given a string") if not op(head, t): return values.w_false head = t return values.w_true
def comp(args): if len(args) < 2: raise SchemeException(name + ": requires at least 2 arguments") head, tail = args[0], args[1:] if not isinstance(head, values.W_Character): raise SchemeException(name + ": not given a character") for t in tail: if not isinstance(t, values.W_Character): raise SchemeException(name + ": not given a character") if not op(head.value, t.value): return values.w_false head = t return values.w_true
def comp(args): if len(args) < 2: raise SchemeException(name + ": requires at least 2 arguments") head = args[0] if not isinstance(head, W_String): raise SchemeException(name + ": not given a string") for i in range(1, len(args)): t = args[i] if not isinstance(t, W_String): raise SchemeException(name + ": not given a string") if not op(head, t): return values.w_false head = t return values.w_true
def binary_op(x1, x2, op): x_size = 0 y_size = 0 nodata = None driver = None georef = None proj = None if isinstance(x1, Number) and isinstance(x2, Number): return op(x1, x2); else: if isinstance(x1, Raster): if rank == 0: (x_size, y_size) = x1.x_size, x1.y_size (nodata, driver, georef, proj) = x1.get_geo_info() x1 = transfer_data(x1) if isinstance(x2, Raster): if rank == 0: (x_size, y_size) = x2.x_size, x2.y_size (nodata, driver, georef, proj) = x2.get_geo_info() x2 = transfer_data(x2) proc_result = op(x1, x2) proc_data = gather_data(proc_result, x_size, y_size) comm.Barrier() return Raster(None, proc_data, nodata, driver, georef, proj)
def method(self, other): if isinstance(other, placeholder): if self is _ and other is _: acc = lambda x: op(x, x) elif self is _: f = other._acc acc = lambda x: op(x, f(x)) else: g = self._acc f = other._acc acc = lambda x: op(g(x), f(x)) ast = BinOp(op, self._ast, other._ast) else: if self is _: acc = lambda x: op(x, other) else: f = self._acc acc = lambda x: op(f(x), other) ast = BinOp(op, self._ast, Cte(other)) return placeholder(ast, acc)
def compte(digits): """ Recursive auxiliary function to solve the problem """ for digit in digits: if digit.n == self.total: # Terminal case : if the total is in the list, it's ok return digit elif self.best is None or abs(self.total - digit.n) < abs(self.total - self.best.n): # We keep trace of the closest result found self.best = digit for idg, g in enumerate(digits): for idh, h in enumerate(digits[idg + 1:]): # We test all the combinations (not permutations). All we miss are # not commutative operations (- and /), but only the case where g > h # are significative, so we reorder them. We also copy the digit list and remove # the two digits we are working on, as they will be replaced by the result of their operation new_digits = digits[:] new_digits.pop(idg) new_digits.pop( idg + idh ) # There is an hidden +1-1 (-1 because we have removed one before) i, j = max(g, h, key=lambda x: x.n), min(g, h, key=lambda x: x.n) # Iterate over operators and recursion for astop, op in operators.iteritems(): try: r = compte(new_digits + [ digit_ast(n=op(i.n, j.n), ast=ast.BinOp( i.ast, astop, j.ast)) ]) # Stop if we have found a solution if r: return r except CalcError: pass return None
def find_series_and_calc(df, base_series: pd.Series, tags: list, operations: list, transformations: list): assert len(tags) == len(operations) and len(transformations) == len( tags), "ERR" res = base_series for idx, tag in enumerate(tags): try: temp_series = df.loc[tag].fillna(0) op = operations[idx] trans = transformations[idx] if trans != None: temp_series = trans(temp_series) res = op(res, temp_series) except: pass return res
def create_targets(receipts, events, target_fields): """ Merge current and historical data to produce a training set The information in 'receipts' should contain current (i.e. "correct") data for the receipts. The 'events' dataframe on the other hand contains historical data when a specific kind of event has occurred. By comparing the state at those two points we can determine whether the receipt has been correct at the time of the event, which is used as the target for training a classifier. """ valid_rows = receipts.index & events.index result = pd.DataFrame(index=valid_rows) result.index.name = 'id' for output_name, receipts_column, events_column, op in fields_to_compute: result[output_name] = op(receipts.ix[valid_rows, receipts_column], events.ix[valid_rows, events_column]) result['target_val'] = np.all(result[target_fields], axis=1) logging.info('The fields of result are: %s' % result.columns) return result
def visit_binary_expression(self, binary_expr, ctx): left = self.visit(binary_expr.left, ctx) right = self.visit(binary_expr.right, ctx) op = BINARY_OPS.get(binary_expr.op) return op(left, right)
def eval(x, env=global_env,lvl=0,traced=False): "Evaluate an expression in an environment." this = x[0] if isa(x,list) else x if this in env and env.traced.get(this): traced = True if traced: print " " * lvl, str(lvl) + ":", "(" + str(this) + ")" print x if isa(x, Symbol): # variable reference return env.find(x)[x] elif not isa(x, list): # constant literal return x elif x[0] == 'load': tmp=eval(x[1],env,lvl+1) return eload(tmp) elif x[0] == 'quote' or x[0] == "'": (_, exp) = x return exp elif x[0] == 'if': # (if test conseq alt) (_, test, conseq, alt) = x return eval((conseq if eval(test, env) else alt), env,lvl+1, traced) elif x[0] == 'and': for exp in x[1:]: if not exp: return False return True elif x[0] == 'or': for exp in x[1:]: if exp: return True return False elif x[0] == 'map': mapList = [] op = eval(x[1], env) for arg in eval(x[2], env): mapList.append([op(eval(ar, env))]) return mapList elif x[0] == 'reduce': argList = eval(x[2], env) op = eval(x[1], env) if len(x) == 3: agg = eval(argList.pop(), env) else: agg = eval(x[3], env) for arg in argList: agg = op(agg, eval(arg, env)) return agg elif x[0] == 'set!': # (set! var exp) (_, var, exp) = x env.find(var)[var] = eval(exp, env,lvl+1, traced) elif x[0] == 'define': # (define var exp) (_, var, exp) = x env[var] = eval(exp, env,lvl+1, traced) elif x[0] == 'lambda': # (lambda (var*) exp) (_, vars, exp) = x return lambda *args: eval(exp, Env(vars, args, env),lvl+1, traced) elif x[0] == 'begin': # (begin exp*) for exp in x[1:]: val = eval(exp, env,lvl+1, traced) return val elif x[0] == 'trace': z=env.find(x[1]) z.traced[x[1]]=True print '('+x[1].upper() + ')' elif x[0] == 'untrace': (_, var) = x env.traced[var] = False else: # (proc exp*) y=global_env.find(x[0]) z=y.traced exps = [eval(exp, env,lvl+1, traced) for exp in x] proc = exps.pop(0) #print ">calling", proc if ((x[0]) in z) and z[x[0]]: print ' ' * y.level + str((y.level -1)) + ': (' + str(x[0]), str(exps[0:]).strip('[]') + ')' y.level += 1 val= proc(*exps) if ((x[0]) in z) and z[x[0]]: print ' ' * (y.level-1) + str((y.level - 2)) + ': returns ' + str(val) y.level -= 1 return val
def __call__(self, env): operands = [op(env) for op in self.operands] with np.errstate(all='ignore'): return self.func.func(*operands)
def test_scalar_agg_binops(op): assert_dynd_eq(op(s_a, s_b)._data, op(a, b)) assert_dynd_eq(op(s_a, 2)._data, op(a, 2)) assert_dynd_eq(op(s_b, 2)._data, op(b, 2)) assert_dynd_eq(op(s_a, 2.)._data, op(a, 2.)) assert_dynd_eq(op(s_b, 2.)._data, op(b, 2.)) assert_dynd_eq(op(2, s_a)._data, op(2, a)) assert_dynd_eq(op(2, s_b)._data, op(2, b)) assert_dynd_eq(op(2., s_a)._data, op(2., a)) assert_dynd_eq(op(2., s_b)._data, op(2., b))
#coding: utf-8 from show_help import * from op import * i = raw_input().decode('utf-8') print show_help(i) print op(i)
def __call__(self, env): operands = [op(env) for op in self.operands] return self.func.func(*operands)
def test_scalar_agg_bool(op): np_c = nd.as_numpy(c) np_d = nd.as_numpy(d) assert_dynd_eq(op(s_c, s_d)._data, op(np_c, np_d), False) assert_dynd_eq(op(s_c, True)._data, op(np_c, True), False) assert_dynd_eq(op(s_d, True)._data, op(np_d, True), False) assert_dynd_eq(op(s_c, True)._data, op(np_c, True), False) assert_dynd_eq(op(s_d, True)._data, op(np_d, True), False) assert_dynd_eq(op(True, s_c)._data, op(True, np_c), False) assert_dynd_eq(op(True, s_d)._data, op(True, np_d), False) assert_dynd_eq(op(True, s_c)._data, op(True, np_c), False) assert_dynd_eq(op(True, s_d)._data, op(True, np_d), False)
def execute_operation(self, other_access_handle, operator): other_access = other_access_handle.access op = _OPERATORS[operator] return self._create_access_path(op(self._obj, other_access._obj))
def satisfied_by(self, left, right): op = self.op_map[self.elements[0].string] return op(left, right)
def test_operations(self): values = np.arange(12).reshape(3, 4) axc1 = Index("a", [10, 20, 30]) axc2 = Index("b", ["a", "b", "c", "d"]) c = Cube(values, [axc1, axc2]) axd1 = Index("a", [10, 20, 30]) axd2 = Index("b", ["a", "b", "c", "d"]) d = Cube(values, [axd1, axd2]) x = c * d self.assertTrue(np.array_equal(x.values, values * values)) e = Cube([0, 1, 2], [Index("a", [10, 20, 30])]) x2 = c * e self.assertTrue(np.array_equal(x2.values, values * np.array([[0], [1], [2]]))) c3 = Cube([0, 1, 2, 3], [Index("b", ["a", "b", "c", "d"])]) x3 = c * c3 self.assertTrue(np.array_equal(x3.values, values * np.array([0, 1, 2, 3]))) c3 = Cube([0, 1, 2, 3], [Index("b", ["b", "a", "c", "d"])]) x3 = c * c3 self.assertTrue(np.array_equal(x3.values, values * np.array([1, 0, 2, 3]))) values_d = np.array([0, 1]) d = Cube(values_d, [Index("d", ["d1", "d2"])]) x = c * d self.assertEqual(x.ndim, 3) self.assertEqual(x.axis(0).name, "a") self.assertEqual(x.axis(1).name, "b") self.assertEqual(x.axis(2).name, "d") self.assertTrue(np.array_equal(x.values, values.reshape(3, 4, 1) * values_d)) # operations with scalar d = 10 x = c * d self.assertTrue(np.array_equal(x.values, values * d)) x = d * c self.assertTrue(np.array_equal(x.values, values * d)) # operations with numpy.ndarray d = np.arange(4) x = c * d self.assertTrue(np.array_equal(x.values, values * d)) x = d * c self.assertTrue(np.array_equal(x.values, values * d)) d = np.arange(3).reshape(3, 1) x = c * d self.assertTrue(np.array_equal(x.values, values * d)) x = d * c self.assertTrue(np.array_equal(x.values, values * d)) # matching Index and Series values_d = np.array([0, 1]) d = Cube(values_d, Axis("a", [10, 10])) x = c * d self.assertTrue(np.array_equal(x.values, values.take([0, 0], 0) * values_d[:, np.newaxis])) values_d = np.array([0, 1, 2, 3]) d = Cube(values_d, Axis("b", ["d", "d", "c", "a"])) x = c * d self.assertTrue(np.array_equal(x.values, values.take([3, 3, 2, 0], 1) * values_d)) # unary plus and minus c = year_quarter_cube() self.assertTrue(np.array_equal((+c).values, c.values)) self.assertTrue(np.array_equal((-c).values, -c.values)) c = year_quarter_cube() + 1 # +1 to prevent division by zero error import operator as op ops = [op.add, op.mul, op.floordiv, op.truediv, op.sub, op.pow, op.mod, # arithmetics ops op.eq, op.ne, op.ge, op.le, op.gt, op.lt, # comparison ops op.and_, op.or_, op.xor, op.rshift, op.lshift] # bitwise ops # operations with scalar d = 2 for op in ops: self.assertTrue(np.array_equal(op(c, d).values, op(c.values, d))) self.assertTrue(np.array_equal(op(d, c).values, op(d, c.values))) # oprations with numpy array d = (np.arange(12).reshape(3, 4) / 6 + 1).astype(np.int) # +1 to prevent division by zero error for op in ops: self.assertTrue(np.array_equal(op(c, d).values, op(c.values, d))) self.assertTrue(np.array_equal(op(d, c).values, op(d, c.values)))
def lower(a, b): return op(unichr(unicodedb.tolower(ord(a))), unichr(unicodedb.tolower(ord(b))))
def bool_value(self, left, right, data): op = self.op_map[self.elements[0].string] return op(left.bool_value(data), right.bool_value(data))