-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnalysis.py
201 lines (163 loc) · 5.6 KB
/
Analysis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import statsmodels.api as sm
import pandas as pd
import numpy as np
import re
import collections
import matplotlib.pyplot as plt
from mpldatacursor import datacursor
class analysis():
def __init__(self, num_data):
self.num_data = num_data
# clean up a row data
def clean_up(self, file_name):
with open(file_name) as infile:
contents = infile.read()
data = contents.replace('%20', ' ')
data = data.replace('%2F%2F','://')
info = data.replace(';','\n')
info = info.replace('%3D%3D%3D%3D','\n')
info = info.replace('png','\n')
info1 = info.replace('%3A','')
#f = open("Nata.txt","a+")
#f.write(info1 +"\n")
#f.close()
return info1
'''
website_list = pd.read_html("https://en.wikipedia.org/wiki/List_of_most_popular_websites")
for each in website_list:
web_address = pd.DataFrame(data=each[1], index=each[1])
'''
# change to list with in a dictionary
def prepare(self, file_name, from_file=False):
collection = []
data= collections.defaultdict(dict)
count_num_data = 0
if from_file:
with open(file_name,'r') as l_file:
content = l_file.read()
else:
content = file_name
line = content.split('\n')
# convert the data into one hot list
for each in line:
values = each.split(':')
if len(values) == 3:
key, value_1, value_2 = values
value = value_1+":"+ value_2
if key == 'web address':
catagory = value
elif len(values) == 2:
key, value = values
else:
# if count_num_data %100 == 0:
# print key, value, len(value)
pass
if key == 'Waterfall view':
pattern = r'[0-9][0-9]'
if re.search(pattern, value):
x = re.findall(pattern,value)
rep = re.compile(r'\s+')
time = re.sub(rep,'',str(x[:3]).replace("'",""))
value = time.replace('18','2018').replace('[', '').replace(']','').replace(',','-')
key = 'date'
count_num_data += 1
data[catagory].setdefault(key,[]).append(value)
cleaned_dict = dict(data)
for web in cleaned_dict.keys():
#replace empty value with np.nan
del cleaned_dict[web]['Waterfall view']
del cleaned_dict[web]['web address']
for x in cleaned_dict[web].keys():
if '' in cleaned_dict[web][x]:
for y in cleaned_dict[web][x]:
cleaned_dict[web][x] = np.nan
if cleaned_dict[web].has_key(''):
del cleaned_dict[web]['']
else:
pass
print "The number of data collected is: ", count_num_data
return cleaned_dict
def select(self, dataframe, param):
dfT = dataframe.transpose()
# conver to frame
df_2 = pd.DataFrame(data=dfT[param]).dropna() #, columns=['webaddress',param]).dropna()
s = df_2.apply(lambda x: pd.Series(x[param]), axis = 1).transpose().max()
s.name = param
# conver serias to DataFrame
#df = pd.DataFrame(data=s ) #columns=['webaddress', param])
df = df_2.drop(param, axis=1).join(s)
return df
# produce tabel, chart, and graph
def plot(self, dataframe, param, param2, color='red', label ='no', ax = None):
df = self.select(dataframe, param)
df2 = self.select(dataframe, param2)
comb_df = df.join(df2)
if label == 'no':
comb_df.plot.scatter(x=param, y=param2, color=color,title=param+' Vs '+param2)
datacursor(hover=True, point_labels=comb_df.index)
# getting the summary
print df.describe()
print df2.describe()
print comb_df
plt.show()
#return dataframe.plot()
else:
if ax == None:
return comb_df.plot.scatter(x=param, y=param2, color=color, label=label)
else:
comb_df.plot.scatter(x=param, y=param2, color=color, label=label, ax = ax, title=param+' Vs '+param2)
datacursor(hover=True, point_labels=comb_df.index)
# getting the summary
print df.describe()
print df2.describe()
print comb_df
plt.show()
def prop(self, dataframe):
return dataframe.columns
test = analysis(1)
# import from a the cleaned data
#value = test.prepare('Nata.txt', True)
#print value
# import row file
usa = test.clean_up('./Test_results/test_result.txt')
Italy = test.clean_up('./Test_results/Milan_Italy_test_result.txt')
alexa = test.clean_up('./Test_results/alexa_test_result.txt')
USA_v = test.prepare(usa)
Italy_v = test.prepare(Italy)
###############################################################################
# u'(Doc complete) Byets in', u'(Doc complete) Requests',
# u'(Fully loaded) Bytes in', u'(Fully loaded) Requests',
# u'(Fully loaded) Time', u'DOM elements', u'First byte', u'Load time',
# u'Speed Index', u'Start render', u'date'],
###############################################################################
'''
df2 = pd.DataFrame.from_dict({(i,j):value[i][j]
for i in value.keys()
for j in value[i].keys()},
orient = 'index')
'''
df_u = pd.DataFrame(data=USA_v)
df_i = pd.DataFrame(data=Italy_v)
#test.plot(df_u, u'Speed Index', u'Load time')
dat = test.plot(df_u, u'Speed Index', u'Load time',color='lightBlue', label="USA")
test.plot(df_i, u'Speed Index', u'Load time',color='DarkBlue',label="Italy", ax=dat)
# linear regression
p1 = test.select(df_u, u'Speed Index')
p2 = test.select(df_u, u'Load time')
p3 = test.select(df_u, u'Start render')
p4 = test.select(df_u, u'DOM elements')
X = p1.join(p2).join(p3).join(p4)
y = test.select(df_u, u'First byte')
model = sm.OLS(y, X).fit()
predictions = model.predict(X)
print model.summary()
plt.title( "Ordinary Least Squares")
plt.xlabel("Web addresses")
plt.ylabel('First byte')
plt.plot(predictions, 'bo',markersize=9, label='predictions')
plt.plot(y, 'ko',markersize=6, label='TARGET')
Y = -0.7179*p1 + 0.5839*p2 +0.7944*p3 +-1.3634*p4
plt.plot(y, '--')
datacursor(hover=True, point_labels=predictions.index)
plt.legend()
plt.show()