QNLP  v1.0
VerbGraph.py
Go to the documentation of this file.
1 
2 import networkx as nx
3 import numpy as np
4 
5 class VerbGraph:
6  """
7  Used to define subject/object noun ordering from a given verb.
8  Creates a left/right dict of nouns, wherein given a threshold,
9  verbs with respective nouns within that threshold on either side
10  can be thought of as subject (left) or object (right) for
11  bitstring state generation for encoding.
12  """
13  def __init__(self, verb = None, pos = []):
14  self.verb = verb
15  self.pos = pos
16  self.left_nouns = {}
17  self.right_nouns = {}
18  self.lr_nouns = {}
19 
20  def addL(self, noun, pos):
21  self.left_nouns.update({noun : pos})
22 
23  def addR(self, noun, pos):
24  self.right_nouns.update({noun : pos})
25 
26  def createLGraph(self, G = None):
27  v_idx = []
28  l_idx = []
29  if G == None:
30  G = nx.DiGraph()
31  G.add_node(self.verb)
32  v_idx = self.verb
33  for k,v in self.left_nouns.items():
34  G.add_node(k)
35  l_idx.append(k)
36  G.add_edge(k, self.verb)
37  return G, v_idx, l_idx
38 
39  def createRGraph(self, G = None):
40  v_idx = []
41  r_idx = []
42  if G == None:
43  G = nx.DiGraph()
44  G.add_node(self.verb)
45  v_idx = self.verb
46 
47  for k,v in self.right_nouns.items():
48  G.add_node(k)
49  r_idx.append(k)
50  G.add_edge(self.verb, k)
51  return G, v_idx, r_idx
52 
53  @staticmethod
54  def calc_verb_noun_pairings(corpus_list_v, corpus_list_n, dist_cutoff, max_terms=5):
55  v_list = []
56  for word_v, locations_v in corpus_list_v.items():
57 
58  if len(locations_v[1]) <= 1:
59  continue
60 
61  v = VerbGraph(word_v)
62  lv = locations_v[1][:, np.newaxis]
63  for word_n, locations_n in corpus_list_n.items():
64  dists = np.ndarray.flatten(locations_n[1] - lv)
65  if not isinstance(dists, np.int64):
66  vals = [x for x in dists if np.abs(x) <= dist_cutoff]
67  else:
68  vals = [dists] if np.abs(dists) <= dist_cutoff else []
69 
70  dl = [(i,i_pos) for i,i_pos in zip(vals, locations_n[1]) if i < 0]
71  dr = [(i,i_pos) for i,i_pos in zip(vals, locations_n[1]) if i > 0]
72 
73  if len(dl) >0:
74  v.addL(word_n, dl)
75  if len(dr) >0:
76  v.addR(word_n, dr)
77 
78  lr_dist = 0
79  for kl,vl in v.left_nouns.items():
80  for kr,vr in v.right_nouns.items():
81  lr_dist = vr[0][1] - vl[0][1]
82  if lr_dist < 2*dist_cutoff and lr_dist > 0: #>0 assumes correct left-right ordering
83  v.lr_nouns.update({(kl,kr) : lr_dist})
84  if len(v.left_nouns) >1 and len(v.right_nouns) >1 and len(v.lr_nouns) >1:
85  v_list.append(v)
86  return v_list
def createRGraph(self, G=None)
Definition: VerbGraph.py:39
def __init__(self, verb=None, pos=[])
Definition: VerbGraph.py:13
def calc_verb_noun_pairings(corpus_list_v, corpus_list_n, dist_cutoff, max_terms=5)
Definition: VerbGraph.py:54
def addL(self, noun, pos)
Definition: VerbGraph.py:20
def addR(self, noun, pos)
Definition: VerbGraph.py:23
def createLGraph(self, G=None)
Definition: VerbGraph.py:26