You are on page 1of 20

#declaration of fuzzy set

a,b,c=[],[],[]
fuzzy_sets=[a,b,c]

#user input to fuzzy set


for i in range(3):
print("Insert for fuzzy set number : ",i+1)
for j in range(3):
print('Membership value of x{}'.format(j+1))
x=float(input())
fuzzy_sets[i].append(('x{}'.format(j+1),x))

Insert for fuzzy set number : 1


Membership value of x1
0.3
Membership value of x2
0.4
Membership value of x3
0.6
Insert for fuzzy set number : 2
Membership value of x1
0.3
Membership value of x2
0.7
Membership value of x3
0.9
Insert for fuzzy set number : 3
Membership value of x1
0.1
Membership value of x2
0.4
Membership value of x3
0.6

fuzzy_sets

[[('x1', 0.3), ('x2', 0.4), ('x3', 0.6)],


[('x1', 0.3), ('x2', 0.7), ('x3', 0.9)],
[('x1', 0.1), ('x2', 0.4), ('x3', 0.6)]]

#performing union operation


result1=[]
for j in range(3):
result1.append(('x{}'.format(j+1),max(fuzzy_sets[0][j]
[1],fuzzy_sets[1][j][1],fuzzy_sets[2][j][1])))

result1

[('x1', 0.3), ('x2', 0.7), ('x3', 0.9)]


#performing intersection operation
result2=[]
for j in range(3):
result2.append(('x{}'.format(j+1),min(fuzzy_sets[0][j]
[1],fuzzy_sets[1][j][1],fuzzy_sets[2][j][1])))

result2

[('x1', 0.1), ('x2', 0.4), ('x3', 0.6)]

#Implementing Triangular Membership Function


#let fuzzy set be
a=[(1,0),(4,1),(6,0)]
a.sort()
#importing inbuilt plotting function
import matplotlib.pyplot as plt

x=[]
u=[]
for i in a:
x.append(i[0])
u.append(i[1])

plt.plot(x,u)
plt.show()

def triangular(x,fuzzy):
if fuzzy[1][1]!=1 and fuzzy[0][1]!=0 and fuzzy[2][0]!=0:
return 'not triangular'
if x<fuzzy[0][0]:
return 0
elif x>fuzzy[2][0]:
return 0
elif x>=fuzzy[0][0] and x<=fuzzy[1][0]:
val=(x-fuzzy[0][0])/(fuzzy[1][0]-fuzzy[0][0])
return val
elif x>=fuzzy[1][0] and x<=fuzzy[2][0]:
val=(fuzzy[2][0]-x)/(fuzzy[2][0]-fuzzy[1][0])
return val

i=float(input('Enter number: '))


val=triangular(i,a)

Enter number: 3

print('Resultant value is: ',val)

Resultant value is: 0.6666666666666666

plt.plot(x,u,color='black')
plt.scatter(i,val,color='red')
plt.show()

#Implementing Trapezoidal Membership Function


#let fuzzy set be
a=[(1,0),(4,1),(6,1),(7,0)]
a.sort()

x=[]
u=[]
for i in a:
x.append(i[0])
u.append(i[1])

plt.plot(x,u)
plt.show()

def trapezoidal(x,fuzzy):
if fuzzy[1][1]!=1 and fuzzy[0][1]!=0 and fuzzy[2][0]!=1 and
fuzzy[3][0]!=0:
return 'not trapezoidal'
if x<fuzzy[0][0]:
return 0
elif x>fuzzy[3][0]:
return 0
elif x>=fuzzy[0][0] and x<=fuzzy[1][0]:
val=(x-fuzzy[0][0])/(fuzzy[1][0]-fuzzy[0][0])
return val
elif x>=fuzzy[2][0] and x<=fuzzy[3][0]:
val=(fuzzy[3][0]-x)/(fuzzy[3][0]-fuzzy[2][0])
return val
elif x>=fuzzy[1][0] and x<=fuzzy[2][0]:
return 1
i=float(input('Enter number: '))
val=trapezoidal(i,a)

Enter number: 6.4

print('Resultant value is: ',val)

Resultant value is: 0.5999999999999996

plt.plot(x,u,color='black')
plt.scatter(i,val,color='red')
plt.show()

#Gaussian
c=int(input('Center Value: '))
s=int(input('Width Value: '))
m=int(input('Fuzzification Value: '))

Center Value: 5
Width Value: 2
Fuzzification Value: 2

import math

fuzzy_set=[]
for i in range(c*2+1):
m_value=math.exp(-(1/2)*(abs((i-c)/s))**m)
fuzzy_set.append((i,m_value))
x=[]
u=[]
for i in fuzzy_set:
x.append(i[0])
u.append(i[1])

plt.plot(x,u,color='black')
plt.show()

def gaussian(x,c,s,m):
m_value=math.exp(-(1/2)*(abs((x-c)/s))**m)
return m_value

i=float(input('Enter number: '))


val=gaussian(i,c,s,m)

Enter number: 3.4

print('Resultant value is: ',val)

Resultant value is: 0.7261490370736908

plt.plot(x,u,color='black')
plt.scatter(i,val,color='red')
plt.show()
a=fuzzy_sets[0]
b=fuzzy_sets[1]
print(a,b)

[('x1', 0.3), ('x2', 0.4), ('x3', 0.6)] [('x1', 0.3), ('x2', 0.7),
('x3', 0.9)]

def fuzzy_operation(a,b):
result=[]
for j in range(3):
result.append(('x{}'.format(j+1),(a[j][1]*b[j][1])/(a[j]
[1]+b[j][1])))
return result

print(fuzzy_operation(a,b))

[('x1', 0.15), ('x2', 0.2545454545454545), ('x3',


0.36000000000000004)]
9

import pandas as pd
df=pd.DataFrame()

global size
size=5
def iteration(x,df):
def fitness_fun(x):
fitness_func=2*x**2+3*x+1
return fitness_func
def decimal_to_binary(x):
ch=bin(x).replace('0b','')
if len(ch)<size:
ch='0'+ch
return ch

#encoding
string=[]
initial_population=[]
fitness=[]
for i in range(len(x)):
string.append('x{}'.format(i+1))
initial_population.append(decimal_to_binary(x[i]))
fitness.append(fitness_fun(x[i]))
total_val_fitness=sum(fitness)
avg_val_fitness=total_val_fitness/len(x)
def probability_ExpectedCount(x,y):
return x/y
probability=[]
expected_count=[]
for i in fitness:

probability.append(probability_ExpectedCount(i,total_val_fitness))

expected_count.append(probability_ExpectedCount(i,avg_val_fitness))
df['String']=string
df['Initial_Population']=initial_population
df['x']=x
df['Fitness']=fitness
df['Probability']=probability
df['Expected_Count']=expected_count
df['Actual_Count']=round(df['Expected_Count'])
return df

#given
x=[9,11,13,15]
df=iteration(x,df)
df

String Initial_Population x Fitness Probability Expected_Count


\
0 x1 01001 9 190 0.141791 0.567164

1 x2 01011 11 276 0.205970 0.823881

2 x3 01101 13 378 0.282090 1.128358

3 x4 01111 15 496 0.370149 1.480597

Actual_Count
0 1.0
1 1.0
2 1.0
3 1.0

def binary_to_decimal(x):
return int(x,2)

import random

#Uniform Crossover
#x1,x4 x2,x3
def crossover(x,y):
x=list(x)
y=list(y)
for i in range(len(x)):
#tossing coin
if i%2==0:
pass
else:
t=x[i]
x[i]=y[i]
y[i]=t
x=''.join(x)
y=''.join(y)
return (x,y)
offsprings=[]
offsprings.extend(crossover(df['Initial_Population']
[2],df['Initial_Population'][3]))
offsprings.extend(crossover(df['Initial_Population']
[1],df['Initial_Population'][0]))

offsprings

['01111', '01101', '01001', '01011']


off_x=[]
for i in offsprings:
off_x.append(binary_to_decimal(i))

off_x

[15, 13, 9, 11]

df1=pd.DataFrame()

df1=iteration(off_x,df1)

df1

String Initial_Population x Fitness Probability Expected_Count


\
0 x1 01111 15 496 0.370149 1.480597

1 x2 01101 13 378 0.282090 1.128358

2 x3 01001 9 190 0.141791 0.567164

3 x4 01011 11 276 0.205970 0.823881

Actual_Count
0 1.0
1 1.0
2 1.0
3 1.0

offsprings2=[]
offsprings2.extend(crossover(df1['Initial_Population']
[2],df1['Initial_Population'][3]))
offsprings2.extend(crossover(df1['Initial_Population']
[1],df1['Initial_Population'][0]))
off_x2=[]
for i in offsprings2:
off_x2.append(binary_to_decimal(i))

df2=pd.DataFrame()
df2=iteration(off_x2,df2)
df2

String Initial_Population x Fitness Probability Expected_Count


\
0 x1 01011 11 276 0.205970 0.823881

1 x2 01001 9 190 0.141791 0.567164

2 x3 01111 15 496 0.370149 1.480597


3 x4 01101 13 378 0.282090 1.128358

Actual_Count
0 1.0
1 1.0
2 1.0
3 1.0

15

def iteration(x):
def fitness_fun(x):
fitness_func=(int(x[0])+int(x[1]))-(int(x[2])+int(x[3]))+
(int(x[4])+int(x[5]))-(int(x[6])+int(x[7]))
return fitness_func
#encoding
string=[]
fitness=[]
for i in range(len(x)):
string.append('x{}'.format(i+1))
fitness.append(fitness_fun(x[i]))
total_val_fitness=sum(fitness)
val1=zip(string,x,fitness)
val=list(val1)
val=sorted(val,key=lambda x:x[2])[::-1]
return val

x=['65413532','87126601','23921285','41852094']

val1=iteration(x)

val1

[('x2', '87126601', 23),


('x1', '65413532', 9),
('x3', '23921285', -16),
('x4', '41852094', -19)]

#cross-over with best fitted middle point


best1=val1[0][1]
best2=val1[1][1]

off_1=best1[:int(len(best1)/2)]+best2[int(len(best2)/2):]
off_2=best2[:int(len(best2)/2)]+best1[int(len(best1)/2):]

best3=val1[2][1]
#cross-over with 2nd and 3rdbest fitted from 2nd and 6th position
off_3=best2[:2]+best3[2:6]+best2[6:]
off_4=best3[:2]+best2[2:6]+best3[6:]

off_5,off_6=crossover(best1,best3)

offspring=[off_1,off_2,off_3,off_4,off_5,off_6]

new_gen=iteration(offspring)

new_gen

[('x2', '65416601', 17),


('x1', '87123532', 15),
('x5', '83126205', 11),
('x3', '65921232', -2),
('x6', '27921681', -4),
('x4', '23413585', -5)]

import pandas as pd
df=pd.DataFrame(columns=['a','b','c','d','e','f'])

def tsp_d(df,iteration_df):
distance=[]
print(df)
for i in iteration_df['paths']:
add=0
for j in range(len(i)-1):
add+=df.loc[i[j]][i[j+1]]
distance.append(add)
iteration_df['distance']=distance
print(iteration_df)
return iteration_df

def tsp(iteration_df):
total_fitness=sum(iteration_df['distance'])

iteration_df['relative_fitness']=total_fitness/iteration_df['distance'
]
total_relative_fitness=sum(iteration_df['relative_fitness'])

iteration_df['probability']=iteration_df['relative_fitness']/total_rel
ative_fitness
cdf=[]
s=0
for i in iteration_df['probability']:
s+=i
cdf.append(s)
iteration_df['cdf']=cdf

#city table
df['a']=[0,5,6,8,2,1]
df['b']=[5,0,6,3,2,3]
df['c']=[1,6,0,4,4,5]
df['d']=[4,6,8,0,2,1]
df['e']=[3,6,8,2,0,3]
df['f']=[2,5,6,7,2,0]

df.index=['a','b','c','d','e','f']

df=df.transpose()

df

a b c d e f
a 0 5 6 8 2 1
b 5 0 6 3 2 3
c 1 6 0 4 4 5
d 4 6 8 0 2 1
e 3 6 8 2 0 3
f 2 5 6 7 2 0

#a->a
import random as ran

paths=[]
for i in range(4):
path=['a']
roots=['b','c','d','e','f']
for j in range(5):
v=ran.choices(roots)
roots.remove(v[0])
path.append(v[0])
path.append('a')
paths.append(path)

paths

[['a', 'f', 'c', 'b', 'e', 'd', 'a'],


['a', 'f', 'b', 'e', 'c', 'd', 'a'],
['a', 'c', 'e', 'd', 'b', 'f', 'a'],
['a', 'b', 'c', 'e', 'd', 'f', 'a']]

df

a b c d e f
a 0 5 6 8 2 1
b 5 0 6 3 2 3
c 1 6 0 4 4 5
d 4 6 8 0 2 1
e 3 6 8 2 0 3
f 2 5 6 7 2 0

iteration_df=pd.DataFrame()

iteration_df['paths']=paths

iteration_df

paths
0 [a, f, c, b, e, d, a]
1 [a, f, b, e, c, d, a]
2 [a, c, e, d, b, f, a]
3 [a, b, c, e, d, f, a]

iteration_df=tsp_d(df,iteration_df)

a b c d e f
a 0 5 6 8 2 1
b 5 0 6 3 2 3
c 1 6 0 4 4 5
d 4 6 8 0 2 1
e 3 6 8 2 0 3
f 2 5 6 7 2 0
paths distance
0 [a, f, c, b, e, d, a] 21
1 [a, f, b, e, c, d, a] 24
2 [a, c, e, d, b, f, a] 23
3 [a, b, c, e, d, f, a] 20

iteration_df

paths distance
0 [a, f, c, b, e, d, a] 21
1 [a, f, b, e, c, d, a] 24
2 [a, c, e, d, b, f, a] 23
3 [a, b, c, e, d, f, a] 20

df1=iteration_df.copy()

tsp(iteration_df)

iteration_df

paths distance relative_fitness probability


cdf
0 [a, f, c, b, e, d, a] 21 4.190476 0.260549
0.260549
1 [a, f, b, e, c, d, a] 24 3.666667 0.227981
0.488530
2 [a, c, e, d, b, f, a] 23 3.826087 0.237893
0.726423
3 [a, b, c, e, d, f, a] 20 4.400000 0.273577
1.000000

#parents
parents=[]
j=-1
while len(parents)<2:
random_number=ran.random()
for row,i in enumerate(iteration_df['cdf']):
if i>random_number:
if j!=row:
parents.append(iteration_df.iloc[row].paths)
if j==-1:
j=row
break

parents

[['a', 'f', 'b', 'e', 'c', 'd', 'a'], ['a', 'b', 'c', 'e', 'd', 'f',
'a']]

def unique(x,y):
if x[:2]!=y[:2]:
t=y[0]
y[0]=x[0]
for i in range(1,len(y)):
if y[i]==y[0]:
y[i]=t
y[1]=x[1]
for i in range(2,len(y)):
if y[i]==y[1]:
y[i]=t
x=['a']+x+['a']
y=['a']+y+['a']
return [x,y]

parent_ready=unique(parents[0][1:-1],parents[1][1:-1])

parent_ready
[['a', 'f', 'b', 'e', 'c', 'd', 'a'], ['a', 'f', 'b', 'e', 'd', 'b',
'a']]

parents

[['a', 'f', 'b', 'e', 'c', 'd', 'a'], ['a', 'b', 'c', 'e', 'd', 'f',
'a']]

#swap
off1=[]
off1.append(parent_ready[0][:2]+parent_ready[1][2:])
off1.append(parent_ready[1][:2]+parent_ready[0][2:])

off1

[['a', 'f', 'b', 'e', 'd', 'b', 'a'], ['a', 'f', 'b', 'e', 'c', 'd',
'a']]

off_distance=[]
for i in off1:
add=0
for j in range(len(i)-1):
add+=df.loc[i[j]][i[j+1]]
off_distance.append(add)

off_distance

[21, 24]

for d in range(len(off_distance)):
for row,i in enumerate(iteration_df['distance']):
if off_distance[d]<i:
df1.iloc[row]=[off1[d],off_distance[d]]
break

E:\anaconda\lib\site-packages\numpy\core\fromnumeric.py:3156:
VisibleDeprecationWarning: Creating an ndarray from ragged nested
sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays
with different lengths or shapes) is deprecated. If you meant to do
this, you must specify 'dtype=object' when creating the ndarray.
return asarray(a).ndim

iteration_df

paths distance relative_fitness probability


cdf
0 [a, f, c, b, e, d, a] 21 4.190476 0.260549
0.260549
1 [a, f, b, e, c, d, a] 24 3.666667 0.227981
0.488530
2 [a, c, e, d, b, f, a] 23 3.826087 0.237893
0.726423
3 [a, b, c, e, d, f, a] 20 4.400000 0.273577
1.000000

df1

paths distance
0 [a, f, c, b, e, d, a] 21
1 [a, f, b, e, d, b, a] 21
2 [a, c, e, d, b, f, a] 23
3 [a, b, c, e, d, f, a] 20

iteration_df=df1.copy()

tsp(iteration_df)

iteration_df

paths distance relative_fitness probability


cdf
0 [a, f, c, b, e, d, a] 21 4.047619 0.252331
0.252331
1 [a, f, b, e, d, b, a] 21 4.047619 0.252331
0.504663
2 [a, c, e, d, b, f, a] 23 3.695652 0.230389
0.735052
3 [a, b, c, e, d, f, a] 20 4.250000 0.264948
1.000000

import random as ran

13

3 ta plane
5 ta crew a,b,c,d,e
a b c 000
c d e 100
a d e 011
a b c 100
d b c 011
d a e 100
b a e 011
b d c 100
a b c 1 1 1 0 0 3
c d e 0 0 2 1 1 4
a d e 1 0 0 2 2 5
a b c 2 1 1 0 0 4
d b c 0 0 2 1 1 4
d a e 1 0 0 2 2 5
b a e 2 1 1 0 0 4
b d c 0 0 2 1 1 4

def fitness(crew,work_days_count):
for i in crew:
work_days_count[i]+=1
penalty = sum(max(0, work_days_count[crew] - MAX_WORK_DAYS) for
crew in work_days_count)
return 1 / (1 + penalty)

def crossover(parent1, parent2):


crossover_point = random.randint(1, NUM_DAYS - 1)
child = parent1[:crossover_point] + parent2[crossover_point:]
if len(set(child))!=len(child):
for i in set(child):
dup=0
for j in child:
if i==j:
dup+=1
if dup==2:
x=list(work_count.values())
found=False
while not found:
for k in range(5):
if list(work_count.keys())[k] not in
child and work_count[list(work_count.keys())[k]]<=1:
child[child.index(j)]=
list(work_count.keys())[k]
found=True

return child

def crew_fun(crew,work_count,generation):
for _ in range(generation):
fit_score=[]
for i in combi:
work_days_count=work_count.copy()
fit_score.append(fitness(i,work_days_count))
parents = [combi[i] for i in range(len(fit_score)) if
ran.random() < fit_score[i]]

try:
parent1, parent2 = random.sample(parents, 2)
child = crossover(parent1, parent2)
min1=min(fit_score)
combi.remove(combi[fit_score.index(min1)])
combi.insert(fit_score.index(min1),child)
fit_score.remove(min1)

except:
pass
fit_score=[]
for i in combi:
work_days_count=work_count.copy()
fit_score.append(fitness(i,work_days_count))
best_solution = combi[fit_score.index(max(fit_score))]
combi.remove(best_solution)
new_combi=[]
complete=[]
al=['a','b','c','d','e']
for i in best_solution:
work_count[i]+=1
for i in al:
if i not in best_solution:
work_count[i]=0
for i in work_count:
if work_count[i]>=2:
complete.append(i)
for i in al:
if i not in complete:
new_combi.append(i)
if len(new_combi)>3:
new_combi=new_combi[:3]
combi.append(new_combi)
return best_solution

global work_count
work_count={'a':0,'b':0,'c':0,'d':0,'e':0}
POPULATION_SIZE = 8

combi=[]
for _ in range(8):
crew=['a','b','c','d','e']
c=[]
for _ in range(3):
s=ran.choice(crew)
crew.remove(s[0])
c.append(s[0])
combi.append(c)

generation=20
print(crew_fun(combi,work_count,generation))
['a', 'b', 'e']

work_count

{'a': 2, 'b': 1, 'c': 0, 'd': 0, 'e': 1}

You might also like