Пример #1
0
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
Пример #2
0
    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))
Пример #3
0
    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)
Пример #4
0
def test_function():
    exponential_func = Function(exp)
    sin_func = Function(sin)
    # print(exponential_func.execute(sin_func.execute(0)))

    assert sin_func.execute(0, False) == 0
    assert exponential_func.execute(sin_func.execute(0, False), False) == 1

    print('Function tested SUCCESSFULLY')
Пример #5
0
    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
Пример #6
0
 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()
Пример #7
0
 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([]))
Пример #8
0
    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 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
Пример #10
0
 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
Пример #11
0
    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()
Пример #12
0
def run_remove_category_test():
    expenses = []
    function = Function(expenses)

    function.insert(["25", "2", constants.CATEGORY_OTHERS])
    assert len(expenses) == 1

    try:
        function.remove_category([""])
        assert False
    except ValidationError:
        assert True
    assert len(expenses) == 1

    try:
        function.remove_category(["abc"])
        assert False
    except ValidationError:
        assert True
    assert len(expenses) == 1

    function.remove_category([constants.CATEGORY_TRANSPORT])
    assert len(expenses) == 1

    function.remove_category([constants.CATEGORY_OTHERS])
    assert len(expenses) == 0
Пример #13
0
 def __init__(self):
     """ define supported functions and operators and link them to numpy functions """
     self.functions = {
         'EXP': Function(numpy.exp),
         'LOG': Function(numpy.log),
         'SIN': Function(numpy.sin),
         'COS': Function(numpy.cos),
         'SQRT': Function(numpy.sqrt)
     }
     self.operators = {
         'PLUSS': Operator(numpy.add, 0),
         'GANGE': Operator(numpy.multiply, 1),
         'DELE': Operator(numpy.divide, 1),
         'MINUS': Operator(numpy.subtract, 0)
     }
     self.output_queue = Queue()
Пример #14
0
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)
Пример #15
0
def run_list_category_test():
    expenses = []
    function = Function(expenses)

    try:
        function.list_category([""])
        assert False
    except ValidationError:
        assert True

    try:
        function.list_category(["abc"])
        assert False
    except ValidationError:
        assert True

    try:
        function.list_category([constants.CATEGORY_TRANSPORT])
        assert False
    except ValidationError:
        assert True

    function.insert(["24", "1", constants.CATEGORY_CLOATHING])
    assert len(expenses) == 1

    assert function.list_category([constants.CATEGORY_CLOATHING])
Пример #16
0
 def MAKE_FUNCTION(self, argc):
     name = self.pop()
     code = self.pop()
     defaults = self.popn(argc)
     globs = self.frame.f_globals
     fn = Function(name, code, globs, defaults, None, self)
     self.push(fn)
Пример #17
0
    def create_function(self, bea, haddr):
        """
            Create function descriptor from VM IP and address of handler
            :param bea: Begin IP of function in VM disassembler trace
            :param haddr: Address of handler in binary

            :return Success status
        """
        print "[+] Analyzing function by address %s" % hex(bea)
        dg = None
        try:
            dg = DiGraph(bea, self.instruction_size)
            dg.parse(self.instructions)
        except Exception:
            print "[~] Unhandled exception in create graph routine"
            return False

        if dg.is_bad_cfg:
            print "[!] Function at address: %s invalid" % hex(bea).replace("0x", "").replace("L", "")
            return False

        f = Function(bea, dg.get_low_address(), dg, "sub_%s" % hex(bea).replace("0x", "").replace("L", ""), haddr)
        self.functions[bea] = f

        return True
    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))
Пример #19
0
def run_sum_category_test():
    expenses = []
    function = Function(expenses)

    try:
        function.sum_category([""])
        assert False
    except ValidationError:
        assert True

    try:
        function.sum_category(["abc"])
        assert False
    except ValidationError:
        assert True

    assert "0" in function.sum_category([constants.CATEGORY_CLOATHING])

    function.insert(["22", "4", constants.CATEGORY_FOOD])
    assert len(expenses) == 1
    assert "4" in function.sum_category([constants.CATEGORY_FOOD])

    function.insert(["21", "8", constants.CATEGORY_HOUSEKEEPING])
    assert len(expenses) == 2
    assert "4" in function.sum_category([constants.CATEGORY_FOOD])

    function.insert(["20", "16", constants.CATEGORY_FOOD])
    assert len(expenses) == 3
    assert "20" in function.sum_category([constants.CATEGORY_FOOD])
Пример #20
0
 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)
Пример #21
0
def run_filter_category_test():
    expenses = []
    function = Function(expenses)

    try:
        function.filter_category([""])
        assert False
    except ValidationError:
        assert True

    try:
        function.filter_category(["abc"])
        assert False
    except ValidationError:
        assert True

    function.filter_category([constants.CATEGORY_TRANSPORT])

    function.insert(["11", "32", constants.CATEGORY_CLOATHING])
    assert len(expenses) == 1

    function.insert(["10", "16", constants.CATEGORY_FOOD])
    assert len(expenses) == 2

    function.insert(["9", "8", constants.CATEGORY_CLOATHING])
    assert len(expenses) == 3

    function.filter_category([constants.CATEGORY_CLOATHING])
    assert len(expenses) == 2
Пример #22
0
 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
Пример #23
0
 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 = ""
Пример #24
0
    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
Пример #25
0
 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
Пример #26
0
def un_follow(event):
    try:
        user_id = event.source.user_id
        Function().delete_user(user_id)
        logger.log(20, LOG_DATA["UN_FOLLOW"] + date_data)

    except:
        logger.log(40, LOG_DATA["ERROR_UN_FOLLOW"] + date_data)
Пример #27
0
def leave_group(event):
    try:
        group_id = event.source.group_id
        Function().delete_group(group_id)
        logger.log(20, LOG_DATA["LEAVE_GROUP"] + date_data)

    except:
        logger.log(40, LOG_DATA["ERROR_LEAVE"] + date_data)
Пример #28
0
    def __execute_method(self,
                         f,
                         y_solution_func,
                         x_0,
                         y_0,
                         x_n,
                         n,
                         precision=4) -> Tuple[Function]:
        '''
        Basically execute iteration method
        '''
        h = (x_n - x_0) / n
        assert (h > 0, 'x_n should be greater than x_0')

        logging.debug(
            f"Solving eq with steps {h}. y_0: {y_0} x_n: {x_n}, x_0: {x_0}, n: {n}"
        )
        result_function = Function([], [])
        lte_function = Function([], [])
        gte_function = Function([], [])
        x_i = x_0
        y_i = y_0
        LTE = 0
        GTE = 0
        for i in range(1, n + 2):
            # add values to result functions

            result_function.append(x_i, y_i)
            lte_function.append(x_i, LTE)
            gte_function.append(x_i, GTE)

            # execute method
            y_i = self.get_next_value(f, x_i, y_i, h)

            # errors
            LTE = abs(y_solution_func(x_i + h) - \
                self.get_next_value(
                    f, x_i, y_solution_func(x_i), h
                    )
                )
            GTE = abs(y_solution_func(x_i + h) - y_i)
            # step
            x_i = round(x_0 + i * h, precision)
            y_init = y_solution_func(x_i)

        return (result_function, lte_function, gte_function)
Пример #29
0
 def add_function(self, function_id):
     '''Add function to fuctions directory. Verify if function already exists'''
     if self.functions.get(function_id, None) is not None:
         raise NameError(
             'Error: 1001 Function already declared! Function: ' +
             str(function_id))
     else:
         self.functions[function_id] = Function()
Пример #30
0
 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)