Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixed some class definitions and typos #1131

Merged
merged 126 commits into from
Nov 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
126 commits
Select commit Hold shift + click to select a range
fe514c6
changed queue to set in AC3
dmeoli Mar 24, 2019
0129aa9
re-added test commented by mistake
dmeoli Mar 28, 2019
03551fb
added the mentioned AC4 algorithm for constraint propagation
dmeoli Apr 11, 2019
c0b8383
Merge branch 'master' into master
dmeoli Apr 11, 2019
6986247
added doctest in Sudoku for AC4 and and the possibility of choosing t…
dmeoli Apr 11, 2019
b3cd24c
removed useless doctest for AC4 in Sudoku because AC4's tests are alr…
dmeoli Apr 11, 2019
9e0fa55
added map coloring SAT problems
dmeoli Jun 17, 2019
f743146
fixed typo errors and removed unnecessary brackets
dmeoli Jun 17, 2019
20ab0e5
reformulated the map coloring problem
dmeoli Jul 4, 2019
404b179
Revert "reformulated the map coloring problem"
dmeoli Jul 4, 2019
c9c5106
Revert "fixed typo errors and removed unnecessary brackets"
dmeoli Jul 4, 2019
3243ba1
Revert "added map coloring SAT problems"
dmeoli Jul 4, 2019
2af1659
Revert "removed useless doctest for AC4 in Sudoku because AC4's tests…
dmeoli Jul 4, 2019
0c7e5af
Revert "added doctest in Sudoku for AC4 and and the possibility of ch…
dmeoli Jul 4, 2019
ff8c411
Revert "added the mentioned AC4 algorithm for constraint propagation"
dmeoli Jul 4, 2019
93af259
added map coloring SAT problem
dmeoli Jul 4, 2019
002a34e
Merge remote-tracking branch 'upstream/master'
dmeoli Jul 4, 2019
6641c2c
fixed build error
dmeoli Jul 4, 2019
9399dfc
Revert "added map coloring SAT problem"
dmeoli Jul 29, 2019
e130909
Revert "fixed build error"
dmeoli Jul 29, 2019
78bdeb1
Merge remote-tracking branch 'upstream/master'
dmeoli Jul 29, 2019
2f62776
added map coloring SAT problem
dmeoli Jul 29, 2019
aaea704
removed redundant parentheses
dmeoli Jul 29, 2019
0cd6386
Merge remote-tracking branch 'upstream/master'
dmeoli Aug 7, 2019
be656aa
added Viterbi algorithm
dmeoli Aug 14, 2019
c74933a
added monkey & bananas planning problem
dmeoli Aug 23, 2019
6d229ce
simplified condition in search.py
dmeoli Aug 23, 2019
24041e9
added tests for monkey & bananas planning problem
dmeoli Aug 23, 2019
9d37ae0
removed monkey & bananas planning problem
dmeoli Aug 23, 2019
459aae6
Revert "removed monkey & bananas planning problem"
dmeoli Aug 23, 2019
dbfb9c1
Revert "added tests for monkey & bananas planning problem"
dmeoli Aug 23, 2019
14d9014
Revert "simplified condition in search.py"
dmeoli Aug 23, 2019
5eb29cd
Revert "added monkey & bananas planning problem"
dmeoli Aug 23, 2019
396c38b
Merge remote-tracking branch 'upstream/master'
dmeoli Aug 23, 2019
776c131
defined the PlanningProblem as a specialization of a search.Problem &…
dmeoli Aug 27, 2019
ccc7de1
fixed doctest in logic.py
dmeoli Aug 27, 2019
7e98afb
fixed doctest for cascade_distribution
dmeoli Aug 27, 2019
061cba1
added ForwardPlanner and tests
dmeoli Aug 30, 2019
8c10d9f
added __lt__ implementation for Expr
dmeoli Aug 30, 2019
aa61869
added more tests
dmeoli Aug 30, 2019
c4139e5
renamed forward planner
dmeoli Aug 31, 2019
e4c4343
Revert "renamed forward planner"
dmeoli Aug 31, 2019
6e084c0
renamed forward planner class & added doc
dmeoli Aug 31, 2019
b6a0cbd
added backward planner and tests
dmeoli Sep 2, 2019
1131f4d
Merge remote-tracking branch 'upstream/master'
dmeoli Sep 3, 2019
1af8978
fixed mdp4e.py doctests
dmeoli Sep 3, 2019
a4ad133
removed ignore_delete_lists_heuristic flag
dmeoli Sep 3, 2019
26f2b5d
fixed heuristic for forward and backward planners
dmeoli Sep 6, 2019
9faf17a
added SATPlan and tests
dmeoli Sep 6, 2019
0be0f5d
fixed ignore delete lists heuristic in forward and backward planners
dmeoli Sep 7, 2019
2cc2d3f
fixed backward planner and added tests
dmeoli Sep 8, 2019
4222176
updated doc
dmeoli Sep 8, 2019
30af352
Merge remote-tracking branch 'upstream/master'
dmeoli Sep 11, 2019
b69a907
added nary csp definition and examples
dmeoli Sep 11, 2019
6ff465a
added CSPlan and tests
dmeoli Sep 11, 2019
d3c291c
fixed CSPlan
dmeoli Sep 11, 2019
785850a
added book's cryptarithmetic puzzle example
dmeoli Sep 11, 2019
7249058
fixed typo errors in test_csp
dmeoli Sep 11, 2019
42e9cbc
fixed #1111
dmeoli Sep 12, 2019
0fb48f6
added sortedcontainers to yml and doc to CSPlan
dmeoli Sep 12, 2019
5cce7d9
added tests for n-ary csp
dmeoli Sep 13, 2019
b567a6d
fixed utils.extend
dmeoli Sep 13, 2019
2eba772
updated test_probability.py
dmeoli Sep 14, 2019
427e85a
converted static methods to functions
dmeoli Sep 15, 2019
cd1ad41
added AC3b and AC4 with heuristic and tests
dmeoli Sep 15, 2019
0092f27
Merge remote-tracking branch 'upstream/master'
dmeoli Sep 16, 2019
d9dd4bb
added conflict-driven clause learning sat solver
dmeoli Sep 16, 2019
c0220d2
added tests for cdcl and heuristics
dmeoli Sep 16, 2019
8f0779d
fixed probability.py
dmeoli Sep 17, 2019
7a59010
fixed import
dmeoli Sep 17, 2019
0135db6
fixed kakuro
dmeoli Sep 20, 2019
ac98bd8
Merge remote-tracking branch 'upstream/master'
dmeoli Sep 21, 2019
dca70da
added Martelli and Montanari rule-based unification algorithm
dmeoli Sep 25, 2019
84e7a55
removed duplicate standardize_variables
dmeoli Sep 25, 2019
20bc37b
renamed variables known as built-in functions
dmeoli Sep 26, 2019
4b02d92
fixed typos in learning.py
dmeoli Sep 26, 2019
8427b5f
renamed some files and fixed typos
dmeoli Sep 26, 2019
3ffe3e9
fixed typos
dmeoli Sep 26, 2019
2d0dbc2
fixed typos
dmeoli Sep 27, 2019
b7e8206
fixed tests
dmeoli Sep 27, 2019
0c5f0ac
removed unify_mm
dmeoli Sep 29, 2019
bcc169d
remove unnecessary brackets
dmeoli Sep 29, 2019
9dd097b
fixed tests
dmeoli Sep 29, 2019
abc8f17
moved utility functions to utils.py
dmeoli Sep 29, 2019
9839d14
Merge remote-tracking branch 'upstream/master'
dmeoli Sep 29, 2019
50e036f
fixed typos
dmeoli Oct 1, 2019
44e1f9c
moved utils function to utils.py, separated probability learning clas…
dmeoli Oct 3, 2019
17285cc
added missing learners
dmeoli Oct 3, 2019
d80fed5
fixed Travis build
dmeoli Oct 3, 2019
a734d46
fixed typos
dmeoli Oct 3, 2019
df16744
fixed typos
dmeoli Oct 3, 2019
c81425f
fixed typos
dmeoli Oct 3, 2019
0071746
fixed typos
dmeoli Oct 4, 2019
25ac7b3
Merge branch 'master' into master
dmeoli Oct 4, 2019
f4f8663
fixed typos in agents files
dmeoli Oct 4, 2019
dd8ae31
fixed imports in agent files
dmeoli Oct 4, 2019
13000ac
Merge branch 'ml'
dmeoli Oct 4, 2019
b11adf4
Merge remote-tracking branch 'upstream/master'
dmeoli Oct 7, 2019
e041479
fixed deep learning .ipynb imports
dmeoli Oct 8, 2019
be7c131
fixed typos
dmeoli Oct 8, 2019
8bede28
Merge remote-tracking branch 'upstream/master'
dmeoli Oct 8, 2019
e0b4a1c
Merge remote-tracking branch 'upstream/master'
dmeoli Oct 24, 2019
99c1b4c
Merge remote-tracking branch 'upstream/master'
dmeoli Oct 29, 2019
b9236db
added .ipynb and fixed typos
dmeoli Nov 1, 2019
3001803
adapted code for .ipynb
dmeoli Nov 1, 2019
e5f75f3
fixed typos
dmeoli Nov 1, 2019
278574d
updated .ipynb
dmeoli Nov 1, 2019
25c590d
updated .ipynb
dmeoli Nov 1, 2019
23e3d95
updated logic.py
dmeoli Nov 1, 2019
aa79be3
updated .ipynb
dmeoli Nov 1, 2019
42a6d4a
updated .ipynb
dmeoli Nov 1, 2019
ce3d0c6
updated planning.py
dmeoli Nov 1, 2019
8f5ef83
updated inf definition
dmeoli Nov 1, 2019
9d27673
fixed typos
dmeoli Nov 2, 2019
181d257
fixed typos
dmeoli Nov 2, 2019
08ad660
fixed typos
dmeoli Nov 2, 2019
658309d
fixed typos
dmeoli Nov 2, 2019
35fc24d
Revert "fixed typos"
dmeoli Nov 2, 2019
ecc7c2d
Revert "fixed typos"
dmeoli Nov 2, 2019
dbbe897
fixed typos
dmeoli Nov 2, 2019
8ef5e0c
fixed typos
dmeoli Nov 2, 2019
cf95e44
fixed typos
dmeoli Nov 2, 2019
0d64274
fixed typos
dmeoli Nov 2, 2019
29644d4
fixed typos and utils imports in *4e.py files
dmeoli Nov 2, 2019
1c68b8a
Merge remote-tracking branch 'upstream/master'
dmeoli Nov 3, 2019
1654a9c
fixed typos
dmeoli Nov 3, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 17 additions & 19 deletions csp.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
"""CSP (Constraint Satisfaction Problems) problems and solvers. (Chapter 6)"""

import itertools
import random
import re
import string
from collections import defaultdict, Counter
from functools import reduce
from operator import eq, neg

from sortedcontainers import SortedSet

from utils import argmin_random_tie, count, first, extend
import search

from collections import defaultdict, Counter
from functools import reduce

import itertools
import re
import random
from utils import argmin_random_tie, count, first, extend


class CSP(search.Problem):
Expand Down Expand Up @@ -54,12 +53,12 @@ class CSP(search.Problem):

def __init__(self, variables, domains, neighbors, constraints):
"""Construct a CSP problem. If variables is empty, it becomes domains.keys()."""
super().__init__(())
variables = variables or list(domains.keys())
self.variables = variables
self.domains = domains
self.neighbors = neighbors
self.constraints = constraints
self.initial = ()
self.curr_domains = None
self.nassigns = 0

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

# Subclasses may implement this more efficiently
def conflict(var2):
return (var2 in assignment and
not self.constraints(var, val, var2, assignment[var2]))
return var2 in assignment and not self.constraints(var, val, var2, assignment[var2])

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

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


# ______________________________________________________________________________
# Map Coloring Problems
# Map Coloring CSP Problems


class UniversalDict:
Expand Down Expand Up @@ -585,7 +583,7 @@ def MapColoringCSP(colors, neighbors):
return CSP(list(neighbors.keys()), UniversalDict(colors), neighbors, different_values_constraint)


def parse_neighbors(neighbors, variables=None):
def parse_neighbors(neighbors):
"""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
Expand Down Expand Up @@ -676,10 +674,10 @@ def nconflicts(self, var, val, assignment):

def assign(self, var, val, assignment):
"""Assign var, and keep track of conflicts."""
oldval = assignment.get(var, None)
if val != oldval:
if oldval is not None: # Remove old val if there was one
self.record_conflict(assignment, var, oldval, -1)
old_val = assignment.get(var, None)
if val != old_val:
if old_val is not None: # Remove old val if there was one
self.record_conflict(assignment, var, old_val, -1)
self.record_conflict(assignment, var, val, +1)
CSP.assign(self, var, val, assignment)

Expand Down Expand Up @@ -776,7 +774,7 @@ class Sudoku(CSP):
>>> h = Sudoku(harder1)
>>> backtracking_search(h, select_unassigned_variable=mrv, inference=forward_checking) is not None
True
""" # noqa
"""

R3 = _R3
Cell = _CELL
Expand Down Expand Up @@ -831,7 +829,7 @@ def Zebra():
Spaniard: Dog; Kools: Yellow; Chesterfields: Fox;
Norwegian: Blue; Winston: Snails; LuckyStrike: OJ;
Ukranian: Tea; Japanese: Parliaments; Kools: Horse;
Coffee: Green; Green: Ivory""", variables)
Coffee: Green; Green: Ivory""")
for type in [Colors, Pets, Drinks, Countries, Smokes]:
for A in type:
for B in type:
Expand Down
2 changes: 1 addition & 1 deletion knowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ def extend_example(self, example, literal):

def new_literals(self, clause):
"""Generate new literals based on known predicate symbols.
Generated literal must share atleast one variable with clause"""
Generated literal must share at least one variable with clause"""
share_vars = variables(clause[0])
for l in clause[1]:
share_vars.update(variables(l))
Expand Down
19 changes: 10 additions & 9 deletions logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,10 @@
issequence, Expr, expr, subexpressions, extend)


# ______________________________________________________________________________


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

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


# ______________________________________________________________________________
# DPLL-Satisfiable [Figure 7.17]
# Heuristics for SAT Solvers


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


# ______________________________________________________________________________
# DPLL-Satisfiable [Figure 7.17]


def dpll_satisfiable(s, branching_heuristic=no_branching_heuristic):
"""Check satisfiability of a propositional sentence.
This differs from the book code in two ways: (1) it returns a model
Expand Down Expand Up @@ -1114,7 +1115,7 @@ def sat_count(sym):


# ______________________________________________________________________________
# Map Coloring Problems
# Map Coloring SAT Problems


def MapColoringSAT(colors, neighbors):
Expand Down Expand Up @@ -1803,7 +1804,7 @@ def cascade_substitution(s):
for x in s:
s[x] = subst(s, s.get(x))
if isinstance(s.get(x), Expr) and not is_variable(s.get(x)):
# Ensure Function Terms are correct updates by passing over them again.
# Ensure Function Terms are correct updates by passing over them again
s[x] = subst(s, s.get(x))


Expand Down Expand Up @@ -2055,7 +2056,7 @@ def fol_bc_and(kb, goals, theta):
# ______________________________________________________________________________

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


Expand Down
20 changes: 9 additions & 11 deletions making_simple_decision4e.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
from utils4e import (
argmax, element_wise_product, matrix_multiplication,
vector_to_diagonal, vector_add, scalar_vector_product, inverse_matrix,
weighted_sample_with_replacement, probability, normalize
)
import random

from agents import Agent
from probability import BayesNet
import random
from utils4e import argmax, vector_add, weighted_sample_with_replacement


# Making Simple Decisions (Chapter 15)

Expand Down Expand Up @@ -108,6 +106,7 @@ def vpi(self, variable):
class MCLmap:
"""Map which provides probability distributions and sensor readings.
Consists of discrete cells which are either an obstacle or empty"""

def __init__(self, m):
self.m = m
self.nrows = len(m)
Expand All @@ -131,7 +130,7 @@ def ray_cast(self, sensor_num, kin_state):
# 0
# 3R1
# 2
delta = ((sensor_num % 2 == 0)*(sensor_num - 1), (sensor_num % 2 == 1)*(2 - sensor_num))
delta = ((sensor_num % 2 == 0) * (sensor_num - 1), (sensor_num % 2 == 1) * (2 - sensor_num))
# sensor direction changes based on orientation
for _ in range(orient):
delta = (delta[1], -delta[0])
Expand All @@ -149,9 +148,9 @@ def ray_cast(sensor_num, kin_state, m):
return m.ray_cast(sensor_num, kin_state)

M = len(z)
W = [0]*N
S_ = [0]*N
W_ = [0]*N
W = [0] * N
S_ = [0] * N
W_ = [0] * N
v = a['v']
w = a['w']

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

S = weighted_sample_with_replacement(N, S_, W_)
return S

6 changes: 3 additions & 3 deletions planning.py
Original file line number Diff line number Diff line change
Expand Up @@ -1047,8 +1047,8 @@ def orderlevel(self, level, planning_problem):
def execute(self):
"""Finds total-order solution for a planning graph"""

graphplan_solution = GraphPlan(self.planning_problem).execute()
filtered_solution = self.filter(graphplan_solution)
graphPlan_solution = GraphPlan(self.planning_problem).execute()
filtered_solution = self.filter(graphPlan_solution)
ordered_solution = []
planning_problem = self.planning_problem
for level in filtered_solution:
Expand Down Expand Up @@ -1635,7 +1635,7 @@ def angelic_search(self, hierarchy, initial_plan):
if guaranteed and RealWorldPlanningProblem.making_progress(plan, initial_plan):
final_state = guaranteed[0] # any element of guaranteed
return RealWorldPlanningProblem.decompose(hierarchy, final_state, pes_reachable_set)
# there should be at least one HLA/Angelic_HLA, otherwise plan would be primitive
# there should be at least one HLA/AngelicHLA, otherwise plan would be primitive
hla, index = RealWorldPlanningProblem.find_hla(plan, hierarchy)
prefix = plan.action[:index]
suffix = plan.action[index + 1:]
Expand Down
22 changes: 11 additions & 11 deletions probability.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@
Probability models. (Chapter 13-15)
"""

from utils import (product, argmax, element_wise_product, matrix_multiplication, vector_to_diagonal, vector_add,
scalar_vector_product, inverse_matrix, weighted_sample_with_replacement, isclose, probability,
normalize, extend)
from agents import Agent

import random
from collections import defaultdict
from functools import reduce
import numpy as np

import numpy as np

# ______________________________________________________________________________
from agents import Agent
from utils import (product, argmax, element_wise_product, matrix_multiplication, vector_to_diagonal, vector_add,
scalar_vector_product, inverse_matrix, weighted_sample_with_replacement, isclose, probability,
normalize, extend)


def DTAgentProgram(belief_state):
Expand Down Expand Up @@ -106,7 +104,7 @@ def __getitem__(self, values):
return ProbDist.__getitem__(self, values)

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

def __init__(self, X, parents, cpt):
"""X is a variable name, and parents a sequence of variable
names or a space-separated string. cpt, the conditional
names or a space-separated string. cpt, the conditional
probability table, takes one of these forms:

* A number, the unconditional probability P(X=true). You can
Expand Down Expand Up @@ -541,8 +539,10 @@ def prior_sample(bn):


def rejection_sampling(X, e, bn, N=10000):
"""Estimate the probability distribution of variable X given
evidence e in BayesNet bn, using N samples. [Figure 14.14]
"""
[Figure 14.14]
Estimate the probability distribution of variable X given
evidence e in BayesNet bn, using N samples.
Raises a ZeroDivisionError if all the N samples are rejected,
i.e., inconsistent with e.
>>> random.seed(47)
Expand Down
13 changes: 8 additions & 5 deletions probability4e.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
"""Probability models."""

from utils4e import product, argmax, isclose, probability, extend
from math import sqrt, pi, exp
import copy
import random
from collections import defaultdict
from functools import reduce
from math import sqrt, pi, exp

from utils4e import product, argmax, isclose, probability, extend


# ______________________________________________________________________________
Expand Down Expand Up @@ -107,7 +108,7 @@ def __getitem__(self, values):
return ProbDist.__getitem__(self, values)

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

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

def likelihood_weighting(X, e, bn, N=10000):
"""
[Figure 13.17]
Estimate the probability distribution of variable X given
evidence e in BayesNet bn. [Figure 13.17]
evidence e in BayesNet bn.
>>> random.seed(1017)
>>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T),
... burglary, 10000).show_approx()
Expand Down
Loading