forked from laironald/PythonBase
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsenGraph.py~
523 lines (460 loc) · 21.7 KB
/
senGraph.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
from igraphSen import *
from senAdd import *
import copy, csv, datetime, sqlite3, types, random
def def_plot(g, layout="fr", vs_nm=None):
if vs_nm==None:
plot(g, layout=g.layout(layout))
else:
plot(g, layout=g.layout(layout), vertex_label=[str(x) for x in g.vs[vs_nm]])
class senGraph:
def __init__(self, lst, varType="edge", vs_nm="id", sort=True, debug=False):
if str(type(lst))=="<class 'igraph.Graph'>":
self.g = lst
elif str(type(lst))=="<class 'igraphSen.GraphSen'>":
self.g = lst
else:
tab = False
if str(type(lst))=="<type 'instance'>":
tab = True
if varType=="vertex" and tab:
import types
t = lst
self.g = GraphSen()
self.g.add_vertices(len(lst.vList)-1)
try:
vList = zip(*lst.vList)
self.g.vs[vs_nm] = vList[0]
for i, fld in enumerate(lst.vlst):
self.g.vs[fld] = vList[1+i]
except:
self.g.vs[vs_nm] = lst.vList
self.g.add_edges(
map(lambda x:
[self.g.vs[vs_nm].index(x[0]),
self.g.vs[vs_nm].index(x[1])],
lst.eList))
if len(lst.eList[0])>2:
eList = zip(*lst.eList)
for i, fld in enumerate(lst.elst):
self.g.es[fld] = eList[2+i]
elif varType=="edge":
count = 0
gDict = {}
gList = []
if tab:
tabL = copy.copy(lst)
lst = tabL.eList
#edge approach
for x in lst:
rList = []
for y in x[:2]: #just grab the first two
if y not in gDict:
gDict[y]=count
count = count + 1
rList.append(gDict[y])
gList.extend([rList])
if sort:
node_list = [x[0] for x in sorted(gDict.items(), key=lambda x: x[1])]
sort_list = sorted(node_list)
node_list = [sort_list.index(x) for x in node_list]
gList = [[node_list[x[0]], node_list[x[1]]] for x in gList]
self.g = GraphSen(gList)
if sort:
self.g.vs[vs_nm] = sort_list
else:
self.g.vs[vs_nm] = [x[0] for x in sorted(gDict.items(), key=lambda x: x[1])]
if tab:
self.vs_add(tabL.vList, tabL.vlst)
self.es_add(tabL.eList, tabL.elst)
self.component_attrib()
if debug:
print gList
print [x[0] for x in sorted(gDict.items(), key=lambda x: x[1])]
def vs_add(self, dset, field, vs_nm="id"):
if type(field)==types.StringType:
vs_dct = dict([[z[0], len(z)==2 and z[-1] or z[1:]] for z in dset])
self.g.vs[field] = [vs_dct[x] for x in self.g.vs[vs_nm]]
elif type(field)==types.ListType:
for i,fld in enumerate(field):
try:
vs_dct = dict([[z[0], z[1+i]] for z in dset])
self.g.vs[fld] = [vs_dct[x] for x in self.g.vs[vs_nm]]
except:
print z
def es_add(self, dset, field):
for i,fld in enumerate(field):
self.g.es[fld] = [x[i] for x in dset]
def vs_cent_label(self, filt, label, number=1, size=5):
self.g.vs["prank"] = self.g.pagerank(damping=0.95, directed=False)
centLst = []
for x in set(self.g.vs[filt]):
filter_list = sorted([self.g.vs["prank"][j] for j,y in enumerate(self.g.vs[filt]) if x==y], reverse=True)
if len(filter_list)>=size:
centLst.append([x, [number, (lambda j,y: j==1 and [y[0]] or y[:j])(number, filter_list)]])
centDct = dict(centLst)
labLst = []
for i,x in enumerate(self.g.vs[filt]):
labLst.append("")
if x in centDct:
if centDct[x][0]>0:
if self.g.vs["prank"][i] in centDct[x][1]:
centDct[x][0] = centDct[x][0] - 1
labLst[-1] = self.g.vs[label][i]
self.g.vs["label"] = labLst
def vs_color(self, field, graph=True, rand=True):
asgCnt = sorted([[x, self.g.vs[field].count(x)] for x in set(self.g.vs[field])], reverse=True, key=lambda(x): x[1])
if rand: col = random.sample(colors, len(colors))
else: col = colors
def hexIt():
return hex(int(256*random.random()))[-2:].replace("x", "0")
asgDct = dict([[x[0], (i<len(col)) and col[i][1] or colGrad("#FFFFFF", "#%s%s%s" % (hexIt(), hexIt(), hexIt()), 35)] for i,x in enumerate(asgCnt)])
self.g.vs["color"] = [x=="" and "#F8F8F8" or asgDct[x] for x in self.g.vs[field]]
def es_sel(self, varN, ge=None, le=None, eq=None):
if ge!=None and le!=None:
exec("sub = self.g.es(%s_ge=%s, %s_le=%s);" % (varN, ge, varN, le))
elif ge!=None:
exec("sub = self.g.es(%s_ge=%s);" % (varN, ge))
elif le!=None:
exec("sub = self.g.es(%s_le=%s);" % (varN, le))
elif eq!=None:
exec("sub = self.g.es(%s_eq=%s);" % (varN, eq))
z = [x.tuple[0] for x in sub]
z.extend([x.tuple[1] for x in sub])
g = self.g.subgraph(list(set(z)))
if ge!=None:
exec("g.delete_edges(%s_lt=%s);" % (varN, ge))
if le!=None:
exec("g.delete_edges(%s_gt=%s);" % (varN, le))
if eq!=None:
exec("g.delete_edges(%s_ne=%s);" % (varN, eq))
return g
def __repr__(self):
return "%s" % summary(self.g)
def component(self, num=1, debug=False):
mem = self.g.clusters().membership
if debug:
print "Members: %s" % (max(mem)+1)
if num<1:
num=1
elif num>max(mem)+1:
num = max(mem)+1
com = [[mem.count(x), x] for x in range(0, max(mem)+1)]
com.sort(reverse=True)
if debug:
print [x[0] for x in com[num-1: min(len(com), num+4)]]
return self.g.clusters().subgraph(com[num-1][1])
def component_attrib(self, var_name="component"):
mem = self.g.clusters().membership
com = [[mem.count(x), x] for x in range(0, max(mem)+1)]
com.sort(reverse=True)
com = [[x[1], i] for i,x in enumerate(com)]
com.sort()
self.g.vs[var_name] = [com[x][1] for x in mem]
def neighborhood(self, vx, order=1):
listed = []
for i in range(0, order):
for num in vx:
listed.extend([num])
listed.extend(self.g.neighbors(num))
vx = list(set(listed))
return senGraph(self.g.subgraph(vx))
def __KML_rng(self, lst, scale):
return min(lst), scale/(max(lst)-min(lst))
def __KML_eDt(self, edgeDict, x):
if x[0] in edgeDict:
if x[1] not in edgeDict[x[0]]:
edgeDict[x[0]].append(x[1])
else:
edgeDict[x[0]] = [x[1]]
return edgeDict
def KML(self, output=None, color="color", layout="layout",
defColor="#63B8FF", scale=[25., 15.], edgeDraw=True):
KMLstr = ""
if not(layout in self.g.vs.attribute_names()):
self.g.vs[layout] = self.g.layout("KK")
## fcol = color in self.g.vs.attribute_names() and list(set([x.upper() for x in self.g.vs[color]])) or [defColor]
## for x in fcol:
## KMLstr = """%s
## <Style id="col%s"><IconStyle><Icon>
## <href>http://140.247.116.250/mptest.py/image2?c0=%s&r=75</href>
## </Icon></IconStyle></Style>""" % (KMLstr, x[1:].upper(), x[1:].upper())
KMLstr = """%s
<Style id="line"><LineStyle>
<color>#88aaaaaa</color>
<width>1</width>
</LineStyle></Style>""" % (KMLstr)
#Determine ranges
if scale!=None:
xSc = self.__KML_rng([x[0] for x in self.g.vs[layout]], scale[0])
ySc = self.__KML_rng([x[1] for x in self.g.vs[layout]], scale[1])
else:
xSc = [0, 1]
ySc = [0, 1]
if edgeDraw:
edgeDict = {}
for x in self.g.get_edgelist():
edgeDict = self.__KML_eDt(edgeDict, list(x))
edgeDict = self.__KML_eDt(edgeDict, list(reversed(x)))
for k,x in edgeDict.iteritems():
linestr = ""
for y in x:
linestr = "%s%f,%f %f,%f " % (linestr,
xSc[1]*(self.g.vs["layout"][k][0]-xSc[0]),
ySc[1]*(self.g.vs["layout"][k][1]-ySc[0]),
xSc[1]*(self.g.vs["layout"][y][0]-xSc[0]),
ySc[1]*(self.g.vs["layout"][y][1]-ySc[0]))
KMLstr = """%s
<Placemark>
<styleUrl>#line</styleUrl>
<LineString>
<coordinates>%s</coordinates>
</LineString>
</Placemark>""" % (KMLstr, linestr.strip())
for i,x in enumerate(self.g.vs):
col = color in self.g.vs.attribute_names() and x[color][1:] or defColor[1:]
KMLstr = """%s
<Placemark>
<name>#%d</name>
<description>%s</description>
<Style>
<IconStyle>
<Icon>
<href>http://140.247.116.250/mptest.py/image2?c0=%s&r=%d</href>
</Icon>
</IconStyle>
</Style>
<Point><coordinates>%f,%f</coordinates></Point>
</Placemark>""" % (KMLstr,
i, x["name"], col, x["size"],
xSc[1]*(x["layout"][0]-xSc[0]),
ySc[1]*(x["layout"][1]-ySc[0]))
## KMLstr = """%s
## <Style id="Marker%d"><IconStyle><Icon>
## <href>http://140.247.116.250/mptest.py/image2?c0=%s&r=%d</href>
## </Icon></IconStyle></Style>
## <Placemark>
## <name>Placemark %d</name>
## <description>%s</description>
## <styleUrl>#Marker%d</styleUrl>
## <Point><coordinates>%f,%f</coordinates></Point>
## </Placemark>""" % (KMLstr,
## i, col, x["size"], i, x["name"], i,
## xSc[1]*(x["layout"][0]-xSc[0]),
## ySc[1]*(x["layout"][1]-ySc[0]))
## KMLstr = """%s
## <Placemark>
## <name>Placemark %d</name>
## <description>%s</description>
## <styleUrl>#col%s</styleUrl>
## <Point><coordinates>%f,%f</coordinates></Point>
## </Placemark>""" % (KMLstr, i,
## x["name"], col.upper(),
## xSc[1]*(x["layout"][0]-xSc[0]),
## ySc[1]*(x["layout"][1]-ySc[0]))
return """
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>%s</name>
<description>%s</description>
%s
</Document>
</kml>""" % ("", "", KMLstr)
class senDB:
def __init__(self, table, bbox=None, db="MySQL", fname=None, dbconfig={}, eCnt=250):
#delete from vertex where lat is null or lng is null or state in ('GU', 'HI', 'AK', 'PR', 'VI');
#create table e_state as select h, t, count(*) as cnt from (select a.State as h, b.State as t from vertex as a inner join vertex as b where a.state < b.state and a.Patent=b.Patent) as tbl group by h,t;
#create table v_state as select state, lat, lng, count(*) as cnt from vertex group by state
if db=="MySQL":
import MySQLdb
conn = MySQLdb.connect(passwd=dbconfig["passwd"], db=dbconfig["db"], host=dbconfig["host"], user=dbconfig["user"])
c = conn.cursor()
if bbox==None:
c.execute("SELECT * FROM v_%s" % table)
else:
c.execute("SELECT %s, lat, lng, count(*) as cnt FROM %s GROUP BY %s" %
(table[0], "vertex WHERE lat>%f AND lng>%f AND lat<%f AND lng<%f" % tuple(bbox), table[0]))
self.vList = c.fetchall()
self.vlst = [x[0] for x in c.description] #column names
self.vlst.pop(0)
if bbox==None:
c.execute("SELECT * FROM e_%s LIMIT %d" % (table, eCnt))
else:
c.execute("SELECT h%s AS h, t%s AS t, count(*) as cnt FROM edge WHERE %s AND %s GROUP BY h%s, t%s" % \
(table[1], table[1],
"tLat>%f AND tLng>%f AND tLat<%f AND tLng<%f" % tuple(bbox),
"hLat>%f AND hLng>%f AND hLat<%f AND hLng<%f" % tuple(bbox),
table[1], table[1]))
self.eList = c.fetchall()
self.elst = [x[0] for x in c.description]
self.elst.pop(0)
c.close()
conn.close()
class senTab:
def __init__(self, csv_file=""):
##print "Note: First row in CSV must contain filed names"
self.recs = 0
self.files = 0
self.sTab = {}
if csv_file!="":
self.addCsv(csv_file)
def addCsv(self, csv_file):
senv = csv.reader(open(csv_file))
senv = [x for x in senv]
headers = senv[0]
for i,x in enumerate(senv[0]):
if x not in self.sTab:
self.sTab[x] = ["" for y in range(0, self.recs)]
self.sTab[x].extend([y[i] for y in senv[1:]])
self.recs = self.recs + len(senv) - 1
#the basic disambiguation, name ONLY
def au_dis1(self, tag="AU"):
damg = sorted([[x.upper(),i] for i,x in enumerate(self.sTab[tag])])
order = [x[1] for x in damg]
dlist = [[x[0]] for x in damg]
inum = 0
dlist[0].append(0)
for i in range(1, len(dlist)):
if dlist[i][0]!=dlist[i-1][0]:
inum = inum + 1
dlist[i].append(inum)
self.sTab["InvID"] = [x[1] for x in sorted([[order[i], dlist[i][-1]] for i in range(0, len(dlist))])]
#more advanced disambiguation, implementing FUZZY
def au_dis2(self, tag="AU", jaro=0.95):
conn = sqlite3.connect(":memory:")
conn.create_function("jarow", 2, invComp)
conn.create_function("invXMtch", 1, invXMtch)
conn.create_aggregate("uQvals", 1, uQvals)
damg = [[x[0], x[0][:3], x[1], i] for i,x in enumerate(sorted([[x.upper(),i] for i,x in enumerate(self.sTab[tag])]))]
c = conn.cursor()
quickSQL(c, damg, "author0")
c.executescript("""
CREATE TABLE author1 AS
SELECT v0, v1, v2, min(v3) as v3 FROM author0 GROUP BY v0;
CREATE INDEX au_ ON author1 (v1);
CREATE TABLE author2 AS
SELECT a.v0 AS h, b.v0 AS t, a.v3 AS numH, b.v3 AS numT, jarow(a.v0, b.v0) AS jaro
FROM author1 AS a
INNER JOIN author1 AS b
ON a.v1=b.v1 and a.v3<b.v3
WHERE jaro>%s;
CREATE TABLE author3 (numT INTEGER, numH INTEGER, t VARCHAR, h VARCHAR, UNIQUE(numT));
INSERT OR REPLACE INTO author3
SELECT numT, min(numH) as numH, t, h
FROM author2
GROUP BY numT;
""" % str(jaro))
while 1==1:
c.executescript("""
DROP TABLE IF EXISTS author4;
CREATE TABLE author4 AS
SELECT a.numT, b.numH, a.t, a.h
FROM author3 AS a
INNER JOIN author3 AS b
ON b.numT = a.numH;
INSERT OR REPLACE INTO author3
SELECT * FROM author4;
""")
#keep self merging until no more to self merge
if c.execute("SELECT count(*) FROM author4").fetchone()[0]==0:
break;
#**this removes inventors that have clear mismatches
#EX. THOMAS, DW | THOMAS, D | THOMAS, DY
# Matches per THOMAS, D but DW <> DY
c.executemany("DELETE FROM author3 WHERE numH=?",
c.execute("""
SELECT numH
FROM author3
GROUP BY numH
HAVING invXMtch(uQvals(t))
""").fetchall())
#final "disambiguated"
c.executescript("""
CREATE TABLE author5 (inv VARCHAR, ord INTEGER, invID INTEGER, UNIQUE(ord));
INSERT OR REPLACE INTO author5
SELECT a.v0, a.v2, b.v3
FROM author0 AS a
INNER JOIN author1 AS b
ON a.v0 = b.v0;
INSERT OR REPLACE INTO author5
SELECT a.inv, a.ord, b.numH
FROM author5 AS a
INNER JOIN author3 AS b
ON a.invID = b.numT;
""")
self.sTab["InvID"] = [x[0] for x in c.execute("SELECT invID FROM author5 ORDER BY ord")]
c = None
conn = None
def csv_graph(self, vertex="InvID", edge="UT", vertex_lst=["AU"], vertex_agg=[], edge_lst=["TI", "JI", "PD", "PY", "SC", "TC"], output="wosc", index=True):
t = datetime.datetime.now()
print output
if vertex not in self.sTab:
self.au_dis2()
print " - disambg (%s)" % str(datetime.datetime.now()-t)
allF = [vertex]
allF.extend(vertex_lst)
allF.extend([edge])
allF.extend(edge_lst)
conn = sqlite3.connect(":memory:")
conn.create_aggregate("uQvals", 1, uQvals)
c = conn.cursor()
c.execute("CREATE TABLE AllData (%s, %s, %s, %s);" %
("%s INTEGER" % vertex, "%s VARCHAR" % " VARCHAR, ".join(vertex_lst),
"%s VARCHAR" % edge, "%s VARCHAR" % " VARCHAR, ".join(edge_lst)));
c.executemany("INSERT INTO AllData VALUES (%s)" % ", ".join(["?"]*(len(edge_lst)+len(vertex_lst)+1+1)),
[[self.sTab[x][i] for x in allF] for i in range(0, self.recs)])
if index:
c.executescript("""
CREATE INDEX IF NOT EXISTS ADve ON AllData (%s, %s);
CREATE INDEX IF NOT EXISTS ADvert ON AllData (%s);
CREATE INDEX IF NOT EXISTS ADedge ON AllData (%s);
""" % (vertex, edge, vertex, edge))
print " - Indices (%s)" % str(datetime.datetime.now()-t)
c.executescript("""
CREATE TABLE vertex AS
SELECT %s, %s, count(*) as cnt, uQvals(%s)
FROM AllData
GROUP BY %s;
""" % (vertex, len(vertex_agg)==0 and ",".join(vertex_lst) or ",".join(vertex_lst[:-len(vertex_agg)])+","+",".join(vertex_agg), vertex_lst[0], vertex))
self.csv_output(c, "vertex", output)
print " - vertex (%s)" % str(datetime.datetime.now()-t)
c.execute("""
CREATE TABLE edge AS
SELECT a.%s AS hID, b.%s AS tID, %s, a.%s
FROM AllData AS a
INNER JOIN AllData AS b
ON a.%s < b.%s and a.%s = b.%s;
""" % (vertex, vertex, "a.%s" % ", a.".join(edge_lst), edge,
vertex, vertex, edge, edge))
self.csv_output(c, "edge", output)
print " - edge (%s)" % str(datetime.datetime.now()-t)
self.csv_output(c, "alldata", output)
print " - Alldata (%s)" % str(datetime.datetime.now()-t)
self.vList = [list(x) for x in c.execute("SELECT %s, %s, cnt FROM vertex" % (vertex, ",".join(vertex_lst)))]
self.eList = [list(x) for x in c.execute("SELECT * FROM edge")]
#self.eListF = [list(x) for x in c.execute("SELECT * FROM edge")]
c = None
conn = None
self.vlst = vertex_lst
self.vlst.extend(["cnt"])
self.elst = ["numT", "numH"]
self.elst.extend(edge_lst)
self.elst.extend([edge])
def csv_output(self, c, table, output):
writer = csv.writer(open("%s_%s.csv" % (output, table), "wb"), lineterminator="\n")
writer.writerows([[x[1] for x in c.execute("PRAGMA TABLE_INFO(%s)" % table)]])
writer.writerows(c.execute("SELECT * FROM %s" % table).fetchall())
writer = None
def __repr__(self):
return "Recs: %d\nsTab Keys: (%d) %s" % (self.recs, len(self.sTab.keys()), str(self.sTab.keys()))
##r = senTab("websciences\wosc period 1.csv")
##r.csv_graph(output="wosc1")
##s = senGraph(r.eList)
##plot(s.component(2), layout="FR", vertex_label="")
##
##r = senTab("websciences\wosc pat 1.csv")
##r.csv_graph(vertex="invnum_N", vertex_lst=["name"],
## edge="patent", edge_lst=["loc", "assignee", "Description"],
## output="wscp1")
##s = senGraph(r.eList)
##plot(s.g, layout="FR", vertex_label="")