You are on page 1of 10

ROLL NO: 201071026

NAME: MAYURI PAWAR

AI LAB
EXPERIMENT NO: 3b

CODE:
from string import ascii_lowercase
import random
from itertools import combinations
import numpy as np
alphabet = (list(ascii_lowercase))[:26]
def generateVariableList(n):
positive_var = []
for i in range(1, n + 1):
x = i
s = ""
while x > 0:
if x % 26 == 0:
s = s + 'z'
x = int(x / 26)
x = x - 1
else:
s = alphabet[(x % 26) - 1] + s
x = int(x / 26)
positive_var.append(s)
return positive_var
def getVariableKey(n):
x = n
s = ""
while x > 0:
if x % 26 == 0:
s = s + 'z'
x = int(x / 26)
x = x - 1
else:
s = alphabet[(x % 26) - 1] + s
x = int(x / 26)

return s
def generateProblemSet(m, k, n,test_cases):
positive_var = generateVariableList(n)
negative_var = [c.upper() for c in positive_var]
variables = positive_var + negative_var
problems = []
allCombs = list(combinations(variables, k))
i = 0
while i<test_cases:
c = random.sample(allCombs, m)
if c not in problems:
i += 1
problems.append(list(c))
return variables, problems
def assignValues(variables, n):
forPositive = list(np.random.choice(2,n))
forNegative = [abs(1-i) for i in forPositive]
values = forPositive + forNegative
var_assign = dict(zip(variables, values))
return var_assign
def getHeuersticScore(problem, values):
count = 0
for sub in problem:
l = [values[val] for val in sub]
count += any(l)
return count
def hillClimbing(problem,values,noOfClauses,n):
curr_score = getHeuersticScore(problem,values)
if(curr_score == noOfClauses):
return curr_score, True
maxScore = 0
maxConfiguration = {}
for i in range(1,n+1):
temp_values = values.copy()
key = getVariableKey(i)
temp_values[key] = abs(temp_values[key] - 1)
temp_values[key.upper()] = abs(temp_values[key.upper()] - 1)
new_score = getHeuersticScore(problem,temp_values)
if new_score > maxScore:
maxScore = new_score
maxConfiguration = temp_values
if maxScore == noOfClauses:
return maxScore, True
if maxScore <= curr_score:
return curr_score,False
else:
return hillClimbing(problem,maxConfiguration,noOfClauses,n)
def beamSearch(problem,values,noOfClauses,n,beamWidth):
stateQueue = []
temp = values.copy()
stateQueue.append(temp)
nodes_visited = 0
maxScore = 0
while len(stateQueue) > 0:
temp = stateQueue.pop(0).copy()
nodes_visited += 1
curr_score = getHeuersticScore(problem,temp)
maxScore = max(maxScore,curr_score)
if(curr_score == noOfClauses):
return curr_score,True
neighbours = list()
for i in range(1,n+1):
temp_values = temp.copy()
key = getVariableKey(i)
temp_values[key] = abs(temp_values[key] - 1)
temp_values[key.upper()] = abs(temp_values[key.upper()] - 1)
new_score = getHeuersticScore(problem,temp_values)
if new_score > curr_score:
z = {'score': new_score, 'state': temp_values}
neighbours.append(z)
neighbours.sort(key=lambda item: item.get("score"))
sorted_neighbours = neighbours[::-1]
best_neighbours = sorted_neighbours[:beamWidth]
for neigh in best_neighbours:
stateQueue.append(neigh['state'])
return maxScore,False
def
variableNeighbourhoodDescent(problem,values,noOfClauses,n,neighbourhoodFuncVal
ue):
curr_score = getHeuersticScore(problem,values)
if(curr_score == noOfClauses):
return curr_score,True
maxScore = 0
maxConfiguration = {}
if neighbourhoodFuncValue == 1:

for i in range(1,n+1):
temp_values = values.copy()
key = getVariableKey(i)
temp_values[key] = abs(temp_values[key] - 1)
temp_values[key.upper()] = abs(temp_values[key.upper()] - 1)
new_score = getHeuersticScore(problem,temp_values)
if new_score > maxScore:
maxScore = new_score
maxConfiguration = temp_values
elif neighbourhoodFuncValue == 2:
for i in range(1,n):
for j in range(i+1,n+1):
temp_values = values.copy()
key1 = getVariableKey(i)
key2 = getVariableKey(j)
temp_values[key1] = abs(temp_values[key1] - 1)
temp_values[key1.upper()] = abs(temp_values[key1.upper()] - 1)
temp_values[key2] = abs(temp_values[key2] - 1)
temp_values[key2.upper()] = abs(temp_values[key2.upper()] - 1)
new_score = getHeuersticScore(problem,temp_values)
if new_score > maxScore:
maxScore = new_score
maxConfiguration = temp_values
else :
for i in range(1,n-1):
for j in range(i+1,n):
for k in range(j+1,n+1):
temp_values = values.copy()
key1 = getVariableKey(i)
key2 = getVariableKey(j)
key3 = getVariableKey(k)
temp_values[key1] = abs(temp_values[key1] - 1)
temp_values[key1.upper()] = abs(temp_values[key1.upper()] -
1)
temp_values[key2] = abs(temp_values[key2] - 1)
temp_values[key2.upper()] = abs(temp_values[key2.upper()] -
1)
temp_values[key3] = abs(temp_values[key3] - 1)
temp_values[key3.upper()] = abs(temp_values[key3.upper()] -
1)
new_score = getHeuersticScore(problem,temp_values)
if new_score > maxScore:
maxScore = new_score
maxConfiguration = temp_values
if maxScore == noOfClauses:
return maxScore, True
if maxScore <= curr_score:
if(neighbourhoodFuncValue < 3):
return
variableNeighbourhoodDescent(problem,maxConfiguration,noOfClauses,n,neighbourh
oodFuncValue + 1)
else:
return maxScore, False
else:
return
variableNeighbourhoodDescent(problem,maxConfiguration,noOfClauses,n,neighbourh
oodFuncValue)
def tabu(problem,values,noOfClauses,n,tabuTenure):
curr_score = getHeuersticScore(problem,values)

if(curr_score == noOfClauses):
return curr_score,True
maxScore = curr_score
maxConfiguration = values.copy()
nextConfiguration = values.copy()
tabu_memory = []

for i in range(n):
tabu_memory.append(0)
time = 0
while time<= 2000:
if maxScore == noOfClauses:
return maxScore, True
new_i = 0
new_j = 0
maxLocalScore = 0
for i in range(1,n):
if tabu_memory[i]!=0:
continue
for j in range(i+1,n):
if tabu_memory[j]!=0:
continue
temp_values = nextConfiguration.copy()
key1 = getVariableKey(i)
key2 = getVariableKey(j)
temp_values[key1] = abs(temp_values[key1] - 1)
temp_values[key1.upper()] = abs(temp_values[key1.upper()] - 1)
temp_values[key2] = abs(temp_values[key2] - 1)
temp_values[key2.upper()] = abs(temp_values[key2.upper()] - 1)
new_score = getHeuersticScore(problem,temp_values)
if new_score > maxLocalScore:
maxLocalScore = new_score
nextConfiguration = temp_values.copy()
new_i = i
new_j = j
if new_score == noOfClauses:
return maxLocalScore, True
if maxLocalScore > maxScore:
maxScore = maxLocalScore
maxConfiguration = nextConfiguration.copy()
for x in range(n):
if tabu_memory[x]!=0:
tabu_memory[x] -= 1

time+=1
tabu_memory[new_i] = tabuTenure
tabu_memory[new_j] = tabuTenure

return max(maxScore,curr_score), False


def printProblem(problem,m,k):
print("{",end = " ")
for j, clause in enumerate(problem):
print("(",end = " ")
for i,variable in enumerate(clause):
if variable.isupper():
print(f"~{variable.lower()}",end = " ")
else:
print(variable,end = " ")
if i != k-1:
print("V",end = " ")
print(")",end = " ")
if j != m-1:
print("^",end = " ")
print(" }")
print()
print()

if __name__ == '__main__':
m = int(input("Enter the number of clauses(m) : "))
print()
n = int(input("Enter the total number of variables(n) : "))
print()
print("The number of variables in a clause(k) : 3")
k = 3
print()
testcases = int(input("Enter the no of testcases : "))
variables, problems = generateProblemSet(m, k, n,testcases)
values = assignValues(variables, n)
hillClimbTotal = 0
hillClimbFoundSol = 0
beam3Total = 0
beam3FoundSol = 0
beam4Total = 0
beam4FoundSol = 0
vndTotal = 0
vndFoundSol = 0
tabuTotal = 0
tabuFoundSol = 0
for i,problem in enumerate(problems):
print("\n\nCurrent Problem : \n")
printProblem(problem,m,k)
print("-------ANALYSIS-------")
print()
print("\nHill Climbing :")
score, foundSolution = hillClimbing(problem,values,m,n)
print(f"Best Heursictic Score : {score} \nWas Solution found ? :
{foundSolution}")
hillClimbTotal += score
if(foundSolution):
hillClimbFoundSol += 1

print("\nBeam Search for Beam Width 3 : ")


score, foundSolution = (beamSearch(problem,values,m,n,3))
print(f"Best Heursictic Score : {score} \nWas Solution found ? :
{foundSolution}")
beam3Total += score
if(foundSolution):
beam3FoundSol += 1
print("\nBeam Search for Beam Width 4 : ")
score, foundSolution = (beamSearch(problem,values,m,n,4))
print(f"Best Heursictic Score : {score} \nWas Solution found ? :
{foundSolution}")
beam4Total += score
if(foundSolution):
beam4FoundSol += 1

print("\nVariable Neighbourhood Descent : ")


score, foundSolution = variableNeighbourhoodDescent(problem,values,m,n,1)
print(f"Best Heursictic Score : {score} \nWas Solution found ? :
{foundSolution}")
vndTotal += score
if(foundSolution):
vndFoundSol += 1

print("\nTabu Search : ")


score, foundSolution = tabu(problem,values,m,n,4)
print(f"Best Heursictic Score : {score} \nWas Solution found ? :
{foundSolution}")
tabuTotal += score
if(foundSolution):
tabuFoundSol += 1

print()
print("-------FINAL ANALYSIS OF ALL TESTCASES-------")
print()
print("Hill Climbing :")
print(f"Average Heuristic Score : {hillClimbTotal/testcases} ")
print(f"Solution was found for : {hillClimbFoundSol} out of {testcases}
TestCases")
print(f"So the accuracy measure is : {hillClimbFoundSol * 100 /testcases} %")
print()
print("Beam Search for Beam Width 3 : ")
print(f"Average Heuristic Score : {beam3Total/testcases} ")
print(f"Solution was found for : {beam3FoundSol} out of {testcases}
TestCases")
print(f"So the accuracy measure is : {beam3FoundSol* 100/testcases} %")
print()
print("Beam Search for Beam Width 4 : ")
print(f"Average Heuristic Score : {beam4Total/testcases} ")
print(f"Solution was found for : {beam4FoundSol} out of {testcases}
TestCases")
print(f"So the accuracy measure is : {beam4FoundSol* 100/testcases} %")
print()
print("Variable Neighbourhood Descent : ")
print(f"Average Heuristic Score : {vndTotal/testcases} ")
print(f"Solution was found for : {vndFoundSol} out of {testcases} TestCases")
print(f"So the accuracy measure is : {vndFoundSol* 100/testcases} %")
print()

print("Tabu Search : ")


print(f"Average Heuristic Score : {tabuTotal/testcases} ")
print(f"Solution was found for : {tabuFoundSol} out of {testcases}
TestCases")
print(f"So the accuracy measure is : {tabuFoundSol* 100/testcases} %")
print()
OUTPUT:

You might also like