def solve(self, diff: DifferentialEq, precision=4) -> Tuple[Function]: ''' Returns tuple of (method-derived function, LTE function, GTE function) ''' # getting result function and lte result, lte, _ = self.__execute_method( diff.f, diff.solution, diff.x_0, diff.y_0, diff.x_n, diff.n, precision=precision, ) # calculate gte for all n from `n_start` to `n_end` gte = Function() for n in range(diff.n_start, diff.n_end + 1): _, _, gte_values = self.__execute_method( diff.f, diff.solution, diff.x_0, diff.y_0, diff.x_n, n, precision=precision, ) gte.append(n, max(gte_values.Y)) return result, lte, gte
class KalmanFilter: f = Function() h = Function() x = 0 P = 0 def __init__(self, *args, **kwargs): if 'f' in kwargs: self.f = kwargs['f'] if 'h' in kwargs: self.h = kwargs['h'] if 'x' in kwargs: self.x = kwargs['x'] if 'P' in kwargs: self.P = kwargs['P'] def predict(self, Q): xhat = self.f.interpolate(self.x) P = self.f.D(self.x) * self.P * self.f.D(self.x) + Q return xhat, P def update(self, xhat, P, z, R): H = self.h.D(xhat) ytilde = z - self.h.interpolate(xhat) S = H * P * H + R K = P * H / S xhat_new = xhat + K * ytilde P_new = (1 - K * H) * P return xhat_new, P_new
def grow(self, depth=None): """ Grows a random child node by 1, limited by `depth` (if provided) and arity restrictions. Returns the new node (or None if no node can be expanded). Args: depth: int (default=None) Returns: Node instance (or None) """ # Creates a random permutation of child nodes nodes_depths = list(self.descendants_and_self_with_depths()) shuffle(nodes_depths) for node, d in nodes_depths: if len(node.children) >= node.func.arity: continue if d >= depth: continue if d == depth - 1: func = Function.random_terminal() else: func = Function.random_function() child = Node(func) node.add_child(child) return child # If no children can be expanded, return None return None
def get_function(self, parameter): # find the appropriate set of data points lower_param = float("inf") upper_param = 0 lower_data = [] upper_data = [] for d in self.data: print d if d[0] < lower_param: lower_param = d[0] lower_data = d[1] if d[0] > upper_param: upper_param = d[0] upper_data = d[1] print lower_data print upper_data # now split them into some sensible number of points num_points = max(len(lower_data), len(upper_data)) lower_function = reslice_function(Function(data=lower_data), num_points) upper_function = reslice_function(Function(data=upper_data), num_points) lower_function.show() upper_function.show() return merge_functions(lower_function, upper_function, (parameter - lower_param) / (upper_param - lower_param))
def send_call_distance(): Database = json.loads(R_data.get("My_data")) print('Begin') log_db = 'Log_API_FIND_DISTANCE' lat = request.args.get('latitude', type=float) # lat lon = request.args.get('longitude', type=float) # long filters = request.args.get('range', default=1.5, type=float) # filter if type(lat) != float or type(lon) != float: log = { "timestamp": str(datetime.now()), "log": "error please check you reqeust message" } send_data(log_db, log) return jsonify({'message': 'error please check you reqeust message'}), 421 else: input_1 = Function(lat, lon, filters, Database) data = input_1.think() res = {"res": data, "timestamp": str(datetime.now())} log = {"timestamp": str(datetime.now()), "log": data} print('before_send_log' + str(datetime.now())) send_data(log_db, log) print('after_send_log' + str(datetime.now())) return jsonify(res)
def invoke(self): functions = [ Function("y = sin(x)", lambda x: np.sin(x)), Function("y = sin(x) + cos(x)", lambda x: np.sin(x) + np.cos(x)), Function("y = 3x^3 - 2x^2 + 2", lambda x: 3 * np.power(x, 3) - 2 * np.power(x, 2) + 2) ] log( "> {} Welcome to interpolation world {}\n".format( self.DASH, self.DASH), COLOR.HEADER) log("> Please choose your function:\n", COLOR.OKGREEN) for i, func in enumerate(functions): print("> {}. {}".format(i, func.to_str())) log("> Enter your option: ", COLOR.OKGREEN) opt_func = int(input()) chosen_func = functions[opt_func] log(self.DASH * 3 + '\n', COLOR.HEADER) log("> Please choose the way to generate interpolation points: \n", COLOR.OKGREEN) log("> 0. Manual\n") log("> 1. Auto generate (random points)\n") log("> Enter your option: ", COLOR.OKGREEN) opt_gene = int(input()) x = self.generate(opt_gene) y_org = chosen_func.f(x) lagrange = Lagrange(x, y_org) y_lag = [lagrange.f(xi) for xi in x] self.draw(x, y_org, y_lag, chosen_func, lagrange)
def get(self, fn, *args): """get returns the matching function from the virtual namespace. return None if it did not fund any matching function. """ func = Function(fn, self) return self.function_map.get(func.key(args=args))
def __init__(self): Function.__init__(self) self.setupUi(self) self.setFixedSize(self.width(), self.height()) # 禁止窗口拉伸和最大化 self.setWindowTitle('批量修改工具') # self.setWindowIcon(QIcon(QPixmap('./lib/img/smile_96px.png'))) self.setWindowIcon(self.smileLogo()) # self.pix = QPixmap('./res/img/long60x60.png') self.ico.setPixmap(self.chuanLogo()) self.DirChoiceBtn_1.clicked.connect(self.SelectFile_1) self.DirChoiceBtn_2.clicked.connect(self.SelectFile_2) self.DirChoiceBtn_3.clicked.connect(self.SelectFile_3) self.DirChoiceBtn_4.clicked.connect(self.SelectFile_4) self.DirChoiceBtn_5.clicked.connect(self.SelectFile_5) self.DirChoiceBtn_6.clicked.connect(self.SelectFile_6) self.DirChoiceBtn_7.clicked.connect(self.SelectFile_7) self.DirChoiceBtn_8.clicked.connect(self.SelectFile_8) self.DirChoiceBtn_9.clicked.connect(self.SelectFile_9) self.DirChoiceBtn_10.clicked.connect(self.SelectFile_10) self.time = QTimer() # 初始化计时器 self.time.setInterval(6000) # 设置计时器时间为6秒,一秒为1000毫秒 self.IpChangeBtn.clicked.connect(self.change_func) # 按钮激活计时开始,修改按钮文本 self.time.timeout.connect(self.referch) # 计时结束还原按钮文本 self.pushButton.clicked.connect(self.clear_all) self.init_view_info()
def opcode_132(self, oparg): # define MAKE_FUNCTION 132 name = self.stack.pop() mycode = self.stack.pop() f = Function(name, mycode) for i in f.freevars: f.dict[i] = self.dict[i] self.stack.push(f)
def register(self, fn): """register the function in the virtual namespace and returns an instance of callable Function that wraps the function fn """ func = Function(fn, self) self.function_map[func.key()] = fn return func
def test_cubic_derivative(self): a = cubic_derivative_approximation( Function.power(Function.identity(), Function.constant(3)), 4, 10) self.assertAlmostEqual(a(0), 0) self.assertAlmostEqual(a(2), 8) self.assertAlmostEqual(a(5), 125) self.assertAlmostEqual(a(12), 1728) self.assertAlmostEqual(a(-3), -27)
def function_decl(self, tree): class_type_object = tree._meta if len(tree.children) == 4: ident = tree.children[1] formals = tree.children[2] stmt_block = tree.children[3] else: ident = tree.children[0] formals = tree.children[1] stmt_block = tree.children[2] symbol_table_object = SymbolTableObject(scope=stack[-1], name=ident) symbol_table[( stack[-1], ident.value, )] = self.counter self.counter += 1 function = Function(name=ident.value, label=stack[-1] + "/" + ident.value) if type(tree.children[0]) == lark.tree.Tree: object_type = tree.children[0] object_type._meta = symbol_table_object self.visit(object_type) function.return_type = symbol_table_object.type else: symbol_table_object.type.name = 'void' function.return_type.name = 'void' if class_type_object: this = Tree(data='variable', children=[ Tree(data='type', children=[ Token(type_='PRIMITIVE', value=class_type_object.name) ]), Token(type_='IDENT', value='this') ]) temp = formals.children.copy() formals.children = [this] + temp stack.append(stack[-1] + "/" + ident) formals._meta = function self.visit(formals) stack.append(stack[-1] + "/_local") self.visit(stmt_block) stack.pop() # pop _local stack.pop() # pop formals if class_type_object: class_type_object.functions.append(function) pass else: function_table[function.name] = self.static_function_counter function_objects.append(function) self.static_function_counter += 1
def __init__(self, cursor, comment): Function.__init__(self, cursor, comment) self.static = cursor.is_static_method() self.virtual = cursor.is_virtual_method() self.abstract = True self._override = None self.update_abstract(cursor)
def fixed_point(self, expr_g, x0, tolerance, n): ''' It calculates an approximation to a root through finding an intersection between y = x and x = g(x) where g(x) is derivated from the function f. parameters: - x0 : initial point - expr_g: function expresion derivated from f - tolerance: maximum allowed error - n: number of iterations until failure ''' if tolerance < 0: print(f"innapropiate tolerance = {tolerance}") elif n < 1: print(f"innapropiate number of iterations = {n}") else: fx = self.__function.eval(x0) count = 0 error = tolerance + 1 data = { "x": np.array([x0], dtype=np.float64), "f(x)": np.array([fx], dtype=np.float64), "E": np.array([np.NaN], dtype=np.float64) } g = Function(expr_g) while fx != 0 and error > tolerance and count < n: xn = g.eval(x0) fx = self.__function.eval(xn) error = self.__error(x0, xn) x0 = xn count += 1 data["x"] = np.append(data["x"], [xn]) data["f(x)"] = np.append(data["f(x)"], [fx]) data["E"] = np.append(data["E"], [error]) if fx == 0: print(f"{x0} is a root") elif error < tolerance: print( f"{x0} is an approximation to a root with tolerance = {tolerance}" ) else: print(f"failure in {n} iterations") data_frame = pd.DataFrame(data, columns=("x", "f(x)", "E"), dtype=np.float64) data_frame.index.name = "n" print(data_frame)
def mutate_float(node, score_tree, eps=1e-1): """ Takes a Node object and optimizes floats greedily. Returns a new tree. Args: node: Node object to operate on score_tree: function that takes a tree and returns a fitness (as float) eps: learning rate (as float) (default=1e-1) Returns: Node object """ # Copy the tree new_tree = node.deepcopy() # Find all floating leaves floats = new_tree.all_floats() if floats == []: return None has_changed = False for f in floats: value = f.func.func() left_value = value - eps right_value = value + eps func = f.func left_func = Function.make_float_function(left_value) left_func = Function(left_func, 0, str(left_value)) right_func = Function.make_float_function(right_value) right_func = Function(right_func, 0, str(right_value)) score = score_tree(new_tree) f.func = left_func left_score = score_tree(new_tree) f.func = right_func right_score = score_tree(new_tree) max_ = max(left_score, score, right_score) if abs(max_ - left_score) < 1e-10: f.func = left_func has_changed = True elif abs(max_ - right_score) < 1e-10: f.func = right_func has_changed = True else: f.func = func if not has_changed: return None return new_tree
class Manager: ''' Class for managing changes of values of diff. eq ''' def __init__(self, diff: DifferentialEq, methods: List[Method], solution_color): self.diff = diff self.methods = methods self.functions: Dict[List[Function]] = { str(method): [Function(name=str(method), color=method.color) for _ in range(3)] for method in methods } self.solution = Function(name='Analytical solution', color=solution_color) self.update() def update(self, x_0=None, y_0=None, x_n=None, n=None, n_start=None, n_end=None): logging.info( f"Update differential eq with {x_0}, {y_0}, {x_n}, {n}, {n_start}, {n_end}" ) self.diff.x_0 = x_0 or self.diff.x_0 self.diff.y_0 = y_0 or self.diff.y_0 self.diff.x_n = x_n or self.diff.x_n self.diff.n = n or self.diff.n self.diff.n_start = n_start or self.diff.n_start self.diff.n_end = n_end or self.diff.n_end for method in self.methods: for func, new_func in zip(self.functions[method.__str__()], method.solve(self.diff)): #logging.debug(f"Function assign {func} {new_func}") func.assign(new_func) self.__update_solution() def __update_solution(self): new_solution = Function(func=self.diff.solution, start=self.diff.x_0, stop=self.diff.x_n, num=self.diff.n) self.solution.assign(new_solution) def hide_methods(self, methods: Dict[str, bool]): for method in methods: for func in self.functions[method]: func.hide = methods[method]
def function_handler(): data = request.get_json() print data commands = data.pop('commands', None) if commands is None: return jsonify({'status': 1, 'message': "错误的指令序列!", 'data': data}) func = Function(commands) func.run() return jsonify({'status': 1, 'message': "success", 'data': data})
def recursively_generate_cubics(f, left, right, depth = 5): for a in approximate(f, left, right): if is_bounded(Function.sum(f, Function.product( Function.constant(-1), a)), Interval(left, right), Interval(-.008, .008)): return [a] if depth == 0: return [] middle = (left + right) / 2 return recursively_generate_cubics(f, left, middle, depth-1) + \ recursively_generate_cubics(f, middle, right, depth-1)
def __init__(self, diff: DifferentialEq, methods: List[Method], solution_color): self.diff = diff self.methods = methods self.functions: Dict[List[Function]] = { str(method): [Function(name=str(method), color=method.color) for _ in range(3)] for method in methods } self.solution = Function(name='Analytical solution', color=solution_color) self.update()
def create_functions(self): self.functions.append(Function(0, 0, 1, dummy=True)) for i in range(1, self.num_functions+1): if i==1: self.functions.append( Function(i, self.func_cost[i], self.func_sel[i], is_first=True)) else: self.functions.append( Function(i, self.func_cost[i], self.func_sel[i], is_last=False, prev_func=self.functions[i - 1])) self.functions[i-1].next_func = self.functions[i] self.functions[self.num_functions].is_last = True
def set_data(self, data): """set_data Set the data value of the current node :param data: The data """ self.data = data self.head = self.data self.part0 = self.head.part0 self.part1 = self.head.part1 self.others = [Function(x) for x in self.get_paths_to_leaves()] if len(self.others) == 0: self.others.append(Function([]))
def __init__(self, master): self.fun = Function() self.cf = configparser.ConfigParser() self.root = master self.root.title('Reptile Douyin') self.root.resizable(width=False, height=False) width = 500 height = 180 self.root.geometry('%dx%d' % (width, height)) self.create_window() self.root.protocol("WM_DELETE_WINDOW", self.on_closing) # 协议,处理与Windows的互动
def setUp(self): # Setting up some functions data1 = {"x": [1.0, 2.0, 3.0], "y": [5.0, 6.0, 7.0]} self.dataframe1 = pd.DataFrame(data=data1) data2 = {"x": [1.0, 2.0, 3.0], "y": [7.0, 8.0, 9.0]} self.dataframe2 = pd.DataFrame(data=data2) self.function1 = Function("name") self.function1.dataframe = self.dataframe1 self.function2 = Function("name") self.function2.dataframe = self.dataframe2
def __init__(self, head, others, name="tf"): """__init__ Initialize a fake tree function. For now, the order of the nodes which are not the head is not important. :param head: The head of the tree. It is a path :param others: The other paths :param name: """ self.head = Function(head) self.others = [Function(x) for x in others] self.part0 = self.head.part0 self.part1 = self.head.part1 self.name = name
def run(step, point_type, lambda_p, method): f = Function(lambda_p) n = f.get_size() # x size # Initial point if point_type == "const": x0 = np.ones(n) else: x0 = np.random.uniform(-2, 2, n) mxitr = 50000 # Max number of iterations tol_g = 1e-8 # Tolerance for gradient tol_x = 1e-8 # Tolerance for x tol_f = 1e-8 # Tolerance for function # Method for step update if step == "fijo": msg = "StepFijo" elif step == "hess": msg = "StepHess" else: msg = "Backtracking" step_size = 1 # Gradient step size for "StepFijo" method # Estimate minimum point through optimization method chosen if method == "gd": alg = GD() elif method == "newton": alg = Newton() else: print("\n Error: Invalid optimization method: %s\n" % method) return xs = alg.iterate(x0, mxitr, tol_g, tol_x, tol_f, f, msg, step_size) # Print point x found and function value f(x) # print("\nPoint x found: ", xs[-1]) print("\nf(x) = ", f.eval(xs[-1])) plt.plot(np.array(range(n)), xs[-1]) plt.plot(np.array(range(n)), f.y) plt.legend(['x*', 'y'], loc = 'best') plt.show()
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.function = Function() self.endDateEdt.setDate(QDate.currentDate()) self.initSlots() self.chargeTable.setHorizontalHeaderLabels( ['id', '成员', '类型', '金额(元)', '日期', '备注']) self.memberTable.setHorizontalHeaderLabels(['id', '姓名', '备注']) self.memberTable.setColumnHidden(0, True) self.chargeTable.setColumnHidden(0, True) self.updateMemberUI() self.updateTypeUI() self.updateChargeTable()
def main(): obj_func = Function('../target_code') best_styles = {} if os.path.exists('../.clang-format'): with open('../.clang-format') as f: best_styles = yaml.load(f) maps = style_maps() keys = [] for key, vals in maps.items(): keys.append(key) keys = sorted(keys) exclusion_keys = [key for key in best_styles.keys() if not (key in keys)] for key in exclusion_keys: best_styles.pop(key) best_styles = convert(best_styles) best_fval = obj_func.evaluate(best_styles) print('best styles: %s, best fval: %f\n' % (best_styles, best_fval)) influential_keys = [] uninfluential_keys = [] for key in keys: is_influential = False vals = maps[key] vals = [val for val in vals if val != best_styles[key]] for val in vals: styles = deepcopy(best_styles) styles[key] = val fval = obj_func.evaluate(styles) print('key: %s, val: %s, fval: %f' % (key, val, fval)) if fval != best_fval: is_influential = True print('%s is %s\n' % (key, 'influential' if is_influential else 'uninfluential')) if is_influential: influential_keys.append(key) else: uninfluential_keys.append(key) print('influential keys: %s\n' % influential_keys) print('uninfluential keys: %s\n' % uninfluential_keys)
def get_function(self) -> Function: """get_function Gets the function representation of the node :return: The function representation of the node :rtype: Function """ return Function(self.value)
def add_function(self, *args, **kwargs): """ Add a function to the module/namespace. See the documentation for :meth:`Function.__init__` for information on accepted parameters. """ if len(args) >= 1 and isinstance(args[0], Function): func = args[0] warnings.warn( "add_function has changed API; see the API documentation", DeprecationWarning, stacklevel=2) if len(args) == 2: func.custom_name = args[1] elif 'name' in kwargs: assert len(args) == 1 func.custom_name = kwargs['name'] else: assert len(args) == 1 assert len(kwargs) == 0 else: try: func = Function(*args, **kwargs) except utils.SkipWrapper: return None self._add_function_obj(func) return func
def __init__(self): '''Metodo de inicializacion''' self.functions = {} self.functions['global'] = Function() self.scope = 'global' # Define si se esta evaluando la existencia de variables o se estan agregando al directorio self.evaluating = True # Indica si es necesario acutlaizar la lista de prametros de una funcion self.updating_params = False # Indica si se va a leer variable con funcion read self.reading = False # Ultimo token ID, usado para el read self.last_id = Stack() # Ultimo token de tipo que fue leido por el directorio de funciones self.last_type = None '''Funciones que estan siendo llamadas. Se utiliza una pila para llamadas nesteadas a funciones''' self.call_function = Stack() '''Cantidad de argumentos que estan siendo utilizados al llamar a una funcion. Se utiliza una pilla para llamadas nesteadas''' self.call_arguments = Stack() self.last_read = Stack()
def addFunc(self, ast_node): func = Function(ast_node, self) if func.name in self.funcs: raise Exception('Function %s is already defined' % name) else: self.funcs[func.name] = func return func
def __init__(self, head: Node, sons=None, name: str = "regf") -> None: """__init__ Initialize the synthax tree :param head: The head of the tree :param sons: The sons of the root node :param name: The name of the tree :type head: a Node, a string representing a regex or a string \ for * (kleen),\ . (concatenation) or | (or) or anything else :type sons: A list of RegexTree :type name: str """ self.name = name if head.is_str() and head.get_str() == "": # If the head is the empty string, we stop self.head = Node(Function([])) if sons: self.sons = sons[:] else: self.sons = [] self.original_string = "" elif head.is_str() and head.get_str() not in ["|", "*", "."]: # We have a string representing a regex to parse new_head = head.get_str() self.init_from_string(new_head) self.original_string = new_head self.post_processing() else: self.head = head if sons: self.sons = sons[:] else: self.sons = [] self.original_string = ""
def __init__(self, pt_left_bot, pt_right_top, win): self.function = Function("0") self.p1 = pt_left_bot self.p2 = pt_right_top self.graph_area = Rectangle(self.p1, self.p2) self.win = win self.accuracy = 0.1 self.objects_drawn = []
def test_depth(self): f = Function.sum(Function.power(Function.identity(), Function.constant(2)), Function.identity()) # This requires splitting in half self.assertTrue(is_bounded(f, Interval(-1,0), Interval(-3/4,1/2), 1)) self.assertEqual(is_bounded(f, Interval(-1,0), Interval(-3/4,1/2), 0), None) # This requires 3 levels of recursion self.assertTrue(is_bounded(f, Interval(-1,0), Interval(-3/8,1/8), 3)) self.assertEqual(is_bounded(f, Interval(-1,0), Interval(-3/8,1/8), 2), None) # This requires 8 levels of recursion self.assertTrue(is_bounded(f, Interval(-1,0), Interval(-65/256,1/256), 8)) self.assertEqual(is_bounded(f, Interval(-1,0), Interval(-65/256,1/256), 7), None)
def main(): Maths.generateMathExpressions() print("Available operators:") for o in Maths.Expressions: print(Maths.Expressions[o].getAbbreviation()) print("-------------------------") f = Function("cos(3*x)+6/4*(x+3)", False) print("RPN String", f.getRpnString()) for x in range (2, 11): f.compute(x) print("-------------------------") f = Function("56*((6+2)/(8-x)*2^3", False) print("RPN String", f.getRpnString()) #should give 56 6 2 + 8 7 - / 2 3 ^ * * mainwindow = MainWindow("Function Drawer", 992, 512) fx = f.computeRange(0, 10) max_y = max(fx.values()) min_y = min(fx.values()) print(min_y, max_y) mainwindow.setCoords(-1, min_y, 11, max_y) for x in range(0, 11): print(fx[x]) p = Point(x, fx[x]) p.draw(mainwindow) input("Press a key to quit")
def test_approx(self): f = Function.identity() for a in approximate(f, 0, 1): self.assertTrue(isinstance(a, Function)) self.assertTrue(isinstance(a, CubicSpline)) # We may someday generate approximations that don't go through # the endpoints, and remove these tests. Until then, they # help verify that the approximation formulas are correct. self.assertEqual(a(0.0), 0.0) self.assertEqual(a(1.0), 1.0) # (-x^2 - 1) ^ .5 bad = Function.power(Function.sum(Function.product( Function.constant(-1), Function.power(Function.identity(), Function.constant(2))), Function.constant(-1)), Function.constant(.5)) self.assertEqual(list(approximate(bad, 0, 1)), [])
def create_full_tree(depth): """ Creates a tree using the full method with depth `depth`. Returns the root node. Args: depth: int Returns: Node instance """ if depth == 0: # Generate a leaf node terminal = Function.random_terminal() node = Node(terminal) return node else: # Generate an intermediate node func = Function.random_function() node = Node(func) for _ in range(func.arity): node.add_child(TreeMethods.create_full_tree(depth - 1)) return node
def __init__(self, t0, t1, f0, c0, c1, f1): self.__t0 = t0 self.__t1 = t1 self.__f0 = f0 self.__c0 = c0 self.__c1 = c1 self.__f1 = f1 # The specific functional form will have consequences for the # efficiency of interval arithmetic (and thus, slicing). # t' = (t-t0)/(t1-t0) t = Function.product(Function.sum(Function.identity(), Function.constant(-t0)), Function.constant(1.0/(t1-t0))) omt = Function.sum(Function.constant(1), Function.product(Function.constant(-1), t)) def term(const, f): return Function.sum(Function.constant(const), Function.product(t, f)) a = -f0 + 3*c0 - 3*c1 + f1 b = 3*f0 - 6*c0 + 3*c1 c = -3*f0 + 3*c0 d = f0 WrappedFunction.__init__(self, term(d, term(c, term(b, Function.constant(a)))).weak_simplify())
def test_simple(self): self.assertTrue(is_bounded(Function.identity(), Interval(0,1), Interval(0,1))) self.assertFalse(is_bounded(Function.identity(), Interval(0,2), Interval(0,1))) self.assertFalse(is_bounded(Function.identity(), Interval(-1,1), Interval(0,1))) self.assertFalse(is_bounded(Function.identity(), Interval(-1,2), Interval(0,1))) self.assertTrue(is_bounded(Function.constant(0.), Interval(3,4), Interval(0,1))) self.assertFalse(is_bounded(Function.constant(2.), Interval(3,4), Interval(0,1)))
def create_grow_tree(depth): """ Creates a tree using the grow method with depth `depth`. Note that since grow ends when all leaf nodes are 0-arity, it is possible that the tree generated by this method has a depth less than `depth`. Args: depth: int Returns: Node instance """ func = Function.random_function() root = Node(func) while True: if root.grow(depth) is None: break return root
def initialize_traj(self, mode): # see comment at top of ll_prob.py for mode options if self.trust_region_cnt is not None: self.model.remove(self.trust_region_cnt) self.clean(self.trust_temp) for constraint in self.constraints: constraint.clean() obj = grb.QuadExpr() for var in self.vars: if var.get_val() is not None and var.recently_sampled: obj += 1e5 * self.l2_norm_diff_squared(self.model, var) elif var.get_val() is not None and var.is_resampled: obj += 1 * self.l2_norm_diff_squared(self.model, var) if mode == "straight": obj += grb.quicksum(self.obj_quad) elif mode == "l2": for var in self.vars: if var.get_val() is not None: obj += self.l2_norm_diff_squared(self.model, var) elif mode == "minvel": for var in self.vars: if var.hl_param.is_traj: K = var.hl_param.num_dofs() T = var.hl_param.num_timesteps() KT = K * T v = -1 * np.ones((KT - K, 1)) d = np.vstack((np.ones((KT - K, 1)), np.zeros((K, 1)))) # [:,0] allows numpy to see v and d as one-dimensional so # that numpy will create a diagonal matrix with v and d as a diagonal P = np.diag(v[:, 0], K) + np.diag(d[:, 0]) # minimum-velocity finite difference Q = np.dot(np.transpose(P), P) obj += Function.quad_expr((var.get_grb_vars(self) - var.get_val()).flatten(order="f"), Q) else: raise NotImplementedError return self.optimize(objective=obj)
#!/usr/bin/env python # -*- coding:utf-8 -*- # print 'team:%s,name:%s'%(self.team, self.name) from function import Function import function if __name__=="__main__": print "please input the number that a,b,c,d for function" a,b,c,d = map(int, raw_input('input a,b,c,d=').split(",")) func=Function(a,b,c,d) func.showinfo() while True: print "input l,r | l<r & f(l)*f(r)<0" l,r = map(float,raw_input('input l,r=').split(",")) if (func.fnf(l)<func.fnf(r)) and (func.fnf(l)*func.fnf(r)<0): print "correct" break else: print "wrong numbers (l>r or f(l)*f(r)>=0)" th = float(raw_input('please input threshold:')) k=0
#!/usr/bin/env python # -*- coding:utf-8 -*- import math from function import Function import function if __name__ == '__main__': print "please input the number that a,b,c,d for function" a,b,c,d = map(int, raw_input('input a,b,c,d=').split(",")) func=Function(a,b,c,d) func.showinfo() while True: print "input x,r | x<r & f(x)*f(r)<0" x,r = map(float,raw_input('input x,r=').split(",")) if (func.fnf(x)<func.fnf(r)) and (func.fnf(x)*func.fnf(r)<0): print "correct" break else: print "wrong numbers (x>r or f(x)*f(r)>=0)" th = float(raw_input('please input threshold:')) k=0
def solve(n_cells, degree=3, with_plot=False): # Problem w = 3 * np.pi x = Symbol("x") u = sin(w * x) f = -u.diff(x, 2) # As Expr u = Expression(u) f = Expression(f) # Space # element = HermiteElement(degree) poly_set = leg.basis_functions(degree) dof_set = chebyshev_points(degree) element = LagrangeElement(poly_set, dof_set) mesh = IntervalMesh(a=-1, b=1, n_cells=n_cells) V = FunctionSpace(mesh, element) bc = DirichletBC(V, u) # Need mass matrix to intefrate the rhs M = assemble_matrix(V, "mass", get_geom_tensor=None, timer=0) # NOTE We cannot you apply the alpha transform idea because the functions # are mapped with this selective weight on 2nd, 3rd functions. So some rows # of alpha would have to be multiplied by weights which are cell specific. # And then on top of this there would be a dx = J*dy term. Better just to # use the qudrature representations # Mpoly_matrix = leg.mass_matrix(degree) # M_ = assemble_matrix(V, Mpoly_matrix, Mget_geom_tensor, timer=0) # Stiffness matrix for Laplacian A = assemble_matrix(V, "stiffness", get_geom_tensor=None, timer=0) # NOTE the above # Apoly_matrix = leg.stiffness_matrix(degree) # A_ = assemble_matrix(V, Apoly_matrix, Aget_geom_tensor, timer=0) # Interpolant of source fV = V.interpolate(f) # Integrate in L2 to get the vector b = M.dot(fV.vector) # Apply boundary conditions bc.apply(A, b, True) x = spsolve(A, b) # As function uh = Function(V, x) # This is a (slow) way of plotting the high order if with_plot: fig = plt.figure() ax = fig.gca() uV = V.interpolate(u) for cell in Cells(mesh): a, b = cell.vertices[0, 0], cell.vertices[1, 0] x = np.linspace(a, b, 100) y = uh.eval_cell(x, cell) ax.plot(x, y, color=random.choice(["b", "g", "m", "c"])) y = uV.eval_cell(x, cell) ax.plot(x, y, color="r") y = u.eval_cell(x, cell) ax.plot(x, y, color="k") plt.show() # Error norm in CG high order fine_degree = degree + 3 poly_set = leg.basis_functions(fine_degree) dof_set = chebyshev_points(fine_degree) element = LagrangeElement(poly_set, dof_set) V_fine = FunctionSpace(mesh, element) # Interpolate exact solution to fine u_fine = V_fine.interpolate(u) # Interpolate approx solution fine uh_fine = V_fine.interpolate(uh) # Difference vector e = u_fine.vector - uh_fine.vector # L2 if False: Apoly_matrix = leg.mass_matrix(fine_degree) get_geom_tensor = lambda cell: 1.0 / cell.Jac # Need matrix for integration of H10 norm else: Apoly_matrix = leg.stiffness_matrix(fine_degree) get_geom_tensor = lambda cell: cell.Jac A_fine = assemble_matrix(V_fine, Apoly_matrix, get_geom_tensor, timer=0) # Integrate the error e = sqrt(np.sum(e * A_fine.dot(e))) # Mesh size hmin = mesh.hmin() # Add the cond number kappa = np.linalg.cond(A.toarray()) return hmin, e, kappa, A.shape[0]
def get(self): func = _lib.myelin_vtable_get(self) return Function.from_pointer(func)
def prepare(code): lines = filter(lambda line: not re.match(r'^\s*//.*', line), code.split('\n')) lines = re.sub(r'\s+', ' ', ''.join(lines)).strip().split(';') lines = filter(lambda line: not re.match(r'^\s*$', line), lines) return [Function.parse(line) for line in lines]
def parseFunction(fp,dataset): """ FUNCTION IfcVectorSum (Arg1, Arg2 : IfcVectorOrDirection) : IfcVector; """ func=Function() #Function name name=geti(fp) #args begin token=geti(fp) if token!='(': log.error('Function has no args, line %d'%common.counter) return #args token=geti(fp) while True: args=[token] token=geti(fp) if token==',': while token!=':': token=geti(fp) args.append(token) token=geti(fp) if token==':': value='' token=geti(fp) while token!=';' and token!=')': value+=token+' ' token=geti(fp) for arg in args: func.arg[arg]=value.strip() if token==')': break #next element token=geti(fp) #: token=geti(fp) if token!=':': log.error('Function ret has no :, line %d'%common.counter) return #ret ret='' token=geti(fp) while token!=';': ret+=token+' ' token=geti(fp) func.ret=ret.strip() #local parseLocal(fp,func) #code parseCode(fp,func) # where clause func.where=parseWhere(fp) #parse END_TYPE token=geti(fp) if token!='END_FUNCTION': log.error('FUNCTION Defination has no END_FUNCTION, line %d'%common.counter) return token=geti(fp)#skip ; if token!=';': log.error('FUNCTION Defination does not end with ;, line %d'%common.counter) return dataset.functions[name]=func
# Can't cast a primitive. shouldUseConstructor = True elif args[0].func != ctor: # We haven't already called the constructor on this object. shouldUseConstructor = True # Apply our decision. if shouldUseConstructor: # Call ctor manually to avoid having promote() called on the output. ComputedObject.__init__(self, ctor, ctor.promoteArgs(ctor.nameArgs(args))) else: # Just cast and hope for the best. if not onlyOneArg: # We don't know what to do with multiple args. raise EEException("Too many arguments for ee.%s(): %s" % (name, args)) elif firstArgIsPrimitive: # Can't cast a primitive. raise EEException("Invalid argument for ee.%s(): %s. Must be a ComputedObject." % (name, args)) else: result = args[0] ComputedObject.__init__(self, result.func, result.args, result.varName) properties = {"__init__": init, "name": lambda self: name} new_class = type(str(name), (ComputedObject,), properties) ApiFunction.importApi(new_class, name, name) return new_class # Set up type promotion rules as soon the package is loaded. Function._registerPromoter(_Promote) # pylint: disable=protected-access
def test_split(self): # If this ever breaks, we should solve the problem by writing a # new kind of Function that turns a lambda expression into a # Function. That way, it will never be simplified. # f = x^2 + x f = Function.sum(Function.power(Function.identity(), Function.constant(2)), Function.identity()) # f(-1) = 0, f(0) = 0, f(-.5) = -.25 # The range of f on [-1,0] is [-.25,0] # f([-1,0]) = [-1,1] # f([-1,-.5]) = [-.75,.5] # f([-.5,0]) = [-.5,.25] # This will never finish, since it asks for the exact bounds self.assertTrue(is_bounded(f, Interval(-1,0), Interval(-1/4,0)) is None) # g = 1/2*x^3-3/2*x g = Function.sum(Function.product( Function.constant(.5), Function.power(Function.identity(), Function.constant(3))), Function.product(Function.constant(-1.5), Function.identity())) self.assertEqual(is_bounded(g, Interval(-1.5,1.5), Interval(-.9,1)), False) # This encounters a ValueError on the first split so should # return None h = Function.quotient(Function.constant(1), Function.identity()) self.assertTrue(is_bounded(h, Interval(-1,1), Interval(-5,5)) is None)
def term(const, f): return Function.sum(Function.constant(const), Function.product(t, f))
def solve(n_cells, degree=3, with_plot=False): # Problem x = Symbol('x') vvvv = -0.0625*x**3/pi**3 + 0.0625*x/pi**3 + sin(2*pi*x)/(16*pi**4) u = -vvvv.diff(x, 2) f = sin(2*pi*x) # As Expr u = Expression(u) f = Expression(f) vvvv = Expression(vvvv) # Space element = HermiteElement(degree) mesh = IntervalMesh(a=-1, b=1, n_cells=n_cells) V = FunctionSpace(mesh, element) bc = DirichletBC(V, vvvv) # Need mass matrix to intefrate the rhs M = assemble_matrix(V, 'mass', get_geom_tensor=None, timer=0) # NOTE We cannot you apply the alpha transform idea because the functions # are mapped with this selective weight on 2nd, 3rd functions. So some rows # of alpha would have to be multiplied by weights which are cell specific. # And then on top of this there would be a dx = J*dy term. Better just to # use the qudrature representations # Mpoly_matrix = leg.mass_matrix(degree) # M_ = assemble_matrix(V, Mpoly_matrix, Mget_geom_tensor, timer=0) # Stiffness matrix for Laplacian A = assemble_matrix(V, 'bending', get_geom_tensor=None, timer=0) # NOTE the above # Apoly_matrix = leg.stiffness_matrix(degree) # A_ = assemble_matrix(V, Apoly_matrix, Aget_geom_tensor, timer=0) # Interpolant of source fV = V.interpolate(f) # Integrate in L2 to get the vector b = M.dot(fV.vector) # Apply boundary conditions bc.apply(A, b, True) x = spsolve(A, b) print '>>>>', np.linalg.norm(x - V.interpolate(vvvv).vector) ALaplace = assemble_matrix(V, 'stiffness', get_geom_tensor=None, timer=0) c = ALaplace.dot(x) y = spsolve(M, c) uh = Function(V, y) # This is a (slow) way of plotting the high order if with_plot: fig = plt.figure() ax = fig.gca() uV = V.interpolate(u) for cell in Cells(mesh): a, b = cell.vertices[0, 0], cell.vertices[1, 0] x = np.linspace(a, b, 100) y = uh.eval_cell(x, cell) ax.plot(x, y, color=random.choice(['b', 'g', 'm', 'c'])) y = uV.eval_cell(x, cell) ax.plot(x, y, color='r') y = u.eval_cell(x, cell) ax.plot(x, y, color='k') plt.show() # Error norm fine_degree = degree + 3 element = HermiteElement(fine_degree) V_fine = FunctionSpace(mesh, element) # Interpolate exact solution to fine u_fine = V_fine.interpolate(u) # Interpolate approx solution fine uh_fine = V_fine.interpolate(uh) # Difference vector e = u_fine.vector - uh_fine.vector # Integrate the error A_fine = assemble_matrix(V_fine, 'mass', get_geom_tensor=None, timer=0) e = sqrt(np.sum(e*A_fine.dot(e))) # Mesh size hmin = mesh.hmin() # Add the cond number kappa = np.linalg.cond(A.toarray()) return hmin, e, kappa, A.shape[0]
class GraphWidget: def __init__(self, pt_left_bot, pt_right_top, win): self.function = Function("0") self.p1 = pt_left_bot self.p2 = pt_right_top self.graph_area = Rectangle(self.p1, self.p2) self.win = win self.accuracy = 0.1 self.objects_drawn = [] def getFunction(self): return self.func def setFunction(self, func): self.function = func def draw(self, xa, xb): self.cleanGraph() #Compute function and draw it x_min = min(xa, xb) x_max = max(xa, xb) #Compute all the values for f functon, accuracy give the step for computation fx = self.function.computeRange(x_min, x_max, self.accuracy) y_max = max(fx.values()) y_min = min(fx.values()) print(y_max, y_min) self.win.setCoords(x_min-(1/10)*x_max, y_min-(1/10)*y_max, x_max+(1/10)*x_max, y_max+(4/10)*y_max) x = x_min end = x_max prevfx = fx[x] k = 0 while x < (end+self.accuracy): #p = Point(x, fx) #p.draw(mainwindow) u = fx[x] if k > 0: self.drawLine(x-self.accuracy, prevfx, x, u) prevfx = u x += self.accuracy k += 1 self.drawAxis(x_min, x_max, y_min, y_max) def drawLine(self, x1, y1, x2, y2): l = Line(Point(x1, y1), Point(x2, y2)) self.objects_drawn.append(l) drawer = DrawerThread() l.setOutline("blue") drawer.run(l, self.win) return def drawAxis(self, x_min, x_max, y_min, y_max): #Draw axes #draw x axs first #we first consider we will draw it where y=0 x_axis = Line(Point(x_min, 0), Point(x_max, 0)) if y_max < 0: #if all the x values are under 0 #then we draw the on the top x_axis = Line(Point(x_min, y_max), Point(x_max, y_max)) elif y_min > 0: #if all the x values are over 0 #then we draw it at the bottom x_axis = Line(Point(x_min, y_min), Point(x_max, y_min)) drawer = DrawerThread() drawer.run(x_axis, self.win) self.objects_drawn.append(x_axis) #we consider we will draw where x=0 y_axis = Line(Point(0, y_min), Point(0, y_max)) if x_max < 0: #if all the y values are under 0 #then we draw the on right y_axis = Line(Point(x_max, y_min), Point(x_max, y_max)) elif x_min > 0: #if all the y values are over 0 #then we draw it at the bottom y_axis = Line(Point(x_min, y_min), Point(x_min, y_max)) drawer = DrawerThread() drawer.run(y_axis, self.win) self.objects_drawn.append(y_axis) #draw x labels y_ax = x_axis.getP1().getY() x_step = x_max*(0.1) x_size = y_max*.01 #from 0 to x_max x = 0 togo = x_max+0.1 while x < togo: sign = Line(Point(x, y_ax-x_size), Point(x, y_ax+x_size)) drawer = DrawerThread() drawer.run(sign, self.win) self.objects_drawn.append(sign) if x != 0: text = str(int(x)) if abs(x) < 1: text = ("{0:.1f}").format(x) label = Text(Point(x, y_ax-6*x_size), text) label.setSize(8) label.draw(self.win) self.objects_drawn.append(label) x += x_step #from 0 to x_min x = 0 togo = x_min-(0.1) while x > togo: sign = Line(Point(x, y_ax-x_size), Point(x, y_ax+x_size)) drawer = DrawerThread() drawer.run(sign, self.win) self.objects_drawn.append(sign) if x != 0: text = str(int(x)) if abs(x) < 1: text = ("{0:.1f}").format(x) label = Text(Point(x, y_ax-6*x_size), text) label.setSize(8) label.draw(self.win) self.objects_drawn.append(label) x -= x_step #draw y labels x_ax = y_axis.getP1().getX() y_step = y_max*(0.1) y_size = x_max*(0.01) #from 0 to y_max y = 0 togo = y_max+0.1 while y < togo: print(y) sign = Line(Point(x_ax-y_size, y), Point(x_ax+y_size, y)) drawer = DrawerThread() drawer.run(sign, self.win) self.objects_drawn.append(sign) if y != 0: text = str(int(y)) if abs(y) < 1: text = ("{0:.1f}").format(y) y = float(text) label = Text(Point(x_ax-6*y_size, y), text) label.setSize(8) label.draw(self.win) self.objects_drawn.append(label) y = y+y_step #from 0 to y_min y = 0 print(y_max, y) togo = y_min-0.1 while y > togo: sign = Line(Point(x_ax-y_size, y), Point(x_ax+y_size, y)) drawer = DrawerThread() drawer.run(sign, self.win) self.objects_drawn.append(sign) if y != 0: text = str(int(y)) if abs(y) < 1: text = ("{0:.1f}").format(y) y = float(text) label = Text(Point(x_ax-6*y_size, y), text) label.setSize(8) label.draw(self.win) self.objects_drawn.append(label) y = y-y_step def cleanGraph(self): undrawer = UndrawerThread() undrawer.run(self.objects_drawn) self.objects_drawn = [] def drawWuLine(self, x1, y1, x2, y2): xd = x2-x1 yd = y2-y1 if xd == 0 or yd == 0: print("Normal line") self.drawLine(x1, y1, x2, y2) else: if abs(xd) > abs(yd): #this is a vertical line #so we switch x and y if x1 < x2: #algorithm works only from min to max swap(x1, x2) swap(y1, y2) grad = yd/xd #first end point xend = round(x1) yend = y1+grad+(xend-x1) xgap = rfpart(x1+0.5) ix1 = round(xend) iy1 = int(yend) self.drawPixel(ix1, iy1, rfpart(yend)*xgap) self.drawPixel(ix1, iy1+1, fpart(yend)*xgap) yf = yend+grad #second end point xend = round(x2) yend = y2+grad*(xend-x2) xgap = fpart(x2+0.5) ix2 = round(xend) iy2 = int(yend) self.drawPixel(ix2, iy2, rfpart(yend)*xgap) self.drawPixel(ix2, iy2+1, fpart(yend)*xgap) #main loop x = ix1+1 while x<(ix2-1): self.drawPixel(x, int(yf), rfpart(yf)) self.drawPixel(x, int(yf)+1, fpart(yf)) yf += grad x += 1 elif abs(xd) < abs(yd): #this is a vertical line #so we switch x and y if y1 < y2: #algorithm works only from min to max swap(x1, x2) swap(y1, y2) grad = xd/yd #first end point yend = round(y1) xend = x1+grad+(yend-y1) ygap = rfpart(y1+0.5) iy1 = round(yend) ix1 = int(xend) self.drawPixel(ix1, iy1, rfpart(yend)*ygap) self.drawPixel(ix1, iy1+1, fpart(yend)*ygap) xf = xend+grad #second end point yend = round(y2) xend = x2+grad*(yend-y2) ygap = fpart(y2+0.5) iy2 = round(yend) ix2 = int(xend) self.drawPixel(ix2, iy2, rfpart(xend)*ygap) self.drawPixel(ix2, iy2+1, fpart(xend)*ygap) #main loop y = iy1+1 while y<(iy2-1): self.drawPixel(int(xf), y, rfpart(xf)) self.drawPixel(int(xf)+1, y, fpart(xf)) xf += grad y += 1 def drawPixel(self, x, y, c): p = Point(x, y) #we convert the transparence c(0 to 1) to a rgb value(0 to 255) c = math.floor(255*(1-c)) p.draw(self.win)
def test_linear(self): a = linear_approximation(Function.identity(), 0, 1) self.assertEqual(a(3), 3) self.assertEqual(a(44), 44)
def __init__(self,x,y,*args,**kwargs): Function.__init__(self,"B-spline",x,y,*args,**kwargs)
break spl = l.split(',') try: if spl[0].strip() != "nan" and spl[1].strip() != "nan": wh = float(spl[0].strip()) v = float(spl[1].strip()) min_v = min(min_v, v) max_v = max(max_v, v) min_wh = min(min_wh, wh) max_wh = max(max_wh, wh) data.append((v,wh)) except Exception, e: print "An exception occurred: " + str(e) print "It's probably ok" f = Function(data=data) for i in xrange(len(data)): v = data[i][0] wh = data[i][1] data[i] = (v, (wh - min_wh) / (max_wh - min_wh)) SPACING = (max_v - min_v) / 100 fout.write('[\n') v = min_v while v <= max_v: interpolated_wh = f.interpolate(v) fout.write("{%d,%d},\n" % (int(v*1000000), int(interpolated_wh*1000000))) v += SPACING
t = float(spl[3].strip()) if t == cur_time and cur_voltage_drain > 0 and cur_voltage_actual > 0: data.append((cur_voltage_drain, cur_voltage_actual)) cur_time = t except Exception, e: print "An exception occurred: " + str(e) print "It's probably ok" fin.close() fout.close() exit(0) f = Function(data=data) fo = open("function.csv", 'w') for d in data: fo.write("%f,%f\n" % (d[0],d[1])) fo.close() exit(0) # now read in 1A.csv to get voltage_actual against wh # in = time, voltage_drain, current last_time = 0 total_wh = 0