-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPanini.py
97 lines (80 loc) · 3.18 KB
/
Panini.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
import pynini as sandwich
def transducerOfRule(mapping, leftContext, rightContext, alphabet):
valid = sandwich.union(*alphabet).closure()
language = sandwich.union(*(['.'] + alphabet)).closure()
return sandwich.cdrewrite(sandwich.string_map(mapping),
leftContext,
rightContext,
language,
direction = "sim")*valid
def unionTransducer(listOfStuff): return sandwich.union(*listOfStuff)
def runForward(t,x,k = 1):
try:
return sandwich.shortestpath(sandwich.compose(x,t),nshortest = k).stringify()
except:
return None
def inputAcceptor(t):
return t.project(False)
def makeConstantTransducer(k):
return sandwich.transducer(language,k)
def parallelInversion(transducersAndOutputs, alphabet = None):
try:
a = [ sandwich.compose(y,sandwich.invert(t)).project(True) for y,t in transducersAndOutputs ]
a = reduce(sandwich.intersect,a)
if alphabet != None:
lm = sandwich.union(*alphabet).closure()
a = a*lm
a.topsort()
for s in a.states():
iterator = a.mutable_arcs(s)
while not iterator.done():
value = iterator.value()
#print value.olabel,value.ilabel,value.weight
assert value.olabel == value.ilabel
if value.olabel != 0:
value.weight = 1
iterator.set_value(value)
iterator.next()
return sandwich.shortestpath(a).stringify()
except:
# print "Got an exception in parallel inversion..."
# for y,t in transducersAndOutputs:
# print "inverting:"
# t = invert(t)
# print t
# print "composing:"
# t = compose(y,t)
# print t
# print "projecting:"
# t = project(True)
# print t
return None
if __name__ == '__main__':
alphabet = ['a','b','c','z']
if False:
language = sandwich.union(*(['.'] + alphabet)).closure()
deletionRule = sandwich.cdrewrite(string_map({'a': ''}),'b','',language,direction = "sim")
print runForward(deletionRule, 'bacbaa')
print shortestpath(compose('bbc',deletionRule),nshortest = 2).stringify()
r1 = transducerOfRule({'': 'z'}, '[BOS]', '', alphabet)*\
transducerOfRule({'a': ''},
sandwich.union('c','b'),
"",
alphabet)
r2 = transducerOfRule({'': 'z'}, '', '[EOS]', alphabet)*\
transducerOfRule({'a': ''},
sandwich.union("c","b"),
"",
alphabet)
# x*y is saying run x and then feed its output into y
if False:
m1 = transducerOfRule({'': 'a'},'','[EOS]',alphabet)
m2 = transducerOfRule({'': 'z'},'','[EOS]',alphabet)
print runForward(m1*m2,'ccc')
stem = 'bcab'
y1 = runForward(r1,stem)
y2 = runForward(r2,stem)
print y1,"~",y2
print runForward(r1,'bcb'),'~',runForward(r2,'bcb')
print parallelInversion([(y1,r1),
(y2,r2)])