Search is not available for this dataset
text
stringlengths
75
104k
def stop(self): """Stops the motor and returns the new target and position, which are equal""" self._target = self.position self.log.info('Stopping movement after user request.') return self.target, self.position
def set_target(self, new_target): """ Sets the new target in mm, the movement starts immediately. If the value is outside the interval [0, 250] or the motor is already moving, an error is returned, otherwise the new target is returned.""" try: self.device.target = new...
def run_simulation(argument_list=None): # noqa: C901 """ This is effectively the main function of a typical simulation run. Arguments passed in are parsed and used to construct and run the simulation. This function only exits when the program has completed or is interrupted. :param argument_list:...
def map_arguments(self, arguments): """ Returns the mapped function arguments. If no mapping functions are defined, the arguments are returned as they were supplied. :param arguments: List of arguments for bound function as strings. :return: Mapped arguments. """ ...
def map_return_value(self, return_value): """ Returns the mapped return_value of a processed request. If no return_mapping has been defined, the value is returned as is. If return_mapping is a static value, that value is returned, ignoring return_value completely. :param return_...
def start_server(self): """ Starts the TCP stream server, binding to the configured host and port. Host and port are configured via the command line arguments. .. note:: The server does not process requests unless :meth:`handle` is called in regular intervals. ...
def handle(self, cycle_delay=0.1): """ Spend approximately ``cycle_delay`` seconds to process requests to the server. :param cycle_delay: S """ asyncore.loop(cycle_delay, count=1) self._server.process(int(cycle_delay * 1000))
def _bind_device(self): """ This method implements ``_bind_device`` from :class:`~lewis.core.devices.InterfaceBase`. It binds Cmd and Var definitions to implementations in Interface and Device. """ patterns = set() self.bound_commands = [] for cmd in self.comman...
def _override_data(self, overrides): """ This method overrides data members of the class, but does not allow for adding new members. :param overrides: Dict with data overrides. """ if overrides is not None: for name, val in overrides.items(): self.log...
def get(self, addr, count): """ Read list of ``count`` values at ``addr`` memory location in DataBank. :param addr: Address to read from :param count: Number of entries to retrieve :return: list of entry values :except IndexError: Raised if address range falls outside va...
def set(self, addr, values): """ Write list ``values`` to ``addr`` memory location in DataBank. :param addr: Address to write to :param values: list of values to write :except IndexError: Raised if address range falls outside valid range """ addr -= self._start_a...
def from_bytearray(self, stream): """ Constructs this frame from input data stream, consuming as many bytes as necessary from the beginning of the stream. If stream does not contain enough data to construct a complete modbus frame, an EOFError is raised and no data is consumed. ...
def to_bytearray(self): """ Convert this frame into its bytearray representation. :return: bytearray representation of this frame. """ header = bytearray(struct.pack( '>HHHBB', self.transaction_id, self.protocol_id, self.length, ...
def is_valid(self): """ Check integrity and validity of this frame. :return: bool True if this frame is structurally valid. """ conditions = [ self.protocol_id == 0, # Modbus always uses protocol 0 2 <= self.length <= 260, # Absolute length limits ...
def create_exception(self, code): """ Create an exception frame based on this frame. :param code: Modbus exception code to use for this exception :return: ModbusTCPFrame instance that represents an exception """ frame = deepcopy(self) frame.length = 3 fra...
def create_response(self, data=None): """ Create a response frame based on this frame. :param data: Data section of response as bytearray. If None, request data section is kept. :return: ModbusTCPFrame instance that represents a response """ frame = deepcopy(self) ...
def _all_expander(fringe, iteration, viewer): ''' Expander that expands all nodes on the fringe. ''' expanded_neighbors = [node.expand(local_search=True) for node in fringe] if viewer: viewer.event('expanded', list(fringe), expanded_neighbors) list(map(fringe....
def beam(problem, beam_size=100, iterations_limit=0, viewer=None): ''' Beam search. beam_size is the size of the beam. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than the current one. Req...
def _first_expander(fringe, iteration, viewer): ''' Expander that expands only the first node on the fringe. ''' current = fringe[0] neighbors = current.expand(local_search=True) if viewer: viewer.event('expanded', [current], [neighbors]) fringe.extend(neighbors)
def beam_best_first(problem, beam_size=100, iterations_limit=0, viewer=None): ''' Beam search best first. beam_size is the size of the beam. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than th...
def hill_climbing(problem, iterations_limit=0, viewer=None): ''' Hill climbing search. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than the current one. Requires: SearchProblem.actions, Search...
def _random_best_expander(fringe, iteration, viewer): ''' Expander that expands one randomly chosen nodes on the fringe that is better than the current (first) node. ''' current = fringe[0] neighbors = current.expand(local_search=True) if viewer: viewer.event('expanded', [current], [...
def hill_climbing_stochastic(problem, iterations_limit=0, viewer=None): ''' Stochastic hill climbing. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than the current one. Requires: SearchProblem....
def hill_climbing_random_restarts(problem, restarts_limit, iterations_limit=0, viewer=None): ''' Hill climbing with random restarts. restarts_limit specifies the number of times hill_climbing will be runned. If iterations_limit is specified, each hill_climbing will end after that number of iteratio...
def _exp_schedule(iteration, k=20, lam=0.005, limit=100): ''' Possible scheduler for simulated_annealing, based on the aima example. ''' return k * math.exp(-lam * iteration)
def _create_simulated_annealing_expander(schedule): ''' Creates an expander that has a random chance to choose a node that is worse than the current (first) node, but that chance decreases with time. ''' def _expander(fringe, iteration, viewer): T = schedule(iteration) current = frin...
def simulated_annealing(problem, schedule=_exp_schedule, iterations_limit=0, viewer=None): ''' Simulated annealing. schedule is the scheduling function that decides the chance to choose worst nodes depending on the time. If iterations_limit is specified, the algorithm will end after that number...
def _create_genetic_expander(problem, mutation_chance): ''' Creates an expander that expands the bests nodes of the population, crossing over them. ''' def _expander(fringe, iteration, viewer): fitness = [x.value for x in fringe] sampler = InverseTransformSampler(fitness, fringe) ...
def genetic(problem, population_size=100, mutation_chance=0.1, iterations_limit=0, viewer=None): ''' Genetic search. population_size specifies the size of the population (ORLY). mutation_chance specifies the probability of a mutation on a child, varying from 0 to 1. If iterations_li...
def _local_search(problem, fringe_expander, iterations_limit=0, fringe_size=1, random_initial_states=False, stop_when_no_better=True, viewer=None): ''' Basic algorithm for all local search algorithms. ''' if viewer: viewer.event('started') fringe = Bounde...
def find_location(rows, element_to_find): '''Find the location of a piece in the puzzle. Returns a tuple: row, column''' for ir, row in enumerate(rows): for ic, element in enumerate(row): if element == element_to_find: return ir, ic
def actions(self, state): '''Returns a list of the pieces we can move to the empty space.''' rows = string_to_list(state) row_e, col_e = find_location(rows, 'e') actions = [] if row_e > 0: actions.append(rows[row_e - 1][col_e]) if row_e < 2: actio...
def result(self, state, action): '''Return the resulting state after moving a piece to the empty space. (the "action" parameter contains the piece to move) ''' rows = string_to_list(state) row_e, col_e = find_location(rows, 'e') row_n, col_n = find_location(rows, actio...
def heuristic(self, state): '''Returns an *estimation* of the distance from a state to the goal. We are using the manhattan distance. ''' rows = string_to_list(state) distance = 0 for number in '12345678e': row_n, col_n = find_location(rows, number) ...
def is_attribute(method, name=None): """ Decorator for methods that are attributes. """ if name is None: name = method.__name__ method.is_attribute = True method.name = name return method
def load(cls, filepath): """ Loads a pickled version of the classifier saved in `filepath` """ with open(filepath, "rb") as filehandler: classifier = pickle.load(filehandler) if not isinstance(classifier, Classifier): raise ValueError("Pickled object is n...
def tree_to_str(root): """ Returns a string representation of a decision tree with root node `root`. """ xs = [] for value, node, depth in iter_tree(root): template = "{indent}" if node is not root: template += "case={value}\t" if node.attribute is None: ...
def learn(self, examples, attributes, parent_examples): """ A decision tree learner that *strictly* follows the pseudocode given in AIMA. In 3rd edition, see Figure 18.5, page 702. """ if not examples: return self.plurality_value(parent_examples) elif len(set(...
def importance(self, attribute, examples): """ AIMA implies that importance should be information gain. Since AIMA only defines it for binary features this implementation was based on the wikipedia article: http://en.wikipedia.org/wiki/Information_gain_in_decision_trees "...
def save(self, filepath): """ Saves the classifier to `filepath`. Because this classifier needs to save the dataset, it must be something that can be pickled and not something like an iterator. """ if not filepath or not isinstance(filepath, str): rai...
def take_branch(self, example): """ Returns a `DecisionTreeNode` instance that can better classify `example` based on the selectors value. If there are no more branches (ie, this node is a leaf) or the attribute gives a value for an unexistent branch then this method retu...
def _max_gain_split(self, examples): """ Returns an OnlineInformationGain of the attribute with max gain based on `examples`. """ gains = self._new_set_of_gain_counters() for example in examples: for gain in gains: gain.add(example) win...
def backtrack(problem, variable_heuristic='', value_heuristic='', inference=True): ''' Backtracking search. variable_heuristic is the heuristic for variable choosing, can be MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE, or blank for simple ordered choosing. value_heuristic is the heuristi...
def _most_constrained_variable_chooser(problem, variables, domains): ''' Choose the variable that has less available values. ''' # the variable with fewer values available return sorted(variables, key=lambda v: len(domains[v]))[0]
def _highest_degree_variable_chooser(problem, variables, domains): ''' Choose the variable that is involved on more constraints. ''' # the variable involved in more constraints return sorted(variables, key=lambda v: problem.var_degrees[v], reverse=True)[0]
def _count_conflicts(problem, assignment, variable=None, value=None): ''' Count the number of violated constraints on a given assignment. ''' return len(_find_conflicts(problem, assignment, variable, value))
def _find_conflicts(problem, assignment, variable=None, value=None): ''' Find violated constraints on a given assignment, with the possibility of specifying a new variable and value to add to the assignment before checking. ''' if variable is not None and value is not None: assignment = ...
def _least_constraining_values_sorter(problem, assignment, variable, domains): ''' Sort values based on how many conflicts they generate if assigned. ''' # the value that generates less conflicts def update_assignment(value): new_assignment = deepcopy(assignment) new_assignment[varia...
def _backtracking(problem, assignment, domains, variable_chooser, values_sorter, inference=True): ''' Internal recursive backtracking algorithm. ''' from simpleai.search.arc import arc_consistency_3 if len(assignment) == len(problem.variables): return assignment pending = [v for v in pr...
def _min_conflicts_value(problem, assignment, variable): ''' Return the value generate the less number of conflicts. In case of tie, a random value is selected among this values subset. ''' return argmin(problem.domains[variable], lambda x: _count_conflicts(problem, assignment, variable, x))
def min_conflicts(problem, initial_assignment=None, iterations_limit=0): """ Min conflicts search. initial_assignment the initial assignment, or None to generate a random one. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until ...
def convert_to_binary(variables, domains, constraints): """ Returns new constraint list, all binary, using hidden variables. You can use it as previous step when creating a problem. """ def wdiff(vars_): def diff(variables, values): hidden, other = variables if hidd...
def boltzmann_exploration(actions, utilities, temperature, action_counter): '''returns an action with a probability depending on utilities and temperature''' utilities = [utilities[x] for x in actions] temperature = max(temperature, 0.01) _max = max(utilities) _min = min(utilities) if _max == _m...
def make_exponential_temperature(initial_temperature, alpha): '''returns a function like initial / exp(n * alpha)''' def _function(n): try: return initial_temperature / math.exp(n * alpha) except OverflowError: return 0.01 return _function
def mkconstraints(): """ Make constraint list for binary constraint problem. """ constraints = [] for j in range(1, 10): vars = ["%s%d" % (i, j) for i in uppercase[:9]] constraints.extend((c, const_different) for c in combinations(vars, 2)) for i in uppercase[:9]: vars ...
def precision(classifier, testset): """ Runs the classifier for each example in `testset` and verifies that the classification is correct using the `target`. Returns a number between 0.0 and 1.0 with the precision of classification for this test set. """ hit = 0 total = 0 for e...
def kfold(dataset, problem, method, k=10): """ Does a k-fold on `dataset` with `method`. This is, it randomly creates k-partitions of the dataset, and k-times trains the method with k-1 parts and runs it with the partition left. After all this, returns the overall success ratio. """ if k <=...
def actions(self, state): 'actions are index where we can make a move' actions = [] for index, char in enumerate(state): if char == '_': actions.append(index) return actions
def actions(self, s): '''Possible actions from a state.''' # we try to generate every possible state and then filter those # states that are valid return [a for a in self._actions if self._is_valid(self.result(s, a))]
def _is_valid(self, s): '''Check if a state is valid.''' # valid states: no more cannibals than missioners on each side, # and numbers between 0 and 3 return ((s[0] >= s[1] or s[0] == 0)) and \ ((3 - s[0]) >= (3 - s[1]) or s[0] == 3) and \ (0 <= s[0] <= 3)...
def result(self, s, a): '''Result of applying an action to a state.''' # result: boat on opposite side, and numbers of missioners and # cannibals updated according to the move if s[2] == 0: return (s[0] - a[1][0], s[1] - a[1][1], 1) else: return (s[0] + a[...
def revise(domains, arc, constraints): """ Given the arc X, Y (variables), removes the values from X's domain that do not meet the constraint between X and Y. That is, given x1 in X's domain, x1 will be removed from the domain, if there is no value y in Y's domain that makes constraint(X,Y) True, f...
def all_arcs(constraints): """ For each constraint ((X, Y), const) adds: ((X, Y), const) ((Y, X), const) """ arcs = set() for neighbors, constraint in constraints: if len(neighbors) == 2: x, y = neighbors list(map(arcs.add, ((x, y), (y, x)))) ret...
def arc_consistency_3(domains, constraints): """ Makes a CSP problem arc consistent. Ignores any constraint that is not binary. """ arcs = list(all_arcs(constraints)) pending_arcs = set(arcs) while pending_arcs: x, y = pending_arcs.pop() if revise(domains, (x, y), constrain...
def expand(self, local_search=False): '''Create successors.''' new_nodes = [] for action in self.problem.actions(self.state): new_state = self.problem.result(self.state, action) cost = self.problem.cost(self.state, action, ...
def path(self): '''Path (list of nodes and actions) from root to this node.''' node = self path = [] while node: path.append((node.action, node.state)) node = node.parent return list(reversed(path))
def step(self, viewer=None): "This method evolves one step in time" if not self.is_completed(self.state): for agent in self.agents: action = agent.program(self.percept(agent, self.state)) next_state = self.do_action(self.state, action, agent) i...
def breadth_first(problem, graph_search=False, viewer=None): ''' Breadth first search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, and SearchProblem.is_goal. ''' return _search(problem, FifoList(), ...
def depth_first(problem, graph_search=False, viewer=None): ''' Depth first search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, and SearchProblem.is_goal. ''' return _search(problem, LifoList(), ...
def limited_depth_first(problem, depth_limit, graph_search=False, viewer=None): ''' Limited depth first search. Depth_limit is the maximum depth allowed, being depth 0 the initial state. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.resul...
def iterative_limited_depth_first(problem, graph_search=False, viewer=None): ''' Iterative limited depth first search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, and SearchProblem.is_goal. ''' solution = None limit ...
def uniform_cost(problem, graph_search=False, viewer=None): ''' Uniform cost search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.is_goal, and SearchProblem.cost. ''' return _search(problem, ...
def greedy(problem, graph_search=False, viewer=None): ''' Greedy search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic. ''' return _search(problem, ...
def astar(problem, graph_search=False, viewer=None): ''' A* search. If graph_search=True, will avoid exploring repeated states. Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic. ''' return _search(problem, ...
def _search(problem, fringe, graph_search=False, depth_limit=None, node_factory=SearchNode, graph_replace_when_better=False, viewer=None): ''' Basic search algorithm, base of all the other search algorithms. ''' if viewer: viewer.event('started') memory = set() i...
def _get_tree_paths(tree, node_id, depth=0): """ Returns all paths through the tree as list of node_ids """ if node_id == _tree.TREE_LEAF: raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF) left_child = tree.children_left[node_id] right_child = tree.children_right[node_id] if...
def _predict_tree(model, X, joint_contribution=False): """ For a given DecisionTreeRegressor, DecisionTreeClassifier, ExtraTreeRegressor, or ExtraTreeClassifier, returns a triple of [prediction, bias and feature_contributions], such that prediction ≈ bias + feature_contributions. """ leaves ...
def _predict_forest(model, X, joint_contribution=False): """ For a given RandomForestRegressor, RandomForestClassifier, ExtraTreesRegressor, or ExtraTreesClassifier returns a triple of [prediction, bias and feature_contributions], such that prediction ≈ bias + feature_contributions. """ bias...
def predict(model, X, joint_contribution=False): """ Returns a triple (prediction, bias, feature_contributions), such that prediction ≈ bias + feature_contributions. Parameters ---------- model : DecisionTreeRegressor, DecisionTreeClassifier, ExtraTreeRegressor, ExtraTreeClassifier, ...
def extract_keywords_from_text(self, text): """Method to extract keywords from the text provided. :param text: Text to extract keywords from, provided as a string. """ sentences = nltk.tokenize.sent_tokenize(text) self.extract_keywords_from_sentences(sentences)
def extract_keywords_from_sentences(self, sentences): """Method to extract keywords from the list of sentences provided. :param sentences: Text to extraxt keywords from, provided as a list of strings, where each string is a sentence. """ phrase_list = self._gen...
def _build_word_co_occurance_graph(self, phrase_list): """Builds the co-occurance graph of words in the given body of text to compute degree of each word. :param phrase_list: List of List of strings where each sublist is a collection of words which form a contender p...
def _build_ranklist(self, phrase_list): """Method to rank each contender phrase using the formula phrase_score = sum of scores of words in the phrase. word_score = d(w)/f(w) where d is degree and f is frequency. :param phrase_list: List of List of strings where each sublist...
def _generate_phrases(self, sentences): """Method to generate contender phrases given the sentences of the text document. :param sentences: List of strings where each string represents a sentence which forms the text. :return: Set of string tuples where each tu...
def _get_phrase_list_from_words(self, word_list): """Method to create contender phrases from the list of words that form a sentence by dropping stopwords and punctuations and grouping the left words into phrases. Only phrases in the given length range (both limits inclusive) would be con...
def _retain_centroids(numbers, thres): """Only keep one number for each cluster within thres of each other""" numbers.sort() prev = -1 ret = [] for n in numbers: if prev < 0 or n - prev > thres: ret.append(n) prev = n return ret
def _split_vlines_hlines(lines): """Separates lines into horizontal and vertical ones""" vlines, hlines = [], [] for line in lines: (vlines if line.x1 - line.x0 < 0.1 else hlines).append(line) return vlines, hlines
def _npiter(arr): """Wrapper for iterating numpy array""" for a in np.nditer(arr, flags=["refs_ok"]): c = a.item() if c is not None: yield c
def get_normalized_grid(self): """ Analyzes subcell structure """ log = logging.getLogger(__name__) # Resolve multirow mentions, TODO: validate against all PDFs # subcol_count = 0 mega_rows = [] for row_id, row in enumerate(self._grid): # maps...
def _mark_grid_bounds(self, plane, region_bbox): """ Assume all lines define a complete grid over the region_bbox. Detect which lines are missing so that we can recover merged cells. """ # Grid boundaries vbars = np.zeros([self.num_rows, self.num_cols + 1], dtype=...
def vectorize(e, tolerance=0.1): """ vectorizes the pdf object's bounding box min_width is the width under which we consider it a line instead of a big rectangle """ tolerance = max(tolerance, e.linewidth) is_high = e.height > tolerance is_wide = e.width > tolerance # if skewed towar...
def aligned(e1, e2): """ alignment is determined by two boxes having one exactly the same attribute, which could mean parallel, perpendicularly forming a corner etc. """ return ( any(close(c1, c2) for c1, c2 in zip(e1.bbox, e2.bbox)) or x_center_aligned(e1, e2) or y_cente...
def bound_bboxes(bboxes): """ Finds the minimal bbox that contains all given bboxes """ group_x0 = min(map(lambda l: l[x0], bboxes)) group_y0 = min(map(lambda l: l[y0], bboxes)) group_x1 = max(map(lambda l: l[x1], bboxes)) group_y1 = max(map(lambda l: l[y1], bboxes)) return (group_x0, gr...
def bound_elems(elems): """ Finds the minimal bbox that contains all given elems """ group_x0 = min(map(lambda l: l.x0, elems)) group_y0 = min(map(lambda l: l.y0, elems)) group_x1 = max(map(lambda l: l.x1, elems)) group_y1 = max(map(lambda l: l.y1, elems)) return (group_x0, group_y0, gro...
def intersect(a, b): """ Check if two rectangles intersect """ if a[x0] == a[x1] or a[y0] == a[y1]: return False if b[x0] == b[x1] or b[y0] == b[y1]: return False return a[x0] <= b[x1] and b[x0] <= a[x1] and a[y0] <= b[y1] and b[y0] <= a[y1]
def reading_order(e1, e2): """ A comparator to sort bboxes from top to bottom, left to right """ b1 = e1.bbox b2 = e2.bbox if round(b1[y0]) == round(b2[y0]) or round(b1[y1]) == round(b2[y1]): return float_cmp(b1[x0], b2[x0]) return float_cmp(b1[y0], b2[y0])
def xy_reading_order(e1, e2): """ A comparator to sort bboxes from left to right, top to bottom """ b1 = e1.bbox b2 = e2.bbox if round(b1[x0]) == round(b2[x0]): return float_cmp(b1[y0], b2[y0]) return float_cmp(b1[x0], b2[x0])
def column_order(b1, b2): """ A comparator that sorts bboxes first by "columns", where a column is made up of all bboxes that overlap, then by vertical position in each column. b1 = [b1.type, b1.top, b1.left, b1.bottom, b1.right] b2 = [b2.type, b2.top, b2.left, b2.bottom, b2.right] """ (top...
def merge_intervals(elems, overlap_thres=2.0): """ Project in x axis Sort by start Go through segments and keep max x1 Return a list of non-overlapping intervals """ overlap_thres = max(0.0, overlap_thres) ordered = sorted(elems, key=lambda e: e.x0) intervals = [] cur = [-overl...
def predict_heatmap(pdf_path, page_num, model, img_dim=448, img_dir="tmp/img"): """ Return an image corresponding to the page of the pdf documents saved at pdf_path. If the image is not found in img_dir this function creates it and saves it in img_dir. :param pdf_path: path to the pdf document. ...