Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
HarshVardhan12102002 authored Sep 27, 2024
1 parent 03ff595 commit 0738fed
Show file tree
Hide file tree
Showing 100 changed files with 17,728 additions and 0 deletions.
100 changes: 100 additions & 0 deletions DP for coalition formation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
DP.pyfrom itertools import combinations
import random, pandas as pd, timeit


#first line of the input file
ip = open("value_for_DP_file_16.txt", "r")
output = open("output_16.txt", "w")

n = int(ip.readline())
#print("jj",n)
sums = 0
temp = []
dictionary = {}
dp = {}
agents = []
coalition = []
backtrack = {}
dp[()] = 0
backtrack[()] = []

dictionary[(0,)] = ip.readline()
dictionary[(0,)] = dictionary[(0,)].strip()
print(dictionary[(0,)])
#dictionary[(0,)] = float(dictionary[(0,)])

for i in range(1, n + 1):
agents.append(i)
#print(agents)

for i in range(n):
all_combinations = combinations(agents, i + 1)
for element in list(all_combinations):
coalition.append(element)
#print("coalition", coalition)
#print("len of coalition",len(coalition))

def make_dic():
for i in coalition:
dictionary[i] = ip.readline()
dictionary[i] = dictionary[i].strip()
# dictionary[i] = float(dictionary[i])
#print(dictionary)

make_dic()


def complement(t, superset):
c = []
for ele in superset:
#print(ele)
if ele in t:
continue
else:
c.append(ele)
tup = tuple(c)
#print("tup",tup)
return tup



t1 = timeit.default_timer()
for i in range(len(coalition)):
if len(coalition[i]) == 1:
#print(coalition[i])
dp[coalition[i]] = dictionary[coalition[i]]
backtrack[coalition[i]] = coalition[i]
continue
else:
varMax = -1
#print(type(varMax))
tempCoal = 0
tempCoalCompliment = 0
for j in range(int((len(coalition[i]) / 2))):
coal1 = list(combinations(coalition[i], j + 1))
for k in range(len(coal1) - 1):

coalComplement = complement(coal1[k], coalition[i])
tempVar = int(dp[coal1[k]]) + int(dp[coalComplement])
#print(type(tempVar))

#tempVar=int(i) int(float('55063.000000'))
if float(tempVar) > varMax:
tempCoal = backtrack[coal1[k]]
tempCoalCompliment = backtrack[coalComplement]
varMax = max(varMax, tempVar)
if varMax > int(dictionary[coalition[i]]):

dp[coalition[i]] = varMax
backtrack[coalition[i]] = [tempCoal, tempCoalCompliment]
else:
dp[coalition[i]] = dictionary[coalition[i]]
backtrack[coalition[i]] = coalition[i]

t2 = timeit.default_timer()
print(t2 - t1)

output.write("\n" + str(backtrack[coalition[len(coalition) - 1]]))
output.write(" : " + str(dp[coalition[len(coalition) - 1]]) + "\n")
ip.close()
output.close()
Binary file added Dataset for kmeans.docx
Binary file not shown.
92 changes: 92 additions & 0 deletions generate_land_of_agents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import numpy as np
import random
import csv
import pandas as pd
import math

#a function for calculating the resource value with the help of land
def resource(land, value):
r=(land * value)

return (r)

# fist, second and third determine the amount of land in ratio 2:2:1 using the uniform distribution
agent=int(input("enter the range of the agents:"))
f=math.ceil(agent*0.3656)
s=math.floor(agent*0.4231)
#t=math.floor(agent*0.2113)
t=agent-(f+s)

first = np.random.uniform(0, 0.5, f)
second = np.random.uniform(0.5, 1, s)
third = np.random.uniform(1, 2, t)
#print("First 80%: ",first)
#print("Second 10%:",second)
#print("Third 10%:", third)
print("\n")


# now the values of land are written in the following text file 'land_value.txt'.
with open('land_value.txt', 'w') as filehandle:
for x in first:
filehandle.write('%s\n' % x)
for y in second:
filehandle.write('%s\n' % y)
for z in third:
filehandle.write('%s\n' % z)

#the file 'land_value.txt' is being read
my_file = open("land_value.txt", "r")
content = my_file.read()

#the read values are stored in a list "content_str" to get rid of the blank line \n
#because the blank line was getting included
content_list=[]
content_str = content.split("\n")
for i in content_str:
content_list.append(i)
print("the list of the land value in a list form:",content_list)


#random shuffle of the values of the land, [:-1] removes the last line
content_list_to_be_shuffled=content_list[:-1]
random.shuffle(content_list_to_be_shuffled)
print("after shuffle:",content_list_to_be_shuffled)

#the new shuffled values are written in another txt file
with open('land_value_shuffeled_500.txt', 'w') as filehandle:
for x in content_list_to_be_shuffled:
#while x != " ":
filehandle.write('%s\n'% x)
print("test",content_list_to_be_shuffled)


again_my_file=open('land_value_shuffeled.txt', 'r')
again_content=again_my_file.read()
#res1=[]

again_content_list=[]

again_content_str=again_content.split("\n")

res1=[]
res2=[]
res3=[]
for i in content_list_to_be_shuffled:
res1.append(resource(float(i), 7844))
res2.append(resource(float(i), 8180))
res3.append(resource(float(i), 10871))

file = open("land_vs_resource.csv", "w")
writer = csv.writer(file)
for w in range(len(content_list_to_be_shuffled)):
writer.writerow([res1[w],res2[w],res3[w]])
file.close()

df = pd.read_csv("land_vs_resource.csv")
################checking the number of empty rows in th csv file##################
print (df.isnull().sum())
############Droping the empty rows###################
modifiedDF = df.dropna()
##################Saving it to the csv file############################
modifiedDF.to_csv('modifiedland_vs_resource_500.csv',index=False)
Binary file added kmeans 2.0/Description.docx
Binary file not shown.
107 changes: 107 additions & 0 deletions kmeans 2.0/kmeans.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import numpy as np
import pandas as pd
import statsmodels.api as sm
#import seaborn as sns
from itertools import chain
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

data = pd.read_csv('test_case.csv')
print("The shape of data is",data.shape)
print("data",data)
df = pd.DataFrame(data)
data.head()

plt.scatter(data['res1'],data['res2'])
plt.show()

wcss = []
for i in range(1,11):
km = KMeans(n_clusters=i)
km.fit_predict(df)
wcss.append(km.inertia_)
print (wcss)

#x = data.iloc[:,1:3] # 1t for rows and second for columns
#print(x)
plt.plot(range(1,11),wcss)

X = data.iloc[:,:].values
km = KMeans(n_clusters=4, random_state=0)
y_means = km.fit_predict(X)
print(y_means)
print(X[y_means == 3,1])

plt.show()

# Add cluster labels to the dataframe
df['Cluster'] = km.labels_

clusters = [list(df[df['Cluster'] == cluster].index) for cluster in range(km.n_clusters)]
#final_cluster = [list(item) for item in clusters]
print(clusters)

for cluster in range(km.n_clusters):
print(f"Cluster {cluster}:")
print(df[df['Cluster'] == cluster])

#list_of_lists = [list(item) for item in frozen_set]
################################################################
P = 14.3
Q = 5400
res1 = 7844
res2 = 8180
res3 = 10871
# W=(7844+8180+10871)
W = 83683
agent=int(input("enter no of agents: "))

def value_calc(a_list):
# all_agent = [i for i in range(agent)]
ag = list(range(0, agent))
land1 = []
index = []
with open('land_value_shuffeled_15.txt') as f:
lines = f.read().splitlines()
for i in lines:
land1.append(i)
for i in range(0, len(land1)):
land1[i] = float(land1[i])
# print("coalition values:", land1)
for j in a_list:
index.append(ag.index(j))
# print ("index of the agents: ",index)
coalition_land = list(map(lambda x: land1[x], index))
# print("land of the corresponding lands: ",coalition_land)

# print("combined land of a coalition: ",sum(coalition_land))
return sum(coalition_land)


def discount(b_list):
coal_val_final = []
for i in b_list:
if i < 1:
val = P * Q * i - W * i
coal_val_final.append(val)
elif i < 1.5 and i >= 1:
val = P * Q * i - (W * 0.9) * i
coal_val_final.append(val)
elif i < 2 and i >= 1.5:
val = P * Q * i - (W * 0.85) * i
coal_val_final.append(val)
elif i <= 3 and i:
val = P * Q * i - (W * 0.75) * i
coal_val_final.append(val)
else:
val = P * Q * i - (W * 0.50) * i
coal_val_final.append(val)
# print ("the coalition values are v(C): ", coal_val_final)
return coal_val_final

list_of_all_vcs=[]
for i in clusters:
list_of_all_vcs.append(value_calc(i))
final_cs_value=discount(list_of_all_vcs)
print("value of each coalitions:",final_cs_value)
print("value of the entire coalition structure:",sum(final_cs_value))
Loading

0 comments on commit 0738fed

Please sign in to comment.