Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

1.

Logic Programming
Previously with AI, we have learned about Computer Vision, Today, we will see AI
with Python Logic Programming. We will learn how to match mathematical
expressions and how to check for and generate prime numbers. Also, we will see the
example of Python Logic Programming.
1. facts
2. Rules

2. What is Logic Programming in


Python?
Python Logic programming is a programming paradigm that sees computation as
automatic reasoning over a database of knowledge made of facts and rules. It is a way
of programming and is based on formal logic. A program in such a language is a set of
sentences, in logical form, one that expresses facts and rules about a problem domain.
Among others, Datalog is one such major logic programming language family.

a. Structure of Python Logic Programming


Let’s talk about facts and rules. Facts are true statements- say, Bucharest is the capital
of Romania. Rules are constraints that lead us to conclusions about the problem
domain. These are logical clauses that express facts. We use the following syntax to
write a rule (as a clause):
H :- B1, …, Bn.
We can read this as:
H if B1 and … and Bn.
Here, H is the head of the rule and B1, …, Bn is the body. A fact is a rule with no
body:
H.
An example would be:
Have a look at Python Computational Graphs
fallible(X) :- human(X)
Every logic program needs facts based on which to achieve the given goal. Rules are
constraints that get us to conclusions.
b. Logic and Control
Think of an algorithm as a combination of logic and control.
Algorithm=Logic+Control
In a pure logic programming language, the logic component gets to the solution alone.
We can, however, vary the control component for other ways to execute a logic
program.

3. Getting Started With Python Logic


Programming
Gearing up for logic programming with Python, we will install a couple of packages.
Let’s use pip for this.
 Kanren- It lets us express logic as rules and facts and simplifies making code
for business logic.
1. >>> pip install kanren

 SymPy- This is a Python library for symbolic mathematics. It is nearly a full-


featured Computer Algebra System.
1. >>> pip install sympy

4. Python Logic Programming Example

Representing Knowledge
kanren stores data as facts that state relationships between terms.

The following code creates a parent relationship and uses it to state facts about who is a
parent of whom within the Simpsons family.

>>>fromkanrenimport Relation, facts


>>>parent=Relation()
>>>facts(parent, ("Homer", "Bart"),
... ("Homer", "Lisa"),
... ("Abe", "Homer"))

>>>run(1, x, parent(x, "Bart"))


('Homer',)
>>>run(2, x, parent("Homer", x))
('Lisa', 'Bart')
We can use intermediate variables for more complex queries. Who is Bart's grandfather?

>>> y =var()
>>>run(1, x, parent(x, y),
parent(y, 'Bart'))
('Abe',)
We can express the grandfather relationship separately. In this example we use conde, a
goal constructor for logical and and or.
>>>defgrandparent(x, z):
... y =var()
...returnconde((parent(x, y), parent(y, z)))

>>>run(1, x, grandparent(x, 'Bart'))


('Abe,')

With logic programming, we can compare expressions and find out unknown values.
Consider the following piece of code:
1. >>> from kanren import run,var,fact
2. >>> from kanren.assoccomm import eq_assoccomm as eq
3. >>> from kanren.assoccomm import commutative,associative
4. >>> add='add'#Defining operations
5. >>>mul='mul'
6. >>>fact(commutative,mul)#Addition and multiplication are commutative and associative
7. >>>fact(commutative,add)
8. >>>fact(associative,mul)
9. >>>fact(associative,add)
10. >>>a,b,c=var('a'),var('b'),var('c')#Defining variables
11. >>>#2ab+b+3c is the expression we have'
12. >>> expression=(add, (mul, 2, a, b), b, (mul, 3, c))
13. >>> expression=(add,(mul,3,-2),(mul,(add,1,(mul,2,3)),-1))#Expression
14. >>> expr1=(add,(mul,(add,1,(mul,2,a)),b),(mul,3,c))#Expressions to match
15. >>> expr2=(add,(mul,c,3),(mul,b,(add,(mul,2,a),1)))
16. >>> expr3=(add,(add,(mul,(mul,2,a),b),b),(mul,3,c))
17. >>>run(0,(a,b,c),eq(expr1,expression))#Calls to run()
((3, -1, -2),)
1. >>>run(0,(a,b,c),eq(expr2,expression))
((3, -1, -2),)
Do you know about Python Web Framework
1. >>>run(0,(a,b,c),eq(expr3,expression))
()
You’ll see that the third expression gives us nothing. It is mathematically the same,
but structurally different.
5. Checking for Prime Numbers in
Python Logic Programming
If we have a list of numbers, we can find out which ones are prime and also generate
such numbers. Let’s see how.
1. >>> from kanren import isvar,run,membero
2. >>> from kanren.core import success,fail,goaleval,condeseq,eq,var
3. >>> from sympy.ntheory.generate import prime,isprime
4. >>> import itertools as it
5. >>>defprime_test(n): #Function to test for prime
6. if isvar(n):
7. return condeseq([(eq,n,p)] for p in map(prime,it.count(1)))
8. else:
9. return success if isprime(n) else fail
10. >>> n=var()#Variable to use
11. >>>
{41, 19, 29, 23}

1. >>>run(7,n,prime_set(run(0,n,(membero,n,(12,14,15,19,21,20,22,29,23,30,41,44,62,52,65,85)),
(prime_test,n)))test(n))
(2, 3, 5, 7, 11, 13, 17)
Network Programming Paradigm:
Socket programming :
Echo Server

Here’s the server, echo-server.py:

#!/usr/bin/env python3

importsocket

HOST='127.0.0.1'# Standard loopback interface address (localhost)


PORT=65432# Port to listen on (non-privileged ports are > 1023)

withsocket.socket(socket.AF_INET,socket.SOCK_STREAM)ass:
s.bind((HOST,PORT))
s.listen()
conn,addr=s.accept()
withconn:
print('Connected by',addr)
whileTrue:
data=conn.recv(1024)
ifnotdata:
break
conn.sendall(data)
Echo Client

Now let’s look at the client, echo-client.py:

#!/usr/bin/env python3

importsocket

HOST='127.0.0.1'# The server's hostname or IP address


PORT=65432# The port used by the server

withsocket.socket(socket.AF_INET,socket.SOCK_STREAM)ass:
s.connect((HOST,PORT))
s.sendall(b'Hello, world')
data=s.recv(1024)

print('Received',repr(data))

You might also like