signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def begin(self): | if not hasattr(self.local, '<STR_LIT>'):<EOL><INDENT>self.local.tx = []<EOL><DEDENT>self.local.tx.append(self.executable.begin())<EOL> | Enter a transaction explicitly.
No data will be written until the transaction has been committed. | f8609:c0:m7 |
def commit(self): | if hasattr(self.local, '<STR_LIT>') and self.local.tx:<EOL><INDENT>tx = self.local.tx.pop()<EOL>tx.commit()<EOL>self._flush_tables()<EOL><DEDENT> | Commit the current transaction.
Make all statements executed since the transaction was begun permanent. | f8609:c0:m8 |
def rollback(self): | if hasattr(self.local, '<STR_LIT>') and self.local.tx:<EOL><INDENT>tx = self.local.tx.pop()<EOL>tx.rollback()<EOL>self._flush_tables()<EOL><DEDENT> | Roll back the current transaction.
Discard all statements executed since the transaction was begun. | f8609:c0:m9 |
def __enter__(self): | self.begin()<EOL>return self<EOL> | Start a transaction. | f8609:c0:m10 |
def __exit__(self, error_type, error_value, traceback): | if error_type is None:<EOL><INDENT>try:<EOL><INDENT>self.commit()<EOL><DEDENT>except Exception:<EOL><INDENT>with safe_reraise():<EOL><INDENT>self.rollback()<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>self.rollback()<EOL><DEDENT> | End a transaction by committing or rolling back. | f8609:c0:m11 |
@property<EOL><INDENT>def tables(self):<DEDENT> | return self.inspect.get_table_names(schema=self.schema)<EOL> | Get a listing of all tables that exist in the database. | f8609:c0:m12 |
def __contains__(self, table_name): | try:<EOL><INDENT>return normalize_table_name(table_name) in self.tables<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT> | Check if the given table name exists in the database. | f8609:c0:m13 |
def create_table(self, table_name, primary_id=None, primary_type=None): | assert not isinstance(primary_type, six.string_types),'<STR_LIT>'<EOL>table_name = normalize_table_name(table_name)<EOL>with self.lock:<EOL><INDENT>if table_name not in self._tables:<EOL><INDENT>self._tables[table_name] = Table(self, table_name,<EOL>primary_id=primary_id,<EOL>primary_type=primary_type,<EOL>auto_create=True)<EOL><DEDENT>return self._tables.get(table_name)<EOL><DEDENT> | Create a new table.
Either loads a table or creates it if it doesn't exist yet. You can
define the name and type of the primary key field, if a new table is to
be created. The default is to create an auto-incrementing integer,
``id``. You can also set the primary key to be a string or big integer.
The caller will be responsible for the uniqueness of ``primary_id`` if
it is defined as a text type.
Returns a :py:class:`Table <dataset.Table>` instance.
::
table = db.create_table('population')
# custom id and type
table2 = db.create_table('population2', 'age')
table3 = db.create_table('population3',
primary_id='city',
primary_type=db.types.text)
# custom length of String
table4 = db.create_table('population4',
primary_id='city',
primary_type=db.types.string(25))
# no primary key
table5 = db.create_table('population5',
primary_id=False) | f8609:c0:m14 |
def load_table(self, table_name): | table_name = normalize_table_name(table_name)<EOL>with self.lock:<EOL><INDENT>if table_name not in self._tables:<EOL><INDENT>self._tables[table_name] = Table(self, table_name)<EOL><DEDENT>return self._tables.get(table_name)<EOL><DEDENT> | Load a table.
This will fail if the tables does not already exist in the database. If
the table exists, its columns will be reflected and are available on
the :py:class:`Table <dataset.Table>` object.
Returns a :py:class:`Table <dataset.Table>` instance.
::
table = db.load_table('population') | f8609:c0:m15 |
def get_table(self, table_name, primary_id=None, primary_type=None): | return self.create_table(table_name, primary_id, primary_type)<EOL> | Load or create a table.
This is now the same as ``create_table``.
::
table = db.get_table('population')
# you can also use the short-hand syntax:
table = db['population'] | f8609:c0:m16 |
def __getitem__(self, table_name): | return self.get_table(table_name)<EOL> | Get a given table. | f8609:c0:m17 |
def _ipython_key_completions_(self): | return self.tables<EOL> | Completion for table names with IPython. | f8609:c0:m18 |
def query(self, query, *args, **kwargs): | if isinstance(query, six.string_types):<EOL><INDENT>query = text(query)<EOL><DEDENT>_step = kwargs.pop('<STR_LIT>', QUERY_STEP)<EOL>rp = self.executable.execute(query, *args, **kwargs)<EOL>return ResultIter(rp, row_type=self.row_type, step=_step)<EOL> | Run a statement on the database directly.
Allows for the execution of arbitrary read/write queries. A query can
either be a plain text string, or a `SQLAlchemy expression
<http://docs.sqlalchemy.org/en/latest/core/tutorial.html#selecting>`_.
If a plain string is passed in, it will be converted to an expression
automatically.
Further positional and keyword arguments will be used for parameter
binding. To include a positional argument in your query, use question
marks in the query (i.e. ``SELECT * FROM tbl WHERE a = ?```). For
keyword arguments, use a bind parameter (i.e. ``SELECT * FROM tbl
WHERE a = :foo``).
::
statement = 'SELECT user, COUNT(*) c FROM photos GROUP BY user'
for row in db.query(statement):
print(row['user'], row['c'])
The returned iterator will yield each result sequentially. | f8609:c0:m19 |
def __repr__(self): | return '<STR_LIT>' % safe_url(self.url)<EOL> | Text representation contains the URL. | f8609:c0:m20 |
def setup_dataset(self): | dataset = []<EOL>with open(self.IRIS_PATH) as filehandler:<EOL><INDENT>file_data = filehandler.read()<EOL><DEDENT>for line in file_data.split("<STR_LIT:\n>"):<EOL><INDENT>line_data = [np.rint(float(x)) for x in line.split()]<EOL>if line_data:<EOL><INDENT>dataset.append(line_data)<EOL><DEDENT><DEDENT>problem = VectorDataClassificationProblem(dataset, target_index=<NUM_LIT:4>)<EOL>problem.distance = euclidean_vector_distance<EOL>self.corpus = dataset<EOL>self.problem = problem<EOL> | Creates a corpus with the iris dataset. Returns the dataset,
the attributes getter and the target getter. | f8614:c6:m0 |
def setup_dataset(self): | k = <NUM_LIT:2><EOL>n = <NUM_LIT:100><EOL>dataset = []<EOL>for i in range(n):<EOL><INDENT>bits = [(((i + j) * <NUM_LIT>) % (n + <NUM_LIT:1>)) % <NUM_LIT:2> for j in range(k)]<EOL>bits.append(sum(bits) % <NUM_LIT:2>)<EOL>dataset.append(bits)<EOL><DEDENT>problem = VectorDataClassificationProblem(dataset, target_index=k)<EOL>self.corpus = dataset<EOL>self.problem = problem<EOL> | Creates a corpus with n k-bit examples of the parity problem:
k random bits followed by a 1 if an odd number of bits are 1, else 0 | f8614:c7:m0 |
def setup_dataset(self): | size = <NUM_LIT> <EOL>dataset = []<EOL>for i in range(size):<EOL><INDENT>dataset.append([<EOL>i % <NUM_LIT:2> == <NUM_LIT:0>,<EOL>i % <NUM_LIT:3> == <NUM_LIT:0>,<EOL>i % <NUM_LIT:5> == <NUM_LIT:0>,<EOL>i % <NUM_LIT:7> == <NUM_LIT:0>,<EOL>self.isprime(i)<EOL>])<EOL><DEDENT>problem = VectorDataClassificationProblem(dataset, target_index=-<NUM_LIT:1>)<EOL>problem.distance = euclidean_vector_distance<EOL>self.corpus = dataset<EOL>self.problem = problem<EOL> | Creates a corpus of primes. Returns the dataset,
the attributes getter and the target getter. | f8614:c8:m0 |
def isprime(self, number): | if number < <NUM_LIT:2>:<EOL><INDENT>return False<EOL><DEDENT>if number == <NUM_LIT:2>:<EOL><INDENT>return True<EOL><DEDENT>if not number & <NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>for i in range(<NUM_LIT:3>, int(number ** <NUM_LIT:0.5>) + <NUM_LIT:1>, <NUM_LIT:2>):<EOL><INDENT>if number % i == <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL> | Returns if a number is prime testing if
is divisible by any number from 0 to sqrt(number) | f8614:c8:m1 |
def actions(self, state): | return list(self._map[state].keys())<EOL> | returns state's neighbors | f8625:c3:m2 |
def result(self, state, action): | return action<EOL> | returns the action because it indicates the next city | f8625:c3:m3 |
def boltzmann_exploration(actions, utilities, temperature, action_counter): | utilities = [utilities[x] for x in actions]<EOL>temperature = max(temperature, <NUM_LIT>)<EOL>_max = max(utilities)<EOL>_min = min(utilities)<EOL>if _max == _min:<EOL><INDENT>return random.choice(actions)<EOL><DEDENT>utilities = [math.exp(((u - _min) / (_max - _min)) / temperature) for u in utilities]<EOL>probs = [u / sum(utilities) for u in utilities]<EOL>i = <NUM_LIT:0><EOL>tot = probs[i]<EOL>r = random.random()<EOL>while i < len(actions) and r >= tot:<EOL><INDENT>i += <NUM_LIT:1><EOL>tot += probs[i]<EOL><DEDENT>return actions[i]<EOL> | returns an action with a probability depending on utilities and temperature | f8627:m1 |
def make_exponential_temperature(initial_temperature, alpha): | def _function(n):<EOL><INDENT>try:<EOL><INDENT>return initial_temperature / math.exp(n * alpha)<EOL><DEDENT>except OverflowError:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT><DEDENT>return _function<EOL> | returns a function like initial / exp(n * alpha) | f8627:m2 |
def actions(self, state): | raise NotImplementedError()<EOL> | Returns the actions available to perform from `state`.
The returned value is an iterable over actions. | f8627:c1:m0 |
def update_state(self, percept, agent): | return percept<EOL> | Override this method if you need to clean perception to a given agent | f8627:c1:m1 |
def is_attribute(method, name=None): | if name is None:<EOL><INDENT>name = method.__name__<EOL><DEDENT>method.is_attribute = True<EOL>method.name = name<EOL>return method<EOL> | Decorator for methods that are attributes. | f8629:m0 |
def learn(self): | raise NotImplementedError()<EOL> | Does the training. Returns nothing. | f8629:c0:m1 |
@property<EOL><INDENT>def attributes(self):<DEDENT> | return self.problem.attributes<EOL> | The attributes of the problem.
A list of callable objects. | f8629:c0:m2 |
@property<EOL><INDENT>def target(self):<DEDENT> | return self.problem.target<EOL> | The problem's target.
A callable that takes an observation and returns the correct
classification for it. | f8629:c0:m3 |
def classify(self, example): | raise NotImplementedError()<EOL> | Returns the classification for example. | f8629:c0:m4 |
def save(self, filepath): | if not filepath or not isinstance(filepath, str):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.dataset = None<EOL>with open(filepath, "<STR_LIT:wb>") as filehandler:<EOL><INDENT>pickle.dump(self, filehandler)<EOL><DEDENT> | Pickles the tree and saves it into `filepath` | f8629:c0:m5 |
def distance(self, a, b): | raise NotImplementedError()<EOL> | Custom distance between `a` and `b`. | f8629:c0:m6 |
@classmethod<EOL><INDENT>def load(cls, filepath):<DEDENT> | with open(filepath, "<STR_LIT:rb>") as filehandler:<EOL><INDENT>classifier = pickle.load(filehandler)<EOL><DEDENT>if not isinstance(classifier, Classifier):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return classifier<EOL> | Loads a pickled version of the classifier saved in `filepath` | f8629:c0:m7 |
def target(self, example): | raise NotImplementedError()<EOL> | Given an example it returns the classification for that
example. | f8629:c1:m2 |
def __init__(self, dataset, target_index): | super(VectorDataClassificationProblem, self).__init__()<EOL>try:<EOL><INDENT>example = next(iter(dataset))<EOL><DEDENT>except StopIteration:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.target_index = target_index<EOL>N = len(example)<EOL>if self.target_index < <NUM_LIT:0>: <EOL><INDENT>self.target_index = N + self.target_index<EOL><DEDENT>if self.target_index < <NUM_LIT:0> or N <= self.target_index:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>for i in range(N):<EOL><INDENT>if i == self.target_index:<EOL><INDENT>continue<EOL><DEDENT>attribute = VectorIndexAttribute(i, "<STR_LIT>".format(i))<EOL>self.attributes.append(attribute)<EOL><DEDENT> | `dataset` should be an iterable, *not* an iterator.
`target_index` is the index in the vector where the classification
of an example is defined. | f8629:c2:m0 |
def target(self, example): | return example[self.target_index]<EOL> | Uses the target defined in the creation of the vector problem
to return the target of `example`. | f8629:c2:m1 |
def __init__(self, function=None, name=None, description=None): | self.name = name<EOL>self.function = function<EOL>self.description = description<EOL> | Creates an attribute with `function`.
Adds a name and a description if it's specified. | f8629:c3:m0 |
def reason(self, example): | raise NotImplementedError()<EOL> | Returns a string with an explanation of
why the attribute is being applied. | f8629:c3:m1 |
def kfold(dataset, problem, method, k=<NUM_LIT:10>): | if k <= <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>dataset = list(dataset)<EOL>random.shuffle(dataset)<EOL>trials = <NUM_LIT:0><EOL>positive = <NUM_LIT:0><EOL>for i in range(k):<EOL><INDENT>train = [x for j, x in enumerate(dataset) if j % k != i]<EOL>test = [x for j, x in enumerate(dataset) if j % k == i]<EOL>classifier = method(train, problem)<EOL>for data in test:<EOL><INDENT>trials += <NUM_LIT:1><EOL>result = classifier.classify(data)<EOL>if result is not None and result[<NUM_LIT:0>] == problem.target(data):<EOL><INDENT>positive += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return float(positive) / float(trials)<EOL> | 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. | f8630:m1 |
def tree_to_str(root): | xs = []<EOL>for value, node, depth in iter_tree(root):<EOL><INDENT>template = "<STR_LIT>"<EOL>if node is not root:<EOL><INDENT>template += "<STR_LIT>"<EOL><DEDENT>if node.attribute is None:<EOL><INDENT>template += "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>template += "<STR_LIT>" +"<STR_LIT>"<EOL><DEDENT>line = template.format(indent="<STR_LIT:U+0020>" * depth,<EOL>value=value,<EOL>result=node.result[<NUM_LIT:0>],<EOL>prob=node.result[<NUM_LIT:1>],<EOL>split=str(node.attribute))<EOL>xs.append(line)<EOL><DEDENT>return "<STR_LIT:\n>".join(xs)<EOL> | Returns a string representation of a decision tree with
root node `root`. | f8631:m3 |
def learn(self, examples, attributes, parent_examples): | if not examples:<EOL><INDENT>return self.plurality_value(parent_examples)<EOL><DEDENT>elif len(set(map(self.target, examples))) == <NUM_LIT:1>:<EOL><INDENT>return self.plurality_value(examples)<EOL><DEDENT>elif not attributes:<EOL><INDENT>return self.plurality_value(examples)<EOL><DEDENT>A = max(attributes, key=lambda a: self.importance(a, examples))<EOL>tree = DecisionTreeNode(attribute=A)<EOL>for value in set(map(A, examples)):<EOL><INDENT>exs = [e for e in examples if A(e) == value]<EOL>subtree = self.learn(exs, attributes - set([A]), examples)<EOL>tree.add_branch(value, subtree)<EOL><DEDENT>return tree<EOL> | A decision tree learner that *strictly* follows the pseudocode given in
AIMA. In 3rd edition, see Figure 18.5, page 702. | f8631:c0:m1 |
def importance(self, attribute, examples): | gain_counter = OnlineInformationGain(attribute, self.target)<EOL>for example in examples:<EOL><INDENT>gain_counter.add(example)<EOL><DEDENT>return gain_counter.get_gain()<EOL> | 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 | f8631:c0:m3 |
def save(self, filepath): | if not filepath or not isinstance(filepath, str):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>with open(filepath, "<STR_LIT:wb>") as filehandler:<EOL><INDENT>pickle.dump(self, filehandler)<EOL><DEDENT> | 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. | f8631:c2:m3 |
def take_branch(self, example): | if self.attribute is None:<EOL><INDENT>return None<EOL><DEDENT>value = self.attribute(example)<EOL>return self.branches.get(value, None)<EOL> | 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
returns None. | f8631:c3:m1 |
def _max_gain_split(self, examples): | gains = self._new_set_of_gain_counters()<EOL>for example in examples:<EOL><INDENT>for gain in gains:<EOL><INDENT>gain.add(example)<EOL><DEDENT><DEDENT>winner = max(gains, key=lambda gain: gain.get_gain())<EOL>if not winner.get_target_class_counts():<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return winner<EOL> | Returns an OnlineInformationGain of the attribute with
max gain based on `examples`. | f8631:c4:m1 |
def _new_set_of_gain_counters(self): | return [OnlineInformationGain(attribute, self.target)<EOL>for attribute in self.attributes]<EOL> | Creates a new set of OnlineInformationGain objects
for each attribute. | f8631:c4:m2 |
def step(self, viewer=None): | if not self.is_completed(self.state):<EOL><INDENT>for agent in self.agents:<EOL><INDENT>action = agent.program(self.percept(agent, self.state))<EOL>next_state = self.do_action(self.state, action, agent)<EOL>if viewer:<EOL><INDENT>viewer.event(self.state, action, next_state, agent)<EOL><DEDENT>self.state = next_state<EOL>if self.is_completed(self.state):<EOL><INDENT>return<EOL><DEDENT><DEDENT><DEDENT> | This method evolves one step in time | f8632:c0:m2 |
def do_action(self, state, action, agent): | raise NotImplementedError()<EOL> | Override this method to apply an action performed by an agent to a state and return a new state | f8632:c0:m3 |
def is_completed(self, state): | return False<EOL> | Override this method when the environment have terminal states | f8632:c0:m4 |
def percept(self, agent, state): | return self.state<EOL> | This method make agent's perception | f8632:c0:m5 |
def breadth_first(problem, graph_search=False, viewer=None): | return _search(problem,<EOL>FifoList(),<EOL>graph_search=graph_search,<EOL>viewer=viewer)<EOL> | Breadth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. | f8634:m0 |
def depth_first(problem, graph_search=False, viewer=None): | return _search(problem,<EOL>LifoList(),<EOL>graph_search=graph_search,<EOL>viewer=viewer)<EOL> | Depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. | f8634:m1 |
def limited_depth_first(problem, depth_limit, graph_search=False, viewer=None): | return _search(problem,<EOL>LifoList(),<EOL>graph_search=graph_search,<EOL>depth_limit=depth_limit,<EOL>viewer=viewer)<EOL> | 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.result, and
SearchProblem.is_goal. | f8634:m2 |
def iterative_limited_depth_first(problem, graph_search=False, viewer=None): | solution = None<EOL>limit = <NUM_LIT:0><EOL>while not solution:<EOL><INDENT>solution = limited_depth_first(problem,<EOL>depth_limit=limit,<EOL>graph_search=graph_search,<EOL>viewer=viewer)<EOL>limit += <NUM_LIT:1><EOL><DEDENT>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', solution, '<STR_LIT>' % limit)<EOL><DEDENT>return solution<EOL> | Iterative limited depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. | f8634:m3 |
def uniform_cost(problem, graph_search=False, viewer=None): | return _search(problem,<EOL>BoundedPriorityQueue(),<EOL>graph_search=graph_search,<EOL>node_factory=SearchNodeCostOrdered,<EOL>graph_replace_when_better=True,<EOL>viewer=viewer)<EOL> | Uniform cost search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, and SearchProblem.cost. | f8634:m4 |
def greedy(problem, graph_search=False, viewer=None): | return _search(problem,<EOL>BoundedPriorityQueue(),<EOL>graph_search=graph_search,<EOL>node_factory=SearchNodeHeuristicOrdered,<EOL>graph_replace_when_better=True,<EOL>viewer=viewer)<EOL> | Greedy search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic. | f8634:m5 |
def astar(problem, graph_search=False, viewer=None): | return _search(problem,<EOL>BoundedPriorityQueue(),<EOL>graph_search=graph_search,<EOL>node_factory=SearchNodeStarOrdered,<EOL>graph_replace_when_better=True,<EOL>viewer=viewer)<EOL> | A* search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic. | f8634:m6 |
def _search(problem, fringe, graph_search=False, depth_limit=None,<EOL>node_factory=SearchNode, graph_replace_when_better=False,<EOL>viewer=None): | if viewer:<EOL><INDENT>viewer.event('<STR_LIT>')<EOL><DEDENT>memory = set()<EOL>initial_node = node_factory(state=problem.initial_state,<EOL>problem=problem)<EOL>fringe.append(initial_node)<EOL>while fringe:<EOL><INDENT>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', fringe.sorted())<EOL><DEDENT>node = fringe.pop()<EOL>if problem.is_goal(node.state):<EOL><INDENT>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', node, True)<EOL>viewer.event('<STR_LIT>', fringe.sorted(), node, '<STR_LIT>')<EOL><DEDENT>return node<EOL><DEDENT>else:<EOL><INDENT>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', node, False)<EOL><DEDENT><DEDENT>memory.add(node.state)<EOL>if depth_limit is None or node.depth < depth_limit:<EOL><INDENT>expanded = node.expand()<EOL>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', [node], [expanded])<EOL><DEDENT>for n in expanded:<EOL><INDENT>if graph_search:<EOL><INDENT>others = [x for x in fringe if x.state == n.state]<EOL>assert len(others) in (<NUM_LIT:0>, <NUM_LIT:1>)<EOL>if n.state not in memory and len(others) == <NUM_LIT:0>:<EOL><INDENT>fringe.append(n)<EOL><DEDENT>elif graph_replace_when_better and len(others) > <NUM_LIT:0> and n < others[<NUM_LIT:0>]:<EOL><INDENT>fringe.remove(others[<NUM_LIT:0>])<EOL>fringe.append(n)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>fringe.append(n)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', fringe.sorted(), None, '<STR_LIT>')<EOL><DEDENT> | Basic search algorithm, base of all the other search algorithms. | f8634:m7 |
def backtrack(problem, variable_heuristic='<STR_LIT>', value_heuristic='<STR_LIT>', inference=True): | assignment = {}<EOL>domains = deepcopy(problem.domains)<EOL>if variable_heuristic == MOST_CONSTRAINED_VARIABLE:<EOL><INDENT>variable_chooser = _most_constrained_variable_chooser<EOL><DEDENT>elif variable_heuristic == HIGHEST_DEGREE_VARIABLE:<EOL><INDENT>variable_chooser = _highest_degree_variable_chooser<EOL><DEDENT>else:<EOL><INDENT>variable_chooser = _basic_variable_chooser<EOL><DEDENT>if value_heuristic == LEAST_CONSTRAINING_VALUE:<EOL><INDENT>values_sorter = _least_constraining_values_sorter<EOL><DEDENT>else:<EOL><INDENT>values_sorter = _basic_values_sorter<EOL><DEDENT>return _backtracking(problem,<EOL>assignment,<EOL>domains,<EOL>variable_chooser,<EOL>values_sorter,<EOL>inference=inference)<EOL> | 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 heuristic for value choosing, can be
LEAST_CONSTRAINING_VALUE or blank for simple ordered choosing. | f8635:m0 |
def _basic_variable_chooser(problem, variables, domains): | return variables[<NUM_LIT:0>]<EOL> | Choose the next variable in order. | f8635:m1 |
def _most_constrained_variable_chooser(problem, variables, domains): | <EOL>return sorted(variables, key=lambda v: len(domains[v]))[<NUM_LIT:0>]<EOL> | Choose the variable that has less available values. | f8635:m2 |
def _highest_degree_variable_chooser(problem, variables, domains): | <EOL>return sorted(variables, key=lambda v: problem.var_degrees[v], reverse=True)[<NUM_LIT:0>]<EOL> | Choose the variable that is involved on more constraints. | f8635:m3 |
def _count_conflicts(problem, assignment, variable=None, value=None): | return len(_find_conflicts(problem, assignment, variable, value))<EOL> | Count the number of violated constraints on a given assignment. | f8635:m4 |
def _find_conflicts(problem, assignment, variable=None, value=None): | if variable is not None and value is not None:<EOL><INDENT>assignment = deepcopy(assignment)<EOL>assignment[variable] = value<EOL><DEDENT>conflicts = []<EOL>for neighbors, constraint in problem.constraints:<EOL><INDENT>if all(n in assignment for n in neighbors):<EOL><INDENT>if not _call_constraint(assignment, neighbors, constraint):<EOL><INDENT>conflicts.append((neighbors, constraint))<EOL><DEDENT><DEDENT><DEDENT>return conflicts<EOL> | Find violated constraints on a given assignment, with the possibility
of specifying a new variable and value to add to the assignment before
checking. | f8635:m6 |
def _basic_values_sorter(problem, assignment, variable, domains): | return domains[variable][:]<EOL> | Sort values in the same original order. | f8635:m7 |
def _least_constraining_values_sorter(problem, assignment, variable, domains): | <EOL>def update_assignment(value):<EOL><INDENT>new_assignment = deepcopy(assignment)<EOL>new_assignment[variable] = value<EOL>return new_assignment<EOL><DEDENT>values = sorted(domains[variable][:],<EOL>key=lambda v: _count_conflicts(problem, assignment,<EOL>variable, v))<EOL>return values<EOL> | Sort values based on how many conflicts they generate if assigned. | f8635:m8 |
def _backtracking(problem, assignment, domains, variable_chooser, values_sorter, inference=True): | from simpleai.search.arc import arc_consistency_3<EOL>if len(assignment) == len(problem.variables):<EOL><INDENT>return assignment<EOL><DEDENT>pending = [v for v in problem.variables<EOL>if v not in assignment]<EOL>variable = variable_chooser(problem, pending, domains)<EOL>values = values_sorter(problem, assignment, variable, domains)<EOL>for value in values:<EOL><INDENT>new_assignment = deepcopy(assignment)<EOL>new_assignment[variable] = value<EOL>if not _count_conflicts(problem, new_assignment): <EOL><INDENT>new_domains = deepcopy(domains)<EOL>new_domains[variable] = [value]<EOL>if not inference or arc_consistency_3(new_domains, problem.constraints):<EOL><INDENT>result = _backtracking(problem,<EOL>new_assignment,<EOL>new_domains,<EOL>variable_chooser,<EOL>values_sorter,<EOL>inference=inference)<EOL>if result:<EOL><INDENT>return result<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return None<EOL> | Internal recursive backtracking algorithm. | f8635:m9 |
def _min_conflicts_value(problem, assignment, variable): | return argmin(problem.domains[variable], lambda x: _count_conflicts(problem, assignment, variable, x))<EOL> | Return the value generate the less number of conflicts.
In case of tie, a random value is selected among this values subset. | f8635:m10 |
def min_conflicts(problem, initial_assignment=None, iterations_limit=<NUM_LIT:0>): | assignment = {}<EOL>if initial_assignment:<EOL><INDENT>assignment.update(initial_assignment)<EOL><DEDENT>else:<EOL><INDENT>for variable in problem.variables:<EOL><INDENT>value = _min_conflicts_value(problem, assignment, variable)<EOL>assignment[variable] = value<EOL><DEDENT><DEDENT>iteration = <NUM_LIT:0><EOL>run = True<EOL>while run:<EOL><INDENT>conflicts = _find_conflicts(problem, assignment)<EOL>conflict_variables = [v for v in problem.variables<EOL>if any(v in conflict[<NUM_LIT:0>] for conflict in conflicts)]<EOL>if conflict_variables:<EOL><INDENT>variable = random.choice(conflict_variables)<EOL>value = _min_conflicts_value(problem, assignment, variable)<EOL>assignment[variable] = value<EOL><DEDENT>iteration += <NUM_LIT:1><EOL>if iterations_limit and iteration >= iterations_limit:<EOL><INDENT>run = False<EOL><DEDENT>elif not _count_conflicts(problem, assignment):<EOL><INDENT>run = False<EOL><DEDENT><DEDENT>return assignment<EOL> | 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 if finds an assignment
that doesn't generate conflicts (a solution). | f8635:m11 |
def convert_to_binary(variables, domains, constraints): | def wdiff(vars_):<EOL><INDENT>def diff(variables, values):<EOL><INDENT>hidden, other = variables<EOL>if hidden.startswith('<STR_LIT>'):<EOL><INDENT>idx = vars_.index(other)<EOL>return values[<NUM_LIT:1>] == values[<NUM_LIT:0>][idx]<EOL><DEDENT>else:<EOL><INDENT>idx = vars_.index(hidden)<EOL>return values[<NUM_LIT:0>] == values[<NUM_LIT:1>][idx]<EOL><DEDENT><DEDENT>diff.no_wrap = True <EOL>return diff<EOL><DEDENT>new_constraints = []<EOL>new_domains = copy(domains)<EOL>new_variables = list(variables)<EOL>last = <NUM_LIT:0><EOL>for vars_, const in constraints:<EOL><INDENT>if len(vars_) == <NUM_LIT:2>:<EOL><INDENT>new_constraints.append((vars_, const))<EOL>continue<EOL><DEDENT>hidden = '<STR_LIT>' % last<EOL>new_variables.append(hidden)<EOL>last += <NUM_LIT:1><EOL>new_domains[hidden] = [t for t in product(*map(domains.get, vars_)) if const(vars_, t)]<EOL>for var in vars_:<EOL><INDENT>new_constraints.append(((hidden, var), wdiff(vars_)))<EOL><DEDENT><DEDENT>return new_variables, new_domains, new_constraints<EOL> | Returns new constraint list, all binary, using hidden variables.
You can use it as previous step when creating a problem. | f8635:m12 |
def actions(self, state): | raise NotImplementedError<EOL> | Returns the actions available to perform from `state`.
The returned value is an iterable over actions.
Actions are problem-specific and no assumption should be made about
them. | f8638:c0:m1 |
def result(self, state, action): | raise NotImplementedError<EOL> | Returns the resulting state of applying `action` to `state`. | f8638:c0:m2 |
def cost(self, state, action, state2): | return <NUM_LIT:1><EOL> | Returns the cost of applying `action` from `state` to `state2`.
The returned value is a number (integer or floating point).
By default this function returns `1`. | f8638:c0:m3 |
def is_goal(self, state): | raise NotImplementedError<EOL> | Returns `True` if `state` is a goal state and `False` otherwise | f8638:c0:m4 |
def value(self, state): | raise NotImplementedError<EOL> | Returns the value of `state` as it is needed by optimization
problems.
Value is a number (integer or floating point). | f8638:c0:m5 |
def heuristic(self, state): | return <NUM_LIT:0><EOL> | Returns an estimate of the cost remaining to reach the solution
from `state`. | f8638:c0:m6 |
def crossover(self, state1, state2): | raise NotImplementedError<EOL> | Crossover method for genetic search. It should return a new state that
is the 'mix' (somehow) of `state1` and `state2`. | f8638:c0:m7 |
def mutate(self, state): | raise NotImplementedError<EOL> | Mutation method for genetic search. It should return a new state that
is a slight random variation of `state`. | f8638:c0:m8 |
def generate_random_state(self): | raise NotImplementedError<EOL> | Generates a random state for genetic search. It's mainly used for the
seed states in the initilization of genetic search. | f8638:c0:m9 |
def state_representation(self, state): | return str(state)<EOL> | Returns a string representation of a state.
By default it returns str(state). | f8638:c0:m10 |
def action_representation(self, action): | return str(action)<EOL> | Returns a string representation of an action.
By default it returns str(action). | f8638:c0:m11 |
def expand(self, local_search=False): | new_nodes = []<EOL>for action in self.problem.actions(self.state):<EOL><INDENT>new_state = self.problem.result(self.state, action)<EOL>cost = self.problem.cost(self.state,<EOL>action,<EOL>new_state)<EOL>nodefactory = self.__class__<EOL>new_nodes.append(nodefactory(state=new_state,<EOL>parent=None if local_search else self,<EOL>problem=self.problem,<EOL>action=action,<EOL>cost=self.cost + cost,<EOL>depth=self.depth + <NUM_LIT:1>))<EOL><DEDENT>return new_nodes<EOL> | Create successors. | f8638:c1:m1 |
def path(self): | node = self<EOL>path = []<EOL>while node:<EOL><INDENT>path.append((node.action, node.state))<EOL>node = node.parent<EOL><DEDENT>return list(reversed(path))<EOL> | Path (list of nodes and actions) from root to this node. | f8638:c1:m2 |
def revise(domains, arc, constraints): | x, y = arc<EOL>related_constraints = [(neighbors, constraint)<EOL>for neighbors, constraint in constraints<EOL>if set(arc) == set(neighbors)]<EOL>modified = False<EOL>for neighbors, constraint in related_constraints:<EOL><INDENT>for x_value in domains[x]:<EOL><INDENT>constraint_results = (_call_constraint({x: x_value, y: y_value},<EOL>neighbors, constraint)<EOL>for y_value in domains[y])<EOL>if not any(constraint_results):<EOL><INDENT>domains[x].remove(x_value)<EOL>modified = True<EOL><DEDENT><DEDENT><DEDENT>return modified<EOL> | 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, for
those constraints affecting X and Y. | f8639:m0 |
def all_arcs(constraints): | arcs = set()<EOL>for neighbors, constraint in constraints:<EOL><INDENT>if len(neighbors) == <NUM_LIT:2>:<EOL><INDENT>x, y = neighbors<EOL>list(map(arcs.add, ((x, y), (y, x))))<EOL><DEDENT><DEDENT>return arcs<EOL> | For each constraint ((X, Y), const) adds:
((X, Y), const)
((Y, X), const) | f8639:m1 |
def arc_consistency_3(domains, constraints): | arcs = list(all_arcs(constraints))<EOL>pending_arcs = set(arcs)<EOL>while pending_arcs:<EOL><INDENT>x, y = pending_arcs.pop()<EOL>if revise(domains, (x, y), constraints):<EOL><INDENT>if len(domains[x]) == <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT>pending_arcs = pending_arcs.union((x2, y2) for x2, y2 in arcs<EOL>if y2 == x)<EOL><DEDENT><DEDENT>return True<EOL> | Makes a CSP problem arc consistent.
Ignores any constraint that is not binary. | f8639:m2 |
def _all_expander(fringe, iteration, viewer): | expanded_neighbors = [node.expand(local_search=True)<EOL>for node in fringe]<EOL>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', list(fringe), expanded_neighbors)<EOL><DEDENT>list(map(fringe.extend, expanded_neighbors))<EOL> | Expander that expands all nodes on the fringe. | f8641:m0 |
def beam(problem, beam_size=<NUM_LIT:100>, iterations_limit=<NUM_LIT:0>, viewer=None): | return _local_search(problem,<EOL>_all_expander,<EOL>iterations_limit=iterations_limit,<EOL>fringe_size=beam_size,<EOL>random_initial_states=True,<EOL>stop_when_no_better=iterations_limit==<NUM_LIT:0>,<EOL>viewer=viewer)<EOL> | 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.
Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,
and SearchProblem.generate_random_state. | f8641:m1 |
def _first_expander(fringe, iteration, viewer): | current = fringe[<NUM_LIT:0>]<EOL>neighbors = current.expand(local_search=True)<EOL>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', [current], [neighbors])<EOL><DEDENT>fringe.extend(neighbors)<EOL> | Expander that expands only the first node on the fringe. | f8641:m2 |
def beam_best_first(problem, beam_size=<NUM_LIT:100>, iterations_limit=<NUM_LIT:0>, viewer=None): | return _local_search(problem,<EOL>_first_expander,<EOL>iterations_limit=iterations_limit,<EOL>fringe_size=beam_size,<EOL>random_initial_states=True,<EOL>stop_when_no_better=iterations_limit==<NUM_LIT:0>,<EOL>viewer=viewer)<EOL> | 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 the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value. | f8641:m3 |
def hill_climbing(problem, iterations_limit=<NUM_LIT:0>, viewer=None): | return _local_search(problem,<EOL>_first_expander,<EOL>iterations_limit=iterations_limit,<EOL>fringe_size=<NUM_LIT:1>,<EOL>stop_when_no_better=True,<EOL>viewer=viewer)<EOL> | 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, SearchProblem.result, and
SearchProblem.value. | f8641:m4 |
def _random_best_expander(fringe, iteration, viewer): | current = fringe[<NUM_LIT:0>]<EOL>neighbors = current.expand(local_search=True)<EOL>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', [current], [neighbors])<EOL><DEDENT>betters = [n for n in neighbors<EOL>if n.value > current.value]<EOL>if betters:<EOL><INDENT>chosen = random.choice(betters)<EOL>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', chosen)<EOL><DEDENT>fringe.append(chosen)<EOL><DEDENT> | Expander that expands one randomly chosen nodes on the fringe that
is better than the current (first) node. | f8641:m5 |
def hill_climbing_stochastic(problem, iterations_limit=<NUM_LIT:0>, viewer=None): | return _local_search(problem,<EOL>_random_best_expander,<EOL>iterations_limit=iterations_limit,<EOL>fringe_size=<NUM_LIT:1>,<EOL>stop_when_no_better=iterations_limit==<NUM_LIT:0>,<EOL>viewer=viewer)<EOL> | 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.actions, SearchProblem.result, and
SearchProblem.value. | f8641:m6 |
def hill_climbing_random_restarts(problem, restarts_limit, iterations_limit=<NUM_LIT:0>, viewer=None): | restarts = <NUM_LIT:0><EOL>best = None<EOL>while restarts < restarts_limit:<EOL><INDENT>new = _local_search(problem,<EOL>_first_expander,<EOL>iterations_limit=iterations_limit,<EOL>fringe_size=<NUM_LIT:1>,<EOL>random_initial_states=True,<EOL>stop_when_no_better=True,<EOL>viewer=viewer)<EOL>if not best or best.value < new.value:<EOL><INDENT>best = new<EOL><DEDENT>restarts += <NUM_LIT:1><EOL><DEDENT>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', best, '<STR_LIT>' % restarts_limit)<EOL><DEDENT>return best<EOL> | 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 iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,
and SearchProblem.generate_random_state. | f8641:m7 |
def _exp_schedule(iteration, k=<NUM_LIT:20>, lam=<NUM_LIT>, limit=<NUM_LIT:100>): | return k * math.exp(-lam * iteration)<EOL> | Possible scheduler for simulated_annealing, based on the aima example. | f8641:m8 |
def _create_simulated_annealing_expander(schedule): | def _expander(fringe, iteration, viewer):<EOL><INDENT>T = schedule(iteration)<EOL>current = fringe[<NUM_LIT:0>]<EOL>neighbors = current.expand(local_search=True)<EOL>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', [current], [neighbors])<EOL><DEDENT>if neighbors:<EOL><INDENT>succ = random.choice(neighbors)<EOL>delta_e = succ.value - current.value<EOL>if delta_e > <NUM_LIT:0> or random.random() < math.exp(delta_e / T):<EOL><INDENT>fringe.pop()<EOL>fringe.append(succ)<EOL>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', succ)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return _expander<EOL> | 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. | f8641:m9 |
def simulated_annealing(problem, schedule=_exp_schedule, iterations_limit=<NUM_LIT:0>, viewer=None): | return _local_search(problem,<EOL>_create_simulated_annealing_expander(schedule),<EOL>iterations_limit=iterations_limit,<EOL>fringe_size=<NUM_LIT:1>,<EOL>stop_when_no_better=iterations_limit==<NUM_LIT:0>,<EOL>viewer=viewer)<EOL> | 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 of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value. | f8641:m10 |
def _create_genetic_expander(problem, mutation_chance): | def _expander(fringe, iteration, viewer):<EOL><INDENT>fitness = [x.value for x in fringe]<EOL>sampler = InverseTransformSampler(fitness, fringe)<EOL>new_generation = []<EOL>expanded_nodes = []<EOL>expanded_neighbors = []<EOL>for _ in fringe:<EOL><INDENT>node1 = sampler.sample()<EOL>node2 = sampler.sample()<EOL>child = problem.crossover(node1.state, node2.state)<EOL>action = '<STR_LIT>'<EOL>if random.random() < mutation_chance:<EOL><INDENT>child = problem.mutate(child)<EOL>action += '<STR_LIT>'<EOL><DEDENT>child_node = SearchNodeValueOrdered(state=child, problem=problem, action=action)<EOL>new_generation.append(child_node)<EOL>expanded_nodes.append(node1)<EOL>expanded_neighbors.append([child_node])<EOL>expanded_nodes.append(node2)<EOL>expanded_neighbors.append([child_node])<EOL><DEDENT>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', expanded_nodes, expanded_neighbors)<EOL><DEDENT>fringe.clear()<EOL>for node in new_generation:<EOL><INDENT>fringe.append(node)<EOL><DEDENT><DEDENT>return _expander<EOL> | Creates an expander that expands the bests nodes of the population,
crossing over them. | f8641:m11 |
def genetic(problem, population_size=<NUM_LIT:100>, mutation_chance=<NUM_LIT:0.1>,<EOL>iterations_limit=<NUM_LIT:0>, viewer=None): | return _local_search(problem,<EOL>_create_genetic_expander(problem, mutation_chance),<EOL>iterations_limit=iterations_limit,<EOL>fringe_size=population_size,<EOL>random_initial_states=True,<EOL>stop_when_no_better=iterations_limit==<NUM_LIT:0>,<EOL>viewer=viewer)<EOL> | 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_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.generate_random_state, SearchProblem.crossover,
SearchProblem.mutate and SearchProblem.value. | f8641:m12 |
def _local_search(problem, fringe_expander, iterations_limit=<NUM_LIT:0>, fringe_size=<NUM_LIT:1>,<EOL>random_initial_states=False, stop_when_no_better=True,<EOL>viewer=None): | if viewer:<EOL><INDENT>viewer.event('<STR_LIT>')<EOL><DEDENT>fringe = BoundedPriorityQueue(fringe_size)<EOL>if random_initial_states:<EOL><INDENT>for _ in range(fringe_size):<EOL><INDENT>s = problem.generate_random_state()<EOL>fringe.append(SearchNodeValueOrdered(state=s, problem=problem))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>fringe.append(SearchNodeValueOrdered(state=problem.initial_state,<EOL>problem=problem))<EOL><DEDENT>finish_reason = '<STR_LIT>'<EOL>iteration = <NUM_LIT:0><EOL>run = True<EOL>best = None<EOL>while run:<EOL><INDENT>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', list(fringe))<EOL><DEDENT>old_best = fringe[<NUM_LIT:0>]<EOL>fringe_expander(fringe, iteration, viewer)<EOL>best = fringe[<NUM_LIT:0>]<EOL>iteration += <NUM_LIT:1><EOL>if iterations_limit and iteration >= iterations_limit:<EOL><INDENT>run = False<EOL>finish_reason = '<STR_LIT>'<EOL><DEDENT>elif old_best.value >= best.value and stop_when_no_better:<EOL><INDENT>run = False<EOL>finish_reason = '<STR_LIT>'<EOL><DEDENT><DEDENT>if viewer:<EOL><INDENT>viewer.event('<STR_LIT>', fringe, best, '<STR_LIT>' % finish_reason)<EOL><DEDENT>return best<EOL> | Basic algorithm for all local search algorithms. | f8641:m13 |
def actions(self, state): | actions = []<EOL>for index, char in enumerate(state):<EOL><INDENT>if char == '<STR_LIT:_>':<EOL><INDENT>actions.append(index)<EOL><DEDENT><DEDENT>return actions<EOL> | actions are index where we can make a move | f8645:c0:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.