def cylinder_grasp_affordance(self, gripper, obj_input): frame = obj_input.get_frame() shape = obj_input.get_dimensions() cylinder_z = frame.col(2) cylinder_pos = pos_of(frame) gripper_x = gripper.frame.col(0) gripper_z = gripper.frame.col(2) gripper_pos = pos_of(gripper.frame) c_to_g = gripper_pos - cylinder_pos zz_align = sp.Abs(gripper_z.dot(cylinder_z)) xz_align = gripper_x.dot(cylinder_z) dist_z = cylinder_z.dot(c_to_g) border_z = (shape[2] - gripper.height) * 0.5 cap_dist_normalized_signed = dist_z / border_z cap_dist_normalized = sp.Abs(cap_dist_normalized_signed) cap_top_grasp = 1 - sp.Max(-xz_align * sp.Min(cap_dist_normalized_signed, 1), 0) cap_bottom_grasp = 1 - sp.Min(xz_align * sp.Max(cap_dist_normalized_signed, -1), 0) dist_z_center_normalized = sp.Max(1 - cap_dist_normalized, 0) dist_ax = sp.sqrt(frame.col(0).dot(c_to_g) ** 2 + frame.col(1).dot(c_to_g) ** 2) center_grasp = (1 - dist_z_center_normalized - dist_ax) * zz_align return sp.Max(center_grasp, cap_top_grasp, cap_bottom_grasp) * obj_input.get_class_probability()
def FuckedUpMax(*args): if len(args) == 1: return args[0] # expand all expressions: args = [a.expand() for a in args] # Filter expressions with less than the maximum number of symbols max_symbols = max([len(a.free_symbols) for a in args]) args = list( filter(lambda a: len(a.free_symbols) == max_symbols, args)) if max_symbols == 0: return sympy.Max(*args) # Filter symbols with lower exponent max_coeffs = 0 for a in args: for s in a.free_symbols: max_coeffs = max(max_coeffs, len(sympy.Poly(a, s).all_coeffs())) def coeff_filter(a): return max( 0, 0, *[ len(sympy.Poly(a, s).all_coeffs()) for s in a.free_symbols ]) == max_coeffs args = list(filter(coeff_filter, args)) m = sympy.Max(*args) #if m.is_Function: # raise ValueError("Could not resolve {} to maximum.".format(m)) return m
def calc_set_union(set_a, set_b): if isinstance(set_a, subsets.Indices) or isinstance(set_b, subsets.Indices): raise NotImplementedError('Set union with indices is not implemented.') if not (isinstance(set_a, subsets.Range) and isinstance(set_b, subsets.Range)): raise TypeError('Can only compute the union of ranges.') if len(set_a) != len(set_b): raise ValueError('Range dimensions do not match') union = [] for range_a, range_b in zip(set_a, set_b): r_union = [] for i in range(3): if isinstance(range_a[i], SymExpr): a_exact = range_a[i].expr a_approx = range_a[i].approx else: a_exact = range_a[i] a_approx = range_a[i] if isinstance(range_b[i], SymExpr): b_exact = range_b[i].expr b_approx = range_b[i].approx else: b_exact = range_b[i] b_approx = range_b[i] if i in {0, 2}: r_union.append(SymExpr(sympy.Min(a_exact, b_exact), sympy.Min(a_approx, b_approx))) else: r_union.append(SymExpr(sympy.Max(a_exact, b_exact), sympy.Max(a_approx, b_approx))) union.append(r_union) # union.append([ # sympy.Min(range_a[0], range_b[0]), # sympy.Max(range_a[1], range_b[1]), # sympy.Min(range_a[2], range_b[2]), # ]) return subsets.Range(union)
def hat_sympy(x, x0, a=0, b=1): '''Sympy version''' x, x0_, a_, b_ = sp.symbols('x x0 a b') x = (x - a_) / (b_ - a_) x0_ = (x0 - a_) / (b_ - a_) f = sp.Max(0, x) / x0_ - sp.Max(0, x - x0_) / x0_ / (1 - x0_) + sp.Max( 0, x - 1) / (1 - x0_) return f.subs({a_: a, b_: b, x0_: x0})
def and_(truth0, truth1): """ TODO: include t.sigma """ truth0.expression = sympy.sympify(truth0.expression) truth1.expression = sympy.sympify(truth1.expression) exp = sympy.Max(truth0.expression, truth1.expression) sig = sympy.Max(truth0.sigma, truth1.sigma) return Truth(exp, sig)
def _execute_controller(self): rate = rospy.Rate(10) P, I = sp.var('p i') min_linear_vel = sp.var("minLinearVel") min_angular_vel = sp.var("minAngularVel") distErr, distVerticalErr, vertDiff, lastLinearOut = sp.var( 'distErr distVerticalErr vertDiff lastLinearOut') anglErr, lastAngularOut, anglDiff = sp.var( 'anglErr lastAngularOut anglDiff') self.linear_eq = sp.Piecewise( (sp.Max(P * distErr + I * lastLinearOut, min_linear_vel), sp.And(sp.Abs(anglErr) < anglDiff, distErr >= 0)), (sp.Min(P * distErr + I * lastLinearOut, -min_linear_vel), sp.And(sp.Abs(anglErr) < anglDiff, distErr < 0)), (0, sp.Abs(anglErr) >= anglDiff)) self.linear_vertical_eq = sp.Piecewise( (sp.Max(P * distVerticalErr + I * lastLinearOut, min_linear_vel), distVerticalErr > vertDiff), (0, True)) angular_eq_temp = P * anglErr + I * lastAngularOut self.angular_eq = sp.Piecewise( (sp.Min(angular_eq_temp, -min_angular_vel), angular_eq_temp < 0), (sp.Max(angular_eq_temp, min_angular_vel), angular_eq_temp >= 0)) constansts = { P: self.current_config["p"], I: self.current_config["i"], min_linear_vel: self.current_config["min_linear_vel"], min_angular_vel: self.current_config["min_angular_vel"], anglDiff: self.current_config["angular_diff"], vertDiff: self.current_config["vertical_diff"] } variables = [ distErr, distVerticalErr, lastLinearOut, anglErr, lastAngularOut ] self.linear_eq = self.linear_eq.subs(constansts) self.linear_vertical_eq = self.linear_vertical_eq.subs(constansts) self.angular_eq = self.angular_eq.subs(constansts) while not rospy.is_shutdown(): if self._goal != None and self._enabled: self._command_to(self._goal, variables) self._reach_publisher.publish(Bool(self._reach)) rate.sleep()
def intersect(self, other): minCorner = [ sp.Max(self.minCorner[d], other.minCorner[d]) for d in range(self.dim) ] maxCorner = [ sp.Max(minCorner[d], sp.Min(self.maxCorner[d], other.maxCorner[d])) for d in range(self.dim) ] return AABB(minCorner, maxCorner)
class Cell(I.Cell): """Jobst: write docstring.""" # abbreviation: balance = (I.Cell.photosynthesis_carbon_flow - I.Cell.terrestrial_respiration_carbon_flow) atmospheric_carbon_density = sp.Max( 0, B.Cell.world.atmospheric_carbon / B.Cell.world.sum.cells.land_area) processes = [ # using symbolic expressions for performance and legibility: Explicit( "photosynthesis flow", [I.Cell.photosynthesis_carbon_flow], [((B.Cell.environment.basic_photosynthesis_productivity - B.Cell. environment.photosynthesis_sensitivity_on_atmospheric_carbon * atmospheric_carbon_density) * sp.sqrt(atmospheric_carbon_density) * (1 - I.Cell.terrestrial_carbon / (B.Cell.environment.terrestrial_carbon_capacity_per_area * B.Cell.land_area))) * I.Cell.terrestrial_carbon]), Explicit( "respiration flow", [I.Cell.terrestrial_respiration_carbon_flow], [(B.Cell.world.environment.basic_respiration_rate + B.Cell.world. environment.respiration_sensitivity_on_atmospheric_carbon * atmospheric_carbon_density) * I.Cell.terrestrial_carbon]), ODE("effect of photosynthesis and respiration", [I.Cell.terrestrial_carbon, B.Cell.world.atmospheric_carbon], [balance, -balance]), ]
def find_exponents(expr, var): """ Find all exponents of var in expr """ f = expr.to_sympy() x = var.to_sympy() if f is None or x is None: return {0} result = set() for t in f.expand(power_exp=False).as_ordered_terms(): coeff, exponent = t.as_coeff_exponent(x) if exponent: result.add(from_sympy(exponent)) else: # find exponent of terms multiplied with functions: sin, cos, log, exp, ... # e.g: x^3 * Sin[x^2] should give 3 muls = [ term.as_coeff_mul(x)[1] if term.as_coeff_mul(x)[1] else (sympy.Integer(0), ) for term in coeff.as_ordered_terms() ] expos = [ term.as_coeff_exponent(x)[1] for mul in muls for term in mul ] result.add(from_sympy(sympy.Max(*[e for e in expos]))) return sorted(result)
def visit_IfNode(self, if_node: IfNode): self.visit(if_node.condition) cond_tc = if_node.condition.time_complexity self.backward_table_manager.push_table(scope_type='if') true_tc = 0 for child in if_node.true_stmt: self.visit(child) true_tc += child.time_complexity if true_tc == 0: true_tc = 1 if len(if_node.false_stmt) != 0: self.backward_table_manager.push_table(scope_type='else') false_tc = 0 for child in if_node.false_stmt: self.visit(child) false_tc += child.time_complexity if false_tc == 0: false_tc = 1 if len(if_node.false_stmt) != 0: self.backward_table_manager.pop_table() self.backward_table_manager.pop_table() if_node.time_complexity = cond_tc + sympy.Max(true_tc, false_tc) pass
def test_kappa_expressions(): Monomer('A', ['site'], {'site': ['u']}) Parameter('two', 2) Parameter('kr', 0.1) Parameter('num_A', 1000) Expression('kf', 1e-5 / two) Expression('test_sqrt', -1 + sympy.sqrt(1 + two)) Expression('test_pi', sympy.pi) Expression('test_e', sympy.E) Expression('test_log', sympy.log(two)) Expression('test_exp', sympy.exp(two)) Expression('test_sin', sympy.sin(two)) Expression('test_cos', sympy.cos(two)) Expression('test_tan', sympy.tan(two)) Expression('test_max', sympy.Max(two, kr, 2.0)) Expression('test_min', sympy.Min(two, kr, 2.0)) Expression('test_mod', sympy.Mod(10, two)) Expression('test_piecewise', sympy.Piecewise((0.0, two < 400.0), (1.0, True))) Initial(A(site=('u')), num_A) Rule('dimerize_fwd', A(site='u') + A(site='u') >> A(site=('u', 1)) % A(site=('u', 1)), kf) Rule('dimerize_rev', A(site=('u', 1)) % A(site=('u', 1)) >> A(site='u') + A(site='u'), kr) # We need an arbitrary observable here to get a Kappa output file Observable('A_obs', A()) # Accommodates Expression in kappa simulation run_simulation(model, time=0) Rule('degrade_dimer', A(site=('u', ANY)) >> None, kr) Observable('dimer', A(site=('u', ANY))) # Accommodates site with explicit state and arbitrary bond run_simulation(model, time=0, seed=_KAPPA_SEED)
def transform_set(x, expr, sympy_set): """ Transform a sympy_set by an expression >>> x = sympy.Symbol('x') >>> domain = sympy.Interval(-sympy.pi / 4, -sympy.pi / 6, False, True) | sympy.Interval(sympy.pi / 6, sympy.pi / 4, True, False) >>> transform_set(x, -2 * x, domain) [-pi/2, -pi/3) U (pi/3, pi/2] """ if isinstance(sympy_set, sympy.Union): return sympy.Union( transform_set(x, expr, arg) for arg in sympy_set.args) if isinstance(sympy_set, sympy.Intersection): return sympy.Intersection( transform_set(x, expr, arg) for arg in sympy_set.args) f = sympy.Lambda(x, expr) if isinstance(sympy_set, sympy.Interval): left, right = f(sympy_set.left), f(sympy_set.right) if left < right: new_left_open = sympy_set.left_open new_right_open = sympy_set.right_open else: new_left_open = sympy_set.right_open new_right_open = sympy_set.left_open return sympy.Interval(sympy.Min(left, right), sympy.Max(left, right), new_left_open, new_right_open) if isinstance(sympy_set, sympy.FiniteSet): return sympy.FiniteSet(list(map(f, sympy_set)))
def test_trig_solution(theta, phi, lamb, xi, theta1, theta2): r"""Test if arguments are a solution to a system of equations. .. math:: \cos(\phi+\lambda) \cos(\\theta) = \cos(xi) * \cos(\\theta1+\\theta2) \sin(\phi+\lambda) \cos(\\theta) = \sin(xi) * \cos(\\theta1-\\theta2) \cos(\phi-\lambda) \sin(\\theta) = \cos(xi) * \sin(\\theta1+\\theta2) \sin(\phi-\lambda) \sin(\\theta) = \sin(xi) * \sin(-\\theta1+\\theta2) Returns the maximum absolute difference between right and left hand sides as a Max symbol. See: http://docs.sympy.org/latest/modules/functions/elementary.html?highlight=max """ delta1 = sympy.Abs( sympy.cos(phi + lamb) * sympy.cos(theta) - sympy.cos(xi) * sympy.cos(theta1 + theta2)) delta2 = sympy.Abs( sympy.sin(phi + lamb) * sympy.cos(theta) - sympy.sin(xi) * sympy.cos(theta1 - theta2)) delta3 = sympy.Abs( sympy.cos(phi - lamb) * sympy.sin(theta) - sympy.cos(xi) * sympy.sin(theta1 + theta2)) delta4 = sympy.Abs( sympy.sin(phi - lamb) * sympy.sin(theta) - sympy.sin(xi) * sympy.sin(-theta1 + theta2)) return sympy.Max(delta1, delta2, delta3, delta4)
def _argmax(val): "A sympy implementation of argmax" maxval = sp.Max(*val) pieces = [(i, sp.Eq(val[i], maxval)) for i in range(len(val) - 1)] pieces.append((len(val) - 1, True)) return sp.Piecewise(*pieces)
def detect_reduction_type(wcr_str, openmp=False): """ Inspects a lambda function and tries to determine if it's one of the built-in reductions that frameworks such as MPI can provide. :param wcr_str: A Python string representation of the lambda function. :param openmp: Detect additional OpenMP reduction types. :return: dtypes.ReductionType if detected, dtypes.ReductionType.Custom if not detected, or None if no reduction is found. """ if wcr_str == '' or wcr_str is None: return None # Get lambda function from string wcr = eval(wcr_str) wcr_ast = ast.parse(wcr_str).body[0].value.body # Run function through symbolic math engine a = sympy.Symbol('a') b = sympy.Symbol('b') try: result = wcr(a, b) except (TypeError, AttributeError, NameError): # e.g., "Cannot determine truth value of relational" result = None # Check resulting value if result == sympy.Max(a, b) or (isinstance(wcr_ast, ast.Call) and isinstance(wcr_ast.func, ast.Name) and wcr_ast.func.id == 'max'): return dtypes.ReductionType.Max elif result == sympy.Min(a, b) or (isinstance(wcr_ast, ast.Call) and isinstance(wcr_ast.func, ast.Name) and wcr_ast.func.id == 'min'): return dtypes.ReductionType.Min elif result == a + b: return dtypes.ReductionType.Sum elif result == a * b: return dtypes.ReductionType.Product elif result == a & b: return dtypes.ReductionType.Bitwise_And elif result == a | b: return dtypes.ReductionType.Bitwise_Or elif result == a ^ b: return dtypes.ReductionType.Bitwise_Xor elif isinstance(wcr_ast, ast.BoolOp) and isinstance(wcr_ast.op, ast.And): return dtypes.ReductionType.Logical_And elif isinstance(wcr_ast, ast.BoolOp) and isinstance(wcr_ast.op, ast.Or): return dtypes.ReductionType.Logical_Or elif (isinstance(wcr_ast, ast.Compare) and isinstance(wcr_ast.ops[0], ast.NotEq)): return dtypes.ReductionType.Logical_Xor elif result == b: return dtypes.ReductionType.Exchange # OpenMP extensions elif openmp and result == a - b: return dtypes.ReductionType.Sub elif openmp and result == a / b: return dtypes.ReductionType.Div return dtypes.ReductionType.Custom
def calculate_duration(self) -> ExpressionScalar: duration_expressions = [ entries[-1].t for entries in self._entries.values() ] duration_expression = sympy.Max(*(expr.sympified_expression for expr in duration_expressions)) return ExpressionScalar(duration_expression)
def relu(input, result): assert input.spatial_dimensions == result.spatial_dimensions assert input.index_shape == result.index_shape assignments = [] for i in range(input.index_shape[0]): assignments.append(pystencils.Assignment(result.center(i), sympy.Max(input.center(i), 0))) return assignments
def fit(self, j, data): # get range variables self.min_x = data.min() self.max_x = data.max() # get the fourier data (data in transformed in frequencies) fourier_data = pd.Series(range(j)).apply( lambda i: self.cos_fun(i, data, self.min_x, self.max_x)) # use mean to get the coeff. estimators fourier_coef = fourier_data.mean(axis=1) # fix the intercept fourier_coef.iloc[0] = 1 # sympy stuff x = sympy.symbols("x") coef = np.array(fourier_coef).reshape(1, -1) # array of the basis funcs funcs = np.array(pd.Series(range(len(fourier_coef))) \ .apply(lambda i: self.cos_fun2(i, x, self.min_x, self.max_x))) \ .reshape(-1, 1) pdf = np.dot(coef, funcs)[0][0] self.pdf = sympy.Max(0, pdf) self.norm_const()
def setUp(self): self.input_data = {"Species": boppy.core.VariableCollection(["x_s", "x_i", "x_r"]), "Parameters": boppy.core.ParameterCollection({'k_i': 1, 'k_r': 0.05, 'k_s': 0.01, 'N': 100}), "Rate functions": ["4 - 6", "k_i * x_i * x_s / N ", "-3* 2 * k_i * x_i * x_s / max(x_s, x_i) + 2 * x_i - x_i + x_r"], "Reactions": ["x_s => x_i", "x_s + x_i => x_r", "3x_s + x_i => x_r"], "Initial conditions": np.array([80, 20, 0]), } self.expected_update_vector = [np.array([-1, 1, 0]), np.array([-1, -1, 1]), np.array([-3, -1, 1])] self.expected_depends_on_vector = np.array([[0], [0, 1], [0, 1]]) self.expected_affects_vector = np.array([[0, 1], [0, 1, 2], [0, 1, 2]]) x_s, x_i, x_r = sym.symbols("x_s x_i x_r") self.expected_rate_functions = [sym.Integer(-2), x_s * x_i / 100, -6.0 * x_s * x_i / sym.Max(x_i, x_s) + 1.0 * x_i + x_r] self.rate_func_coll = boppy.core.RateFunctionCollection(self.input_data["Rate functions"], self.input_data["Species"], self.input_data["Parameters"]) np.random.seed(42)
class Function: ''' include common functions defined by sympy ''' x = sym.Symbol('x') sigmoid = 1.0 / (1 + sym.exp(-1 * x)) relu = sym.Max(x, 0)
def cie_optical_depth_correction(self): ciefudge = 1.0 mdensity = sympy.Symbol('mdensity') tau = (mdensity / 1.96e16)**2.0 tau = sympy.Max(mdensity, 1e-5) ciefudge = sympy.Min((1.0 - sympy.exp(-tau)) / tau, 1.0) return ciefudge
def sort(fs): fs = list(fs) for i in range(len(fs) - 1, -1, -1): for j in range(i, -1, -1): Fi = fs[i] Fj = fs[j] fs[j] = sympy.Min(Fi, Fj) fs[i] = sympy.Max(Fi, Fj) return fs
def simplify_ext(expr): """ An extended version of simplification with expression fixes for sympy. :param expr: A sympy expression. :return: Simplified version of the expression. """ a = sympy.Wild('a') b = sympy.Wild('b') c = sympy.Wild('c') # Push expressions into both sides of min/max. # Example: Min(N, 4) + 1 => Min(N + 1, 5) dic = expr.match(sympy.Min(a, b) + c) if dic: return sympy.Min(dic[a] + dic[c], dic[b] + dic[c]) dic = expr.match(sympy.Max(a, b) + c) if dic: return sympy.Max(dic[a] + dic[c], dic[b] + dic[c]) return expr
def test_duration(self): lhs = DummyPulseTemplate(duration=ExpressionScalar('x'), defined_channels={'a', 'b'}, parameter_names={'x', 'y'}) rhs = DummyPulseTemplate(duration=ExpressionScalar('y'), defined_channels={'a', 'c'}, parameter_names={'x', 'z'}) arith = lhs - rhs self.assertEqual(sympy.Max('x', 'y'), arith.duration.underlying_expression)
def _infer_binary_ops(self, node): funcs = { 'Add': lambda l: l[0] + l[1], 'Div': lambda l: l[0] // l[1], # integer div in sympy 'Max': lambda l: sympy.Max(l[0], l[1]), 'Min': lambda l: sympy.Min(l[0], l[1]), 'Mul': lambda l: l[0] * l[1], 'Sub': lambda l: l[0] - l[1] } assert node.op_type in funcs self._compute_on_sympy_data(node, funcs[node.op_type])
def widen_bound(op: IComparisonOp[Any], old: sym.Number, new: sym.Number) -> sym.Number: if op == operator.le: mx = sym.Max(old, new) # type: ignore assert isinstance(mx, sym.Number) return mx elif op == operator.ge: mn = sym.Min(old, new) # type: ignore assert isinstance(mn, sym.Number) return mn else: raise Exception("unsupported operator")
class Functions(object): """ include common functions defined by sympy """ x = sym.Symbol('x') v1 = vec.Vector('v1') v2 = vec.Vector('v2') sigmoid = 1.0 / (1 + sym.exp(-1 * x)) relu = sym.Max(x, 0)
def _infer_Range(self, node): vi = self.known_vi_[node.output[0]] input_data = self._get_int_values(node) if all([i is not None for i in input_data]): start = as_scalar(input_data[0]) limit = as_scalar(input_data[1]) delta = as_scalar(input_data[2]) new_shape = [sympy.Max(sympy.ceiling((limit - start) / delta), 0)] else: new_dim = self._new_symbolic_dim_from_output(node) new_shape = [self.symbolic_dims_[new_dim]] vi.CopyFrom( helper.make_tensor_value_info( node.output[0], self.known_vi_[node.input[0]].type.tensor_type.elem_type, get_shape_from_sympy_shape(new_shape)))
def construct_discrete_upwind_matrix(input_matrix, tau, velocity, effective_viscosity, effective_reaction, gauss_shape_functions, gausss_shape_function_derivatives, velocity_convection_operator): number_of_nodes = len(gauss_shape_functions) dimension = len(velocity) output_matrix = create_zero_matrix(number_of_nodes, number_of_nodes) # gamma = sym.Symbol(r"\gamma") gamma = 1.0 for a in range(number_of_nodes): for b in range(a + 1, number_of_nodes): value = 0.0 dNadNb = 0.0 for i in range(dimension): dNadNb += gausss_shape_function_derivatives[a][ i] * gausss_shape_function_derivatives[b][i] value += effective_viscosity * dNadNb value += tau * (gauss_shape_functions[a] * effective_reaction + velocity_convection_operator[a]) * ( gauss_shape_functions[b] * effective_reaction + velocity_convection_operator[b]) value += gauss_shape_functions[a] * gauss_shape_functions[ b] * effective_reaction value += sym.Max( gauss_shape_functions[a] * velocity_convection_operator[a], gauss_shape_functions[b] * velocity_convection_operator[b]) output_matrix[a][b] = -1.0 * gamma * value output_matrix[b][a] = output_matrix[a][b] for a in range(number_of_nodes): dii = 0.0 for b in range(number_of_nodes): if (a != b): dii += output_matrix[a][b] # dii += output_matrix[a][b] + input_matrix[a][b] # output_matrix[a][a] = -1.0 * dii - sym.Abs(input_matrix[a][a]) output_matrix[a][a] = -1.0 * dii return output_matrix
def calc_set_union(set_a, set_b): if isinstance(set_a, subsets.Indices) or isinstance( set_b, subsets.Indices): raise NotImplementedError('Set union with indices is not implemented.') if not (isinstance(set_a, subsets.Range) and isinstance(set_b, subsets.Range)): raise TypeError('Can only compute the union of ranges.') if len(set_a) != len(set_b): raise ValueError('Range dimensions do not match') union = [] for range_a, range_b in zip(set_a, set_b): union.append([ sympy.Min(range_a[0], range_b[0]), sympy.Max(range_a[1], range_b[1]), sympy.Min(range_a[2], range_b[2]), ]) return subsets.Range(union)