Skip to content

Commit 04fa465

Browse files
dmeoliantmarakis
authored andcommitted
fixed some class definitions and typos (#1131)
* changed queue to set in AC3 Changed queue to set in AC3 (as in the pseudocode of the original algorithm) to reduce the number of consistency-check due to the redundancy of the same arcs in queue. For example, on the harder1 configuration of the Sudoku CSP the number consistency-check has been reduced from 40464 to 12562! * re-added test commented by mistake * added the mentioned AC4 algorithm for constraint propagation AC3 algorithm has non-optimal worst case time-complexity O(cd^3 ), while AC4 algorithm runs in O(cd^2) worst case time * added doctest in Sudoku for AC4 and and the possibility of choosing the constant propagation algorithm in mac inference * removed useless doctest for AC4 in Sudoku because AC4's tests are already present in test_csp.py * added map coloring SAT problems * fixed typo errors and removed unnecessary brackets * reformulated the map coloring problem * Revert "reformulated the map coloring problem" This reverts commit 20ab0e5. * Revert "fixed typo errors and removed unnecessary brackets" This reverts commit f743146. * Revert "added map coloring SAT problems" This reverts commit 9e0fa55. * Revert "removed useless doctest for AC4 in Sudoku because AC4's tests are already present in test_csp.py" This reverts commit b3cd24c. * Revert "added doctest in Sudoku for AC4 and and the possibility of choosing the constant propagation algorithm in mac inference" This reverts commit 6986247. * Revert "added the mentioned AC4 algorithm for constraint propagation" This reverts commit 03551fb. * added map coloring SAT problem * fixed build error * Revert "added map coloring SAT problem" This reverts commit 93af259. * Revert "fixed build error" This reverts commit 6641c2c. * added map coloring SAT problem * removed redundant parentheses * added Viterbi algorithm * added monkey & bananas planning problem * simplified condition in search.py * added tests for monkey & bananas planning problem * removed monkey & bananas planning problem * Revert "removed monkey & bananas planning problem" This reverts commit 9d37ae0. * Revert "added tests for monkey & bananas planning problem" This reverts commit 24041e9. * Revert "simplified condition in search.py" This reverts commit 6d229ce. * Revert "added monkey & bananas planning problem" This reverts commit c74933a. * defined the PlanningProblem as a specialization of a search.Problem & fixed typo errors * fixed doctest in logic.py * fixed doctest for cascade_distribution * added ForwardPlanner and tests * added __lt__ implementation for Expr * added more tests * renamed forward planner * Revert "renamed forward planner" This reverts commit c4139e5. * renamed forward planner class & added doc * added backward planner and tests * fixed mdp4e.py doctests * removed ignore_delete_lists_heuristic flag * fixed heuristic for forward and backward planners * added SATPlan and tests * fixed ignore delete lists heuristic in forward and backward planners * fixed backward planner and added tests * updated doc * added nary csp definition and examples * added CSPlan and tests * fixed CSPlan * added book's cryptarithmetic puzzle example * fixed typo errors in test_csp * fixed #1111 * added sortedcontainers to yml and doc to CSPlan * added tests for n-ary csp * fixed utils.extend * updated test_probability.py * converted static methods to functions * added AC3b and AC4 with heuristic and tests * added conflict-driven clause learning sat solver * added tests for cdcl and heuristics * fixed probability.py * fixed import * fixed kakuro * added Martelli and Montanari rule-based unification algorithm * removed duplicate standardize_variables * renamed variables known as built-in functions * fixed typos in learning.py * renamed some files and fixed typos * fixed typos * fixed typos * fixed tests * removed unify_mm * remove unnecessary brackets * fixed tests * moved utility functions to utils.py * fixed typos * moved utils function to utils.py, separated probability learning classes from learning.py, fixed typos and fixed imports in .ipynb files * added missing learners * fixed Travis build * fixed typos * fixed typos * fixed typos * fixed typos * fixed typos in agents files * fixed imports in agent files * fixed deep learning .ipynb imports * fixed typos * added .ipynb and fixed typos * adapted code for .ipynb * fixed typos * updated .ipynb * updated .ipynb * updated logic.py * updated .ipynb * updated .ipynb * updated planning.py * updated inf definition * fixed typos * fixed typos * fixed typos * fixed typos * Revert "fixed typos" This reverts commit 658309d. * Revert "fixed typos" This reverts commit 08ad660. * fixed typos * fixed typos * fixed typos * fixed typos * fixed typos and utils imports in *4e.py files * fixed typos
1 parent 5d3a95c commit 04fa465

14 files changed

+178
-188
lines changed

csp.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,17 @@
11
"""CSP (Constraint Satisfaction Problems) problems and solvers. (Chapter 6)"""
2+
3+
import itertools
4+
import random
5+
import re
26
import string
7+
from collections import defaultdict, Counter
8+
from functools import reduce
39
from operator import eq, neg
410

511
from sortedcontainers import SortedSet
612

7-
from utils import argmin_random_tie, count, first, extend
813
import search
9-
10-
from collections import defaultdict, Counter
11-
from functools import reduce
12-
13-
import itertools
14-
import re
15-
import random
14+
from utils import argmin_random_tie, count, first, extend
1615

1716

1817
class CSP(search.Problem):
@@ -54,12 +53,12 @@ class CSP(search.Problem):
5453

5554
def __init__(self, variables, domains, neighbors, constraints):
5655
"""Construct a CSP problem. If variables is empty, it becomes domains.keys()."""
56+
super().__init__(())
5757
variables = variables or list(domains.keys())
5858
self.variables = variables
5959
self.domains = domains
6060
self.neighbors = neighbors
6161
self.constraints = constraints
62-
self.initial = ()
6362
self.curr_domains = None
6463
self.nassigns = 0
6564

@@ -80,8 +79,7 @@ def nconflicts(self, var, val, assignment):
8079

8180
# Subclasses may implement this more efficiently
8281
def conflict(var2):
83-
return (var2 in assignment and
84-
not self.constraints(var, val, var2, assignment[var2]))
82+
return var2 in assignment and not self.constraints(var, val, var2, assignment[var2])
8583

8684
return count(conflict(v) for v in self.neighbors[var])
8785

@@ -552,7 +550,7 @@ def assign_value(Xj, Xk, csp, assignment):
552550

553551

554552
# ______________________________________________________________________________
555-
# Map Coloring Problems
553+
# Map Coloring CSP Problems
556554

557555

558556
class UniversalDict:
@@ -585,7 +583,7 @@ def MapColoringCSP(colors, neighbors):
585583
return CSP(list(neighbors.keys()), UniversalDict(colors), neighbors, different_values_constraint)
586584

587585

588-
def parse_neighbors(neighbors, variables=None):
586+
def parse_neighbors(neighbors):
589587
"""Convert a string of the form 'X: Y Z; Y: Z' into a dict mapping
590588
regions to neighbors. The syntax is a region name followed by a ':'
591589
followed by zero or more region names, followed by ';', repeated for
@@ -676,10 +674,10 @@ def nconflicts(self, var, val, assignment):
676674

677675
def assign(self, var, val, assignment):
678676
"""Assign var, and keep track of conflicts."""
679-
oldval = assignment.get(var, None)
680-
if val != oldval:
681-
if oldval is not None: # Remove old val if there was one
682-
self.record_conflict(assignment, var, oldval, -1)
677+
old_val = assignment.get(var, None)
678+
if val != old_val:
679+
if old_val is not None: # Remove old val if there was one
680+
self.record_conflict(assignment, var, old_val, -1)
683681
self.record_conflict(assignment, var, val, +1)
684682
CSP.assign(self, var, val, assignment)
685683

@@ -776,7 +774,7 @@ class Sudoku(CSP):
776774
>>> h = Sudoku(harder1)
777775
>>> backtracking_search(h, select_unassigned_variable=mrv, inference=forward_checking) is not None
778776
True
779-
""" # noqa
777+
"""
780778

781779
R3 = _R3
782780
Cell = _CELL
@@ -831,7 +829,7 @@ def Zebra():
831829
Spaniard: Dog; Kools: Yellow; Chesterfields: Fox;
832830
Norwegian: Blue; Winston: Snails; LuckyStrike: OJ;
833831
Ukranian: Tea; Japanese: Parliaments; Kools: Horse;
834-
Coffee: Green; Green: Ivory""", variables)
832+
Coffee: Green; Green: Ivory""")
835833
for type in [Colors, Pets, Drinks, Countries, Smokes]:
836834
for A in type:
837835
for B in type:

knowledge.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ def extend_example(self, example, literal):
300300

301301
def new_literals(self, clause):
302302
"""Generate new literals based on known predicate symbols.
303-
Generated literal must share atleast one variable with clause"""
303+
Generated literal must share at least one variable with clause"""
304304
share_vars = variables(clause[0])
305305
for l in clause[1]:
306306
share_vars.update(variables(l))

logic.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,10 @@
4646
issequence, Expr, expr, subexpressions, extend)
4747

4848

49-
# ______________________________________________________________________________
50-
51-
5249
class KB:
5350
"""A knowledge base to which you can tell and ask sentences.
5451
To create a KB, first subclass this class and implement
55-
tell, ask_generator, and retract. Why ask_generator instead of ask?
52+
tell, ask_generator, and retract. Why ask_generator instead of ask?
5653
The book is a bit vague on what ask means --
5754
For a Propositional Logic KB, ask(P & Q) returns True or False, but for an
5855
FOL KB, something like ask(Brother(x, y)) might return many substitutions
@@ -173,7 +170,7 @@ def variables(s):
173170

174171
def is_definite_clause(s):
175172
"""Returns True for exprs s of the form A & B & ... & C ==> D,
176-
where all literals are positive. In clause form, this is
173+
where all literals are positive. In clause form, this is
177174
~A | ~B | ... | ~C | D, where exactly one clause is positive.
178175
>>> is_definite_clause(expr('Farmer(Mac)'))
179176
True
@@ -602,7 +599,7 @@ def pl_fc_entails(kb, q):
602599

603600

604601
# ______________________________________________________________________________
605-
# DPLL-Satisfiable [Figure 7.17]
602+
# Heuristics for SAT Solvers
606603

607604

608605
def no_branching_heuristic(symbols, clauses):
@@ -707,6 +704,10 @@ def jw2(symbols, clauses):
707704
return P, True if scores[P] >= scores[~P] else False
708705

709706

707+
# ______________________________________________________________________________
708+
# DPLL-Satisfiable [Figure 7.17]
709+
710+
710711
def dpll_satisfiable(s, branching_heuristic=no_branching_heuristic):
711712
"""Check satisfiability of a propositional sentence.
712713
This differs from the book code in two ways: (1) it returns a model
@@ -1114,7 +1115,7 @@ def sat_count(sym):
11141115

11151116

11161117
# ______________________________________________________________________________
1117-
# Map Coloring Problems
1118+
# Map Coloring SAT Problems
11181119

11191120

11201121
def MapColoringSAT(colors, neighbors):
@@ -1803,7 +1804,7 @@ def cascade_substitution(s):
18031804
for x in s:
18041805
s[x] = subst(s, s.get(x))
18051806
if isinstance(s.get(x), Expr) and not is_variable(s.get(x)):
1806-
# Ensure Function Terms are correct updates by passing over them again.
1807+
# Ensure Function Terms are correct updates by passing over them again
18071808
s[x] = subst(s, s.get(x))
18081809

18091810

@@ -2055,7 +2056,7 @@ def fol_bc_and(kb, goals, theta):
20552056
# ______________________________________________________________________________
20562057

20572058
# Example application (not in the book).
2058-
# You can use the Expr class to do symbolic differentiation. This used to be
2059+
# You can use the Expr class to do symbolic differentiation. This used to be
20592060
# a part of AI; now it is considered a separate field, Symbolic Algebra.
20602061

20612062

making_simple_decision4e.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
from utils4e import (
2-
argmax, element_wise_product, matrix_multiplication,
3-
vector_to_diagonal, vector_add, scalar_vector_product, inverse_matrix,
4-
weighted_sample_with_replacement, probability, normalize
5-
)
1+
import random
2+
63
from agents import Agent
74
from probability import BayesNet
8-
import random
5+
from utils4e import argmax, vector_add, weighted_sample_with_replacement
6+
97

108
# Making Simple Decisions (Chapter 15)
119

@@ -108,6 +106,7 @@ def vpi(self, variable):
108106
class MCLmap:
109107
"""Map which provides probability distributions and sensor readings.
110108
Consists of discrete cells which are either an obstacle or empty"""
109+
111110
def __init__(self, m):
112111
self.m = m
113112
self.nrows = len(m)
@@ -131,7 +130,7 @@ def ray_cast(self, sensor_num, kin_state):
131130
# 0
132131
# 3R1
133132
# 2
134-
delta = ((sensor_num % 2 == 0)*(sensor_num - 1), (sensor_num % 2 == 1)*(2 - sensor_num))
133+
delta = ((sensor_num % 2 == 0) * (sensor_num - 1), (sensor_num % 2 == 1) * (2 - sensor_num))
135134
# sensor direction changes based on orientation
136135
for _ in range(orient):
137136
delta = (delta[1], -delta[0])
@@ -149,9 +148,9 @@ def ray_cast(sensor_num, kin_state, m):
149148
return m.ray_cast(sensor_num, kin_state)
150149

151150
M = len(z)
152-
W = [0]*N
153-
S_ = [0]*N
154-
W_ = [0]*N
151+
W = [0] * N
152+
S_ = [0] * N
153+
W_ = [0] * N
155154
v = a['v']
156155
w = a['w']
157156

@@ -167,4 +166,3 @@ def ray_cast(sensor_num, kin_state, m):
167166

168167
S = weighted_sample_with_replacement(N, S_, W_)
169168
return S
170-

planning.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1047,8 +1047,8 @@ def orderlevel(self, level, planning_problem):
10471047
def execute(self):
10481048
"""Finds total-order solution for a planning graph"""
10491049

1050-
graphplan_solution = GraphPlan(self.planning_problem).execute()
1051-
filtered_solution = self.filter(graphplan_solution)
1050+
graphPlan_solution = GraphPlan(self.planning_problem).execute()
1051+
filtered_solution = self.filter(graphPlan_solution)
10521052
ordered_solution = []
10531053
planning_problem = self.planning_problem
10541054
for level in filtered_solution:
@@ -1635,7 +1635,7 @@ def angelic_search(self, hierarchy, initial_plan):
16351635
if guaranteed and RealWorldPlanningProblem.making_progress(plan, initial_plan):
16361636
final_state = guaranteed[0] # any element of guaranteed
16371637
return RealWorldPlanningProblem.decompose(hierarchy, final_state, pes_reachable_set)
1638-
# there should be at least one HLA/Angelic_HLA, otherwise plan would be primitive
1638+
# there should be at least one HLA/AngelicHLA, otherwise plan would be primitive
16391639
hla, index = RealWorldPlanningProblem.find_hla(plan, hierarchy)
16401640
prefix = plan.action[:index]
16411641
suffix = plan.action[index + 1:]

probability.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,16 @@
22
Probability models. (Chapter 13-15)
33
"""
44

5-
from utils import (product, argmax, element_wise_product, matrix_multiplication, vector_to_diagonal, vector_add,
6-
scalar_vector_product, inverse_matrix, weighted_sample_with_replacement, isclose, probability,
7-
normalize, extend)
8-
from agents import Agent
9-
105
import random
116
from collections import defaultdict
127
from functools import reduce
13-
import numpy as np
148

9+
import numpy as np
1510

16-
# ______________________________________________________________________________
11+
from agents import Agent
12+
from utils import (product, argmax, element_wise_product, matrix_multiplication, vector_to_diagonal, vector_add,
13+
scalar_vector_product, inverse_matrix, weighted_sample_with_replacement, isclose, probability,
14+
normalize, extend)
1715

1816

1917
def DTAgentProgram(belief_state):
@@ -106,7 +104,7 @@ def __getitem__(self, values):
106104
return ProbDist.__getitem__(self, values)
107105

108106
def __setitem__(self, values, p):
109-
"""Set P(values) = p. Values can be a tuple or a dict; it must
107+
"""Set P(values) = p. Values can be a tuple or a dict; it must
110108
have a value for each of the variables in the joint. Also keep track
111109
of the values we have seen so far for each variable."""
112110
values = event_values(values, self.variables)
@@ -307,7 +305,7 @@ class BayesNode:
307305

308306
def __init__(self, X, parents, cpt):
309307
"""X is a variable name, and parents a sequence of variable
310-
names or a space-separated string. cpt, the conditional
308+
names or a space-separated string. cpt, the conditional
311309
probability table, takes one of these forms:
312310
313311
* A number, the unconditional probability P(X=true). You can
@@ -541,8 +539,10 @@ def prior_sample(bn):
541539

542540

543541
def rejection_sampling(X, e, bn, N=10000):
544-
"""Estimate the probability distribution of variable X given
545-
evidence e in BayesNet bn, using N samples. [Figure 14.14]
542+
"""
543+
[Figure 14.14]
544+
Estimate the probability distribution of variable X given
545+
evidence e in BayesNet bn, using N samples.
546546
Raises a ZeroDivisionError if all the N samples are rejected,
547547
i.e., inconsistent with e.
548548
>>> random.seed(47)

probability4e.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
"""Probability models."""
22

3-
from utils4e import product, argmax, isclose, probability, extend
4-
from math import sqrt, pi, exp
53
import copy
64
import random
75
from collections import defaultdict
86
from functools import reduce
7+
from math import sqrt, pi, exp
8+
9+
from utils4e import product, argmax, isclose, probability, extend
910

1011

1112
# ______________________________________________________________________________
@@ -107,7 +108,7 @@ def __getitem__(self, values):
107108
return ProbDist.__getitem__(self, values)
108109

109110
def __setitem__(self, values, p):
110-
"""Set P(values) = p. Values can be a tuple or a dict; it must
111+
"""Set P(values) = p. Values can be a tuple or a dict; it must
111112
have a value for each of the variables in the joint. Also keep track
112113
of the values we have seen so far for each variable."""
113114
values = event_values(values, self.variables)
@@ -628,8 +629,9 @@ def prior_sample(bn):
628629

629630
def rejection_sampling(X, e, bn, N=10000):
630631
"""
632+
[Figure 13.16]
631633
Estimate the probability distribution of variable X given
632-
evidence e in BayesNet bn, using N samples. [Figure 13.16]
634+
evidence e in BayesNet bn, using N samples.
633635
Raises a ZeroDivisionError if all the N samples are rejected,
634636
i.e., inconsistent with e.
635637
>>> random.seed(47)
@@ -656,8 +658,9 @@ def consistent_with(event, evidence):
656658

657659
def likelihood_weighting(X, e, bn, N=10000):
658660
"""
661+
[Figure 13.17]
659662
Estimate the probability distribution of variable X given
660-
evidence e in BayesNet bn. [Figure 13.17]
663+
evidence e in BayesNet bn.
661664
>>> random.seed(1017)
662665
>>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T),
663666
... burglary, 10000).show_approx()

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy