From 5dc3db51975a259c7eff84db8561df2f4c545fc4 Mon Sep 17 00:00:00 2001 From: Rahul Goswami Date: Tue, 13 Mar 2018 19:04:50 +0530 Subject: [PATCH 1/5] test commit --- agents.ipynb | 46 +++++++++++++++++++++++----------------------- zp | 0 2 files changed, 23 insertions(+), 23 deletions(-) create mode 100644 zp diff --git a/agents.ipynb b/agents.ipynb index 65878bbab..4c21b359f 100644 --- a/agents.ipynb +++ b/agents.ipynb @@ -16,7 +16,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": null, "metadata": { "collapsed": true, "scrolled": true @@ -738,7 +738,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -757,7 +757,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -776,7 +776,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -795,7 +795,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -814,7 +814,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -833,7 +833,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -852,7 +852,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -871,7 +871,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -890,7 +890,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -909,7 +909,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -928,7 +928,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -947,7 +947,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -966,7 +966,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -985,7 +985,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1004,7 +1004,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1023,7 +1023,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1042,7 +1042,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1061,7 +1061,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1080,7 +1080,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1099,7 +1099,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1118,7 +1118,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" } ], "source": [ @@ -1211,7 +1211,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", diff --git a/zp b/zp new file mode 100644 index 000000000..e69de29bb From 0361ba86ca32fd83b9053d74d456e604ce8efa84 Mon Sep 17 00:00:00 2001 From: Rahul Goswami Date: Tue, 13 Mar 2018 19:13:14 +0530 Subject: [PATCH 2/5] agents.ipynb --- agents.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/agents.ipynb b/agents.ipynb index 4c21b359f..8be4c2ae9 100644 --- a/agents.ipynb +++ b/agents.ipynb @@ -81,7 +81,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": null, "metadata": { "collapsed": true }, From e406ca069c1f070a5f12dcc3d749b32585d89cbf Mon Sep 17 00:00:00 2001 From: Rahul Goswami Date: Tue, 13 Mar 2018 19:16:05 +0530 Subject: [PATCH 3/5] agents.ipynb --- agents.ipynb | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/agents.ipynb b/agents.ipynb index 8be4c2ae9..65878bbab 100644 --- a/agents.ipynb +++ b/agents.ipynb @@ -16,7 +16,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, "metadata": { "collapsed": true, "scrolled": true @@ -81,7 +81,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "metadata": { "collapsed": true }, @@ -738,7 +738,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -757,7 +757,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -776,7 +776,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -795,7 +795,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -814,7 +814,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -833,7 +833,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -852,7 +852,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -871,7 +871,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -890,7 +890,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -909,7 +909,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -928,7 +928,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -947,7 +947,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -966,7 +966,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -985,7 +985,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1004,7 +1004,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1023,7 +1023,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1042,7 +1042,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1061,7 +1061,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1080,7 +1080,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1099,7 +1099,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1118,7 +1118,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" } ], "source": [ @@ -1211,7 +1211,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", From 7711eb8ed9730475101b1a313f87a7a9d2beb927 Mon Sep 17 00:00:00 2001 From: Rahul Goswami Date: Tue, 13 Mar 2018 20:11:54 +0530 Subject: [PATCH 4/5] Fixed all the instances of issue #833 --- agents.ipynb | 48 +++++++++++++++++++++++----------------------- agents.py | 12 ++++++------ csp.py | 4 ++-- knowledge.py | 52 +++++++++++++++++++++----------------------------- logic.py | 7 ++++--- nlp.py | 2 +- notebook.py | 46 ++++++++++++++++++++++---------------------- planning.py | 32 ++++++++++++++++--------------- probability.py | 11 ++++++----- rl.py | 30 ++++++++++++++--------------- text.py | 24 ++++++++++++----------- zp | 0 12 files changed, 133 insertions(+), 135 deletions(-) delete mode 100644 zp diff --git a/agents.ipynb b/agents.ipynb index 65878bbab..8be4c2ae9 100644 --- a/agents.ipynb +++ b/agents.ipynb @@ -16,7 +16,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": null, "metadata": { "collapsed": true, "scrolled": true @@ -81,7 +81,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": null, "metadata": { "collapsed": true }, @@ -738,7 +738,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -757,7 +757,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -776,7 +776,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -795,7 +795,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -814,7 +814,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -833,7 +833,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -852,7 +852,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -871,7 +871,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -890,7 +890,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -909,7 +909,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -928,7 +928,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -947,7 +947,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -966,7 +966,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -985,7 +985,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1004,7 +1004,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1023,7 +1023,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1042,7 +1042,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1061,7 +1061,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1080,7 +1080,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1099,7 +1099,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", @@ -1118,7 +1118,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" } ], "source": [ @@ -1211,7 +1211,7 @@ ] }, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" }, { "name": "stdout", diff --git a/agents.py b/agents.py index 9b1ff0d33..eb085757a 100644 --- a/agents.py +++ b/agents.py @@ -96,7 +96,7 @@ def program(percept): self.program = program def can_grab(self, thing): - """Returns True if this agent can grab this thing. + """Return True if this agent can grab this thing. Override for appropriate subclasses of Agent and Thing.""" return False @@ -444,7 +444,7 @@ def move_to(self, thing, destination): return thing.bump def add_thing(self, thing, location=(1, 1), exclude_duplicate_class_items=False): - """Adds things to the world. If (exclude_duplicate_class_items) then the item won't be + """Add things to the world. If (exclude_duplicate_class_items) then the item won't be added if the location has at least one item of the same class.""" if (self.is_inbounds(location)): if (exclude_duplicate_class_items and @@ -809,7 +809,7 @@ def init_world(self, program): self.add_thing(Explorer(program), (1, 1), True) def get_world(self, show_walls=True): - """Returns the items in the world""" + """Return the items in the world""" result = [] x_start, y_start = (0, 0) if show_walls else (1, 1) @@ -826,7 +826,7 @@ def get_world(self, show_walls=True): return result def percepts_from(self, agent, location, tclass=Thing): - """Returns percepts from a given location, + """Return percepts from a given location, and replaces some items with percepts from chapter 7.""" thing_percepts = { Gold: Glitter(), @@ -846,7 +846,7 @@ def percepts_from(self, agent, location, tclass=Thing): return result if len(result) else [None] def percept(self, agent): - """Returns things in adjacent (not diagonal) cells of the agent. + """Return things in adjacent (not diagonal) cells of the agent. Result format: [Left, Right, Up, Down, Center / Current location]""" x, y = agent.location result = [] @@ -907,7 +907,7 @@ def execute_action(self, agent, action): agent.has_arrow = False def in_danger(self, agent): - """Checks if Explorer is in danger (Pit or Wumpus), if he is, kill him""" + """Check if Explorer is in danger (Pit or Wumpus), if he is, kill him""" for thing in self.list_things_at(agent.location): if isinstance(thing, Pit) or (isinstance(thing, Wumpus) and thing.alive): agent.alive = False diff --git a/csp.py b/csp.py index 62772c322..70223acf2 100644 --- a/csp.py +++ b/csp.py @@ -351,7 +351,7 @@ def topological_sort(X, root): def build_topological(node, parent, neighbors, visited, stack, parents): - """Builds the topological sort and the parents of each node in the graph""" + """Build the topological sort and the parents of each node in the graph.""" visited[node] = True for n in neighbors[node]: @@ -427,7 +427,7 @@ def MapColoringCSP(colors, neighbors): different_values_constraint) -def parse_neighbors(neighbors, variables=[]): +def parse_neighbors(neighbors, variables=None): """Convert a string of the form 'X: Y Z; Y: Z' into a dict mapping regions to neighbors. The syntax is a region name followed by a ':' followed by zero or more region names, followed by ';', repeated for diff --git a/knowledge.py b/knowledge.py index 6fe09acd2..62edcd09c 100644 --- a/knowledge.py +++ b/knowledge.py @@ -11,7 +11,7 @@ # ______________________________________________________________________________ -def current_best_learning(examples, h, examples_so_far=[]): +def current_best_learning(examples, h, examples_so_far=None): """ [Figure 19.2] The hypothesis is a list of dictionaries, with each dictionary representing a disjunction.""" @@ -95,7 +95,7 @@ def generalizations(examples_so_far, h): def add_or(examples_so_far, h): - """Adds an OR operation to the hypothesis. The AND operations in the disjunction + """Add an OR operation to the hypothesis. The AND operations in the disjunction are generated by the last example (which is the problematic one).""" ors = [] e = examples_so_far[-1] @@ -135,7 +135,7 @@ def version_space_update(V, e): def all_hypotheses(examples): - """Builds a list of all the possible hypotheses""" + """Build a list of all the possible hypotheses""" values = values_table(examples) h_powerset = powerset(values.keys()) hypotheses = [] @@ -148,7 +148,7 @@ def all_hypotheses(examples): def values_table(examples): - """Builds a table with all the possible values for each attribute. + """Build a table with all the possible values for each attribute. Returns a dictionary with keys the attribute names and values a list with the possible values for the corresponding attribute.""" values = defaultdict(lambda: []) @@ -210,7 +210,7 @@ def build_h_combinations(hypotheses): def minimal_consistent_det(E, A): - """Returns a minimal set of attributes which give consistent determination""" + """Return a minimal set of attributes which give consistent determination""" n = len(A) for i in range(n + 1): @@ -220,7 +220,7 @@ def minimal_consistent_det(E, A): def consistent_det(A, E): - """Checks if the attributes(A) is consistent with the examples(E)""" + """Check if the attributes(A) is consistent with the examples(E)""" H = {} for e in E: @@ -235,9 +235,9 @@ def consistent_det(A, E): class FOIL_container(FolKB): - """Holds the kb and other necessary elements required by FOIL""" + """Hold the kb and other necessary elements required by FOIL.""" - def __init__(self, clauses=[]): + def __init__(self, clauses=None): self.const_syms = set() self.pred_syms = set() FolKB.__init__(self, clauses) @@ -251,7 +251,7 @@ def tell(self, sentence): raise Exception("Not a definite clause: {}".format(sentence)) def foil(self, examples, target): - """Learns a list of first-order horn clauses + """Learn a list of first-order horn clauses 'examples' is a tuple: (positive_examples, negative_examples). positive_examples and negative_examples are both lists which contain substitutions.""" clauses = [] @@ -268,10 +268,10 @@ def foil(self, examples, target): return clauses def new_clause(self, examples, target): - """Finds a horn clause which satisfies part of the positive + """Find a horn clause which satisfies part of the positive examples but none of the negative examples. The horn clause is specified as [consequent, list of antecedents] - Return value is the tuple (horn_clause, extended_positive_examples)""" + Return value is the tuple (horn_clause, extended_positive_examples).""" clause = [target, []] # [positive_examples, negative_examples] extended_examples = examples @@ -284,14 +284,14 @@ def new_clause(self, examples, target): return (clause, extended_examples[0]) def extend_example(self, example, literal): - """Generates extended examples which satisfy the literal""" + """Generate extended examples which satisfy the literal.""" # find all substitutions that satisfy literal for s in self.ask_generator(subst(example, literal)): s.update(example) yield s def new_literals(self, clause): - """Generates new literals based on known predicate symbols. + """Generate new literals based on known predicate symbols. Generated literal must share atleast one variable with clause""" share_vars = variables(clause[0]) for l in clause[1]: @@ -304,7 +304,7 @@ def new_literals(self, clause): yield Expr(pred, *[var for var in args]) def choose_literal(self, literals, examples): - """Chooses the best literal based on the information gain""" + """Choose the best literal based on the information gain.""" def gain(l): pre_pos = len(examples[0]) pre_neg = len(examples[1]) @@ -328,8 +328,8 @@ def represents(d): return max(literals, key=gain) def update_examples(self, target, examples, extended_examples): - """Adds to the kb those examples what are represented in extended_examples - List of omitted examples is returned""" + """Add to the kb those examples what are represented in extended_examples + List of omitted examples is returned.""" uncovered = [] for example in examples: def represents(d): @@ -346,7 +346,7 @@ def represents(d): def check_all_consistency(examples, h): - """Check for the consistency of all examples under h""" + """Check for the consistency of all examples under h.""" for e in examples: if not is_consistent(e, h): return False @@ -355,7 +355,7 @@ def check_all_consistency(examples, h): def check_negative_consistency(examples, h): - """Check if the negative examples are consistent under h""" + """Check if the negative examples are consistent under h.""" for e in examples: if e['GOAL']: continue @@ -367,7 +367,7 @@ def check_negative_consistency(examples, h): def disjunction_value(e, d): - """The value of example e under disjunction d""" + """The value of example e under disjunction d.""" for k, v in d.items(): if v[0] == '!': # v is a NOT expression @@ -381,7 +381,7 @@ def disjunction_value(e, d): def guess_value(e, h): - """Guess value of example e under hypothesis h""" + """Guess value of example e under hypothesis h.""" for d in h: if disjunction_value(e, d): return True @@ -394,16 +394,8 @@ def is_consistent(e, h): def false_positive(e, h): - if e["GOAL"] == False: - if guess_value(e, h): - return True - - return False + return guess_value(e, h) and not e["GOAL"] def false_negative(e, h): - if e["GOAL"] == True: - if not guess_value(e, h): - return True - - return False + return e["GOAL"] and not guess_value(e, h) diff --git a/logic.py b/logic.py index 5810e633f..129d281cf 100644 --- a/logic.py +++ b/logic.py @@ -901,10 +901,11 @@ class FolKB(KB): False """ - def __init__(self, initial_clauses=[]): + def __init__(self, initial_clauses=None): self.clauses = [] # inefficient: no indexing - for clause in initial_clauses: - self.tell(clause) + if initial_clauses: + for clause in initial_clauses: + self.tell(clause) def tell(self, sentence): if is_definite_clause(sentence): diff --git a/nlp.py b/nlp.py index ace6de90d..6ad92b6bb 100644 --- a/nlp.py +++ b/nlp.py @@ -272,7 +272,7 @@ def __repr__(self): class Chart: """Class for parsing sentences using a chart data structure. - >>> chart = Chart(E0); + >>> chart = Chart(E0) >>> len(chart.parses('the stench is in 2 2')) 1 """ diff --git a/notebook.py b/notebook.py index ae0976900..4bb53cf1c 100644 --- a/notebook.py +++ b/notebook.py @@ -912,17 +912,17 @@ def show_map(graph_data, node_colors = None): # set the size of the plot plt.figure(figsize=(18,13)) # draw the graph (both nodes and edges) with locations from romania_locations - nx.draw(G, pos = {k : node_positions[k] for k in G.nodes()}, - node_color = [node_colors[node] for node in G.nodes()], linewidths = 0.3, edgecolors = 'k') + nx.draw(G, pos={k: node_positions[k] for k in G.nodes()}, + node_color=[node_colors[node] for node in G.nodes()], linewidths=0.3, edgecolors='k') # draw labels for nodes - node_label_handles = nx.draw_networkx_labels(G, pos = node_label_pos, font_size = 14) + node_label_handles = nx.draw_networkx_labels(G, pos=node_label_pos, font_size=14) # add a white bounding box behind the node labels [label.set_bbox(dict(facecolor='white', edgecolor='none')) for label in node_label_handles.values()] # add edge lables to the graph - nx.draw_networkx_edge_labels(G, pos = node_positions, edge_labels = edge_weights, font_size = 14) + nx.draw_networkx_edge_labels(G, pos=node_positions, edge_labels=edge_weights, font_size=14) # add a legend white_circle = lines.Line2D([], [], color="white", marker='o', markersize=15, markerfacecolor="white") @@ -932,7 +932,7 @@ def show_map(graph_data, node_colors = None): green_circle = lines.Line2D([], [], color="green", marker='o', markersize=15, markerfacecolor="green") plt.legend((white_circle, orange_circle, red_circle, gray_circle, green_circle), ('Un-explored', 'Frontier', 'Currently Exploring', 'Explored', 'Final Solution'), - numpoints=1,prop={'size':16}, loc=(.8,.75)) + numpoints=1, prop={'size':16}, loc=(.8,.75)) # show the plot. No need to use in notebooks. nx.draw will show the graph itself. plt.show() @@ -940,7 +940,7 @@ def show_map(graph_data, node_colors = None): ## helper functions for visualisations def final_path_colors(initial_node_colors, problem, solution): - "returns a node_colors dict of the final path provided the problem and solution" + "Return a node_colors dict of the final path provided the problem and solution." # get initial node colors final_colors = dict(initial_node_colors) @@ -956,7 +956,7 @@ def display_visual(graph_data, user_input, algorithm=None, problem=None): def slider_callback(iteration): # don't show graph for the first time running the cell calling this function try: - show_map(graph_data, node_colors = all_node_colors[iteration]) + show_map(graph_data, node_colors=all_node_colors[iteration]) except: pass def visualize_callback(Visualize): @@ -976,26 +976,26 @@ def visualize_callback(Visualize): #time.sleep(.5) slider = widgets.IntSlider(min=0, max=1, step=1, value=0) - slider_visual = widgets.interactive(slider_callback, iteration = slider) + slider_visual = widgets.interactive(slider_callback, iteration=slider) display(slider_visual) - button = widgets.ToggleButton(value = False) - button_visual = widgets.interactive(visualize_callback, Visualize = button) + button = widgets.ToggleButton(value=False) + button_visual = widgets.interactive(visualize_callback, Visualize=button) display(button_visual) if user_input == True: node_colors = dict(initial_node_colors) if isinstance(algorithm, dict): - assert set(algorithm.keys()).issubset(set(["Breadth First Tree Search", + assert set(algorithm.keys()).issubset({"Breadth First Tree Search", "Depth First Tree Search", "Breadth First Search", "Depth First Graph Search", "Uniform Cost Search", - "A-star Search"])) + "A-star Search"}) - algo_dropdown = widgets.Dropdown(description = "Search algorithm: ", - options = sorted(list(algorithm.keys())), - value = "Breadth First Tree Search") + algo_dropdown = widgets.Dropdown(description="Search algorithm: ", + options=sorted(list(algorithm.keys())), + value="Breadth First Tree Search") display(algo_dropdown) elif algorithm is None: print("No algorithm to run.") @@ -1004,7 +1004,7 @@ def visualize_callback(Visualize): def slider_callback(iteration): # don't show graph for the first time running the cell calling this function try: - show_map(graph_data, node_colors = all_node_colors[iteration]) + show_map(graph_data, node_colors=all_node_colors[iteration]) except: pass @@ -1027,18 +1027,18 @@ def visualize_callback(Visualize): slider.value = i #time.sleep(.5) - start_dropdown = widgets.Dropdown(description = "Start city: ", - options = sorted(list(node_colors.keys())), value = "Arad") + start_dropdown = widgets.Dropdown(description="Start city: ", + options=sorted(list(node_colors.keys())), value="Arad") display(start_dropdown) - end_dropdown = widgets.Dropdown(description = "Goal city: ", - options = sorted(list(node_colors.keys())), value = "Fagaras") + end_dropdown = widgets.Dropdown(description="Goal city: ", + options=sorted(list(node_colors.keys())), value="Fagaras") display(end_dropdown) - button = widgets.ToggleButton(value = False) - button_visual = widgets.interactive(visualize_callback, Visualize = button) + button = widgets.ToggleButton(value=False) + button_visual = widgets.interactive(visualize_callback, Visualize=button) display(button_visual) slider = widgets.IntSlider(min=0, max=1, step=1, value=0) - slider_visual = widgets.interactive(slider_callback, iteration = slider) + slider_visual = widgets.interactive(slider_callback, iteration=slider) display(slider_visual) \ No newline at end of file diff --git a/planning.py b/planning.py index e31c8b3a3..95d7655d1 100644 --- a/planning.py +++ b/planning.py @@ -276,8 +276,8 @@ def find_mutex(self): if negeff in self.next_state_links_neg: for a in self.next_state_links_pos[poseff]: for b in self.next_state_links_neg[negeff]: - if set([a, b]) not in self.mutex: - self.mutex.append(set([a, b])) + if {a, b} not in self.mutex: + self.mutex.append({a, b}) # Interference for posprecond in self.current_state_links_pos: @@ -285,16 +285,16 @@ def find_mutex(self): if negeff in self.next_state_links_neg: for a in self.current_state_links_pos[posprecond]: for b in self.next_state_links_neg[negeff]: - if set([a, b]) not in self.mutex: - self.mutex.append(set([a, b])) + if {a, b} not in self.mutex: + self.mutex.append({a, b}) for negprecond in self.current_state_links_neg: poseff = negprecond if poseff in self.next_state_links_pos: for a in self.next_state_links_pos[poseff]: for b in self.current_state_links_neg[negprecond]: - if set([a, b]) not in self.mutex: - self.mutex.append(set([a, b])) + if {a, b} not in self.mutex: + self.mutex.append({a, b}) # Competing needs for posprecond in self.current_state_links_pos: @@ -302,8 +302,8 @@ def find_mutex(self): if negprecond in self.current_state_links_neg: for a in self.current_state_links_pos[posprecond]: for b in self.current_state_links_neg[negprecond]: - if set([a, b]) not in self.mutex: - self.mutex.append(set([a, b])) + if {a, b} not in self.mutex: + self.mutex.append({a, b}) # Inconsistent support state_mutex = [] @@ -314,7 +314,7 @@ def find_mutex(self): else: next_state_1 = self.next_action_links[list(pair)[0]] if (len(next_state_0) == 1) and (len(next_state_1) == 1): - state_mutex.append(set([next_state_0[0], next_state_1[0]])) + state_mutex.append({next_state_0[0], next_state_1[0]}) self.mutex = self.mutex+state_mutex @@ -565,18 +565,20 @@ class HLA(Action): """ unique_group = 1 - def __init__(self, action, precond=[None, None], effect=[None, None], duration=0, - consume={}, use={}): + def __init__(self, action, precond=None, effect=None, duration=0, + consume=None, use=None): """ As opposed to actions, to define HLA, we have added constraints. duration holds the amount of time required to execute the task consumes holds a dictionary representing the resources the task consumes uses holds a dictionary representing the resources the task uses """ + precond = precond or [None, None] + effect = effect or [None, None] super().__init__(action, precond, effect) self.duration = duration - self.consumes = consume - self.uses = use + self.consumes = consume or {} + self.uses = use or {} self.completed = False # self.priority = -1 # must be assigned in relation to other HLAs # self.job_group = -1 # must be assigned in relation to other HLAs @@ -644,10 +646,10 @@ class Problem(PDDL): This class is identical to PDLL, except that it overloads the act function to handle resource and ordering conditions imposed by HLA as opposed to Action. """ - def __init__(self, initial_state, actions, goal_test, jobs=None, resources={}): + def __init__(self, initial_state, actions, goal_test, jobs=None, resources=None): super().__init__(initial_state, actions, goal_test) self.jobs = jobs - self.resources = resources + self.resources = resources or {} def act(self, action): """ diff --git a/probability.py b/probability.py index 9b732edd7..205ae426e 100644 --- a/probability.py +++ b/probability.py @@ -165,10 +165,11 @@ def enumerate_joint(variables, e, P): class BayesNet: """Bayesian network containing only boolean-variable nodes.""" - def __init__(self, node_specs=[]): + def __init__(self, node_specs=None): """Nodes must be ordered with parents before children.""" self.nodes = [] self.variables = [] + node_specs = node_specs or [] for node_spec in node_specs: self.add(node_spec) @@ -526,10 +527,10 @@ def markov_blanket_sample(X, e, bn): class HiddenMarkovModel: """A Hidden markov model which takes Transition model and Sensor model as inputs""" - def __init__(self, transition_model, sensor_model, prior=[0.5, 0.5]): + def __init__(self, transition_model, sensor_model, prior=None): self.transition_model = transition_model self.sensor_model = sensor_model - self.prior = prior + self.prior = prior or [0.5, 0.5] def sensor_dist(self, ev): if ev is True: @@ -561,10 +562,10 @@ def forward_backward(HMM, ev, prior): t = len(ev) ev.insert(0, None) # to make the code look similar to pseudo code - fv = [[0.0, 0.0] for i in range(len(ev))] + fv = [[0.0, 0.0] for _ in range(len(ev))] b = [1.0, 1.0] bv = [b] # we don't need bv; but we will have a list of all backward messages here - sv = [[0, 0] for i in range(len(ev))] + sv = [[0, 0] for _ in range(len(ev))] fv[0] = prior diff --git a/rl.py b/rl.py index 1b7e20c33..9f9c90676 100644 --- a/rl.py +++ b/rl.py @@ -71,13 +71,13 @@ class ModelMDP(MDP): """ Class for implementing modified Version of input MDP with an editable transition model P and a custom function T. """ def __init__(self, init, actlist, terminals, gamma, states): - super().__init__(init, actlist, terminals, states = states, gamma = gamma) + super().__init__(init, actlist, terminals, states=states, gamma=gamma) nested_dict = lambda: defaultdict(nested_dict) # StackOverflow:whats-the-best-way-to-initialize-a-dict-of-dicts-in-python self.P = nested_dict() def T(self, s, a): - """Returns a list of tuples with probabilities for states + """Return a list of tuples with probabilities for states based on the learnt model P.""" return [(prob, res) for (res, prob) in self.P[(s, a)].items()] @@ -120,8 +120,8 @@ def __call__(self, percept): return self.a def update_state(self, percept): - '''To be overridden in most cases. The default case - assumes the percept to be of type (state, reward)''' + """To be overridden in most cases. The default case + assumes the percept to be of type (state, reward).""" return percept @@ -146,7 +146,7 @@ def __init__(self, pi, mdp, alpha=None): if alpha: self.alpha = alpha else: - self.alpha = lambda n: 1./(1+n) # udacity video + self.alpha = lambda n: 1/(1+n) # udacity video def __call__(self, percept): s1, r1 = self.update_state(percept) @@ -164,8 +164,8 @@ def __call__(self, percept): return self.a def update_state(self, percept): - ''' To be overridden in most cases. The default case - assumes the percept to be of type (state, reward)''' + """To be overridden in most cases. The default case + assumes the percept to be of type (state, reward).""" return percept @@ -202,7 +202,7 @@ def f(self, u, n): return u def actions_in_state(self, state): - """ Returns actions possible in given state. + """ Return actions possible in given state. Useful for max and argmax. """ if state in self.terminals: return [None] @@ -229,21 +229,21 @@ def __call__(self, percept): return self.a def update_state(self, percept): - ''' To be overridden in most cases. The default case - assumes the percept to be of type (state, reward)''' + """To be overridden in most cases. The default case + assumes the percept to be of type (state, reward).""" return percept def run_single_trial(agent_program, mdp): - ''' Execute trial for given agent_program + """Execute trial for given agent_program and mdp. mdp should be an instance of subclass - of mdp.MDP ''' + of mdp.MDP """ def take_single_action(mdp, s, a): - ''' - Selects outcome of taking action a + """ + Select outcome of taking action a in state s. Weighted Sampling. - ''' + """ x = random.uniform(0, 1) cumulative_probability = 0.0 for probability_state in mdp.T(s, a): diff --git a/text.py b/text.py index 8dc0ab855..b6beb28ca 100644 --- a/text.py +++ b/text.py @@ -37,19 +37,19 @@ class NgramWordModel(CountingProbDist): You can add, sample or get P[(word1, ..., wordn)]. The method P.samples(n) builds up an n-word sequence; P.add_cond_prob and P.add_sequence add data.""" - def __init__(self, n, observation_sequence=[], default=0): + def __init__(self, n, observation_sequence=None, default=0): # In addition to the dictionary of n-tuples, cond_prob is a # mapping from (w1, ..., wn-1) to P(wn | w1, ... wn-1) CountingProbDist.__init__(self, default=default) self.n = n self.cond_prob = defaultdict() - self.add_sequence(observation_sequence) + self.add_sequence(observation_sequence or []) # __getitem__, top, sample inherited from CountingProbDist # Note that they deal with tuples, not strings, as inputs def add_cond_prob(self, ngram): - """Builds the conditional probabilities P(wn | (w1, ..., wn-1)""" + """Build the conditional probabilities P(wn | (w1, ..., wn-1)""" if ngram[:-1] not in self.cond_prob: self.cond_prob[ngram[:-1]] = CountingProbDist() self.cond_prob[ngram[:-1]].add(ngram[-1]) @@ -88,14 +88,16 @@ def add_sequence(self, words): class UnigramCharModel(NgramCharModel): - def __init__(self, observation_sequence=[], default=0): + def __init__(self, observation_sequence=None, default=0): CountingProbDist.__init__(self, default=default) self.n = 1 self.cond_prob = defaultdict() - self.add_sequence(observation_sequence) + self.add_sequence(observation_sequence or []) def add_sequence(self, words): - [self.add(char) for word in words for char in list(word)] + for word in words: + for char in word: + self.add(char) # ______________________________________________________________________________ @@ -368,9 +370,9 @@ def decode(self, ciphertext): """Search for a decoding of the ciphertext.""" self.ciphertext = canonicalize(ciphertext) # reduce domain to speed up search - self.chardomain = {c for c in self.ciphertext if c is not ' '} + self.chardomain = {c for c in self.ciphertext if c != ' '} problem = PermutationDecoderProblem(decoder=self) - solution = search.best_first_graph_search( + solution = search.best_first_graph_search( problem, lambda node: self.score(node.state)) solution.state[' '] = ' ' @@ -388,9 +390,9 @@ def score(self, code): # add small positive value to prevent computing log(0) # TODO: Modify the values to make score more accurate - logP = (sum([log(self.Pwords[word] + 1e-20) for word in words(text)]) + - sum([log(self.P1[c] + 1e-5) for c in text]) + - sum([log(self.P2[b] + 1e-10) for b in bigrams(text)])) + logP = (sum(log(self.Pwords[word] + 1e-20) for word in words(text)) + + sum(log(self.P1[c] + 1e-5) for c in text) + + sum(log(self.P2[b] + 1e-10) for b in bigrams(text))) return -exp(logP) diff --git a/zp b/zp deleted file mode 100644 index e69de29bb..000000000 From dd4b944100974595b3ae0aab7b5899a3b3b7329b Mon Sep 17 00:00:00 2001 From: Rahul Goswami Date: Tue, 13 Mar 2018 20:29:47 +0530 Subject: [PATCH 5/5] minor fix and cleared change in agents.ipynb --- agents.ipynb | 48 ++++++++++++++++++++++++------------------------ knowledge.py | 1 + 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/agents.ipynb b/agents.ipynb index 8be4c2ae9..65878bbab 100644 --- a/agents.ipynb +++ b/agents.ipynb @@ -16,7 +16,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, "metadata": { "collapsed": true, "scrolled": true @@ -81,7 +81,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "metadata": { "collapsed": true }, @@ -738,7 +738,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -757,7 +757,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -776,7 +776,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -795,7 +795,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -814,7 +814,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -833,7 +833,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -852,7 +852,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -871,7 +871,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -890,7 +890,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -909,7 +909,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -928,7 +928,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -947,7 +947,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -966,7 +966,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -985,7 +985,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1004,7 +1004,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1023,7 +1023,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1042,7 +1042,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1061,7 +1061,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1080,7 +1080,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1099,7 +1099,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", @@ -1118,7 +1118,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" } ], "source": [ @@ -1211,7 +1211,7 @@ ] }, "metadata": {}, - "output_type": "execute_result" + "output_type": "display_data" }, { "name": "stdout", diff --git a/knowledge.py b/knowledge.py index 62edcd09c..2bb12f3b8 100644 --- a/knowledge.py +++ b/knowledge.py @@ -18,6 +18,7 @@ def current_best_learning(examples, h, examples_so_far=None): if not examples: return h + examples_so_far = examples_so_far or [] e = examples[0] if is_consistent(e, h): return current_best_learning(examples[1:], h, examples_so_far + [e])