/
ShakesEM.scala
1932 lines (1589 loc) · 57.6 KB
/
ShakesEM.scala
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ShakesEM is a package for running EM for Probabilistic Context Free Grammars,
* implemented in Scala using the Actors library to allow parallel processing
* over multiple machines and multiple cores. This version implements both
* vanilla EM and the modification to EM in Pereira and Schabes (1992) for
* partially bracketed corpora
*
* Copyright 2010 John K Pate
* Distributed under the GNU General Public License
*
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version. This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* @version 0.20_remote
* @author John K Pate
*/
package ShakesEM {
import scala.actors.Actor
import scala.actors.Actor._
import collection.immutable.{HashMap => IHashMap,HashSet => IHashSet}
import collection.mutable.{HashMap => MHashMap, HashSet => MHashSet}
case class NTExpansion(lhs:String,left:String,right:String)
case class NTRevChild( left:String,right:String )
case class NTRevParent( lhs:String,prob:Double )
case class TermExpansion( pos:String, word:String)
/**
* <code>ShakesPCNF</code> defines a Probabilistic Chomsky Normal Form grammar
* for use with the ShakesEM library
*/
@serializable class ShakesPCNF {
import math._
/**
* Used in re-estimation of the PCFG. f Sums estimated counts for binary
* branching nodes, g for unary branching nodes, and h for any non-terminal
* node.
* See Manning & Schutze p. 396.
* The defaults just make the incrementation code cleaner.
*/
val f = new MHashMap[NTExpansion,Double] {
override def default(exp:NTExpansion) = 0D
}
val g = new MHashMap[TermExpansion,Double] {
override def default(key:TermExpansion) = 0D
}
val h = new MHashMap[String,Double] {
override def default(key:String) = 0D
}
/////**
////* Re-estimates a PCFG based on the counts in f, g, and h. All the action of
////* this function lies in its side-effects.
////*/
////def reestimateRules {
//// f.keysIterator.foreach{ exp =>
//// val NTExpansion(lhs,_,_) = exp
//// phrases( exp ) =
//// 100000 * f(exp) /
//// h (lhs)
//// }
//// g.keysIterator.foreach{ exp =>
//// val TermExpansion( pos, _ ) = exp
//// lexicon ( exp ) =
//// 100000 * g( exp ) /
//// h(pos)
//// }
//// f.clear
//// g.clear
//// h.clear
//// normalize
//// preCalcExps
////}
def reestimateRules( p:(Double => Double) ) {
f.keysIterator.foreach{ exp =>
val NTExpansion(lhs,_,_) = exp
phrases( exp ) =
p( 100000 * f(exp) ) /
p( h (lhs) )
}
g.keysIterator.foreach{ exp =>
val TermExpansion( pos, _ ) = exp
lexicon ( exp ) =
p( 100000 * g( exp ) ) /
p( h(pos) )
}
f.clear
g.clear
h.clear
normalize
preCalcExps
}
def normalize {
val ntTotals = new MHashMap[String,Double] {
override def default( lhs:String ) = 0D
}
phrases.keysIterator.foreach{ exp =>
val NTExpansion( lhs, _, _ ) = exp
ntTotals ( lhs ) += phrases( exp )
}
phrases.keysIterator.foreach{ exp =>
val NTExpansion( lhs, _, _ ) = exp
phrases ( exp ) = phrases( exp ) / ntTotals(lhs)
}
ntTotals.clear
lexicon.keysIterator.foreach{ exp =>
val TermExpansion( pos, _ ) = exp
ntTotals( pos ) += lexicon( exp )
}
lexicon.keysIterator.foreach{ exp =>
val TermExpansion( pos, _ ) = exp
lexicon ( exp ) = lexicon( exp ) / ntTotals(pos)
}
}
def randomizeGrammar( nonTermCount:Int, termSymbols:List[String],
randSeed:Int, centeredOn:Int) {
import scala.util.Random
val nonTermSymbols = "S" :: (
( (1 to nonTermCount - 1) toList ) map ( "N" + _ )
)
val r = new Random( randSeed )
val allSymbols:List[String] = nonTermSymbols ::: termSymbols
for( lhs <- nonTermSymbols )
for( left <- allSymbols )
for( right <- allSymbols )
//phrases(lhs)(left)(right) = r.nextDouble + centeredOn
phrases( NTExpansion( lhs, left, right ) ) = r.nextDouble + centeredOn
for( pos <- nonTermSymbols )
for( word <- termSymbols )
lexicon( TermExpansion( pos, word ) ) = r.nextDouble + centeredOn
normalize
preCalcExps
}
var lexicon = new MHashMap[TermExpansion,Double] {
override def default( exp: TermExpansion ) = 0D
}
var lexExps = new MHashMap[String,List[NTRevParent]] {
override def default( word:String ) = Nil
}
var phrases = new MHashMap[ NTExpansion, Double] {
override def default(exp:NTExpansion) = 0D
}
var phrExps = new MHashMap[ NTRevChild, List[NTRevParent] ] {
override def default( key: NTRevChild ) = Nil
}
/**
* Reads a grammar from a file. Grammar should be in the format:
* <br/><br/>
* <code>parent left-child right-child probability</code>
* <br/><br/>
* and contain only binary rules.
*
* @param gramPath File path to the grammar (relative to current working
* directory)
*/
def readGrammar(gramPath:String) {
import scala.io.Source._
val lines = fromPath(gramPath).getLines("\n")
lines.foreach( line =>
if( line.length > 1 ) {
val fields = line.split(' ')
phrases (NTExpansion( fields(0), fields(1), fields(2))) += fields(3).toDouble
phrExps ( NTRevChild( fields(1), fields(2)) ) = NTRevParent(fields(0), fields(3).toDouble) ::
phrExps( NTRevChild(fields(1),fields(2)) )
}
)
}
/**
* Reads a lexicon from a file. Lexicon should be in the format:
* <br/><br/>
* <code>part-of-speech word probability</code>
* <br/><br/>
* and contain only unary rules.
*
* @param gramPath File path to the grammar (relative to current working
* directory)
*/
def readLexicon(lexPath:String) {
import scala.io.Source._
val lines = fromPath(lexPath).getLines("\n")
lines.foreach( line =>
if( line.length > 1 ) {
val fields = line.split(' ')
lexicon( TermExpansion(fields(0), fields(1)) ) += fields(2).toDouble
lexExps(fields(1)) = NTRevParent( fields(0), fields(2).toDouble ) ::
lexExps(fields(1))
}
)
}
/**
* Computes the value of phrExps on the basis of phrases and the value of
* lexExps on the basis of lexicon. Basically, keep these values in two forms
* to save computation time at the expense of space.
*/
def preCalcExps {
phrExps.clear
lexExps.clear
phrExps.clear
phrases.keysIterator.foreach{ exp =>
val NTExpansion( lhs, left, right ) = exp
phrExps( NTRevChild(left, right) ) =
NTRevParent(lhs, phrases( exp ))::
phrExps( NTRevChild(left, right) )
}
lexicon.keysIterator.foreach{ exp =>
val TermExpansion( pos, word ) = exp
lexExps(word) = NTRevParent(pos, lexicon( TermExpansion(pos,word))) ::
lexExps(word)
}
}
/**
* Returns a ShakesPCNF which has the same lexicon, phrases, lexExps, and
* phrExps but zero counts
*
* @return A ShakesPCNF with the same lexicon, phrases, lexExps, and phrExps
* as the ShakesPCNF calling the function, but with all zero counts.
*/
def countlessCopy:ShakesPCNF = {
val copy = new ShakesPCNF
phrases.keysIterator.foreach( exp =>
copy.phrases( exp ) += 0.0
)
lexicon.keysIterator.foreach{ exp =>
val TermExpansion( pos, word ) = exp
copy.lexicon( TermExpansion(pos, word)) += 0.0
}
copy.preCalcExps
copy
}
def copy:ShakesPCNF = {
val copy = new ShakesPCNF
copy.phrases = phrases
copy.lexicon = lexicon
copy.phrExps = phrExps
copy.lexExps = lexExps
copy
}
/**
* Produce a readable stringification of lexicon and phrases in the same
* format that readGrammar and readLexicon expect.
* @return A string representation of lexicon and phrases.
*/
override def toString =
phrases.keysIterator.map{ exp =>
val NTExpansion( lhs, left, right ) = exp
lhs + " " + left + " " + right + " " + phrases( exp )
}.mkString("Phrases:\n\t","\n\t","\n") +
lexicon.keysIterator.map{ exp =>
val TermExpansion( pos, word ) = exp
pos + " " + word + " " + " " + lexicon( exp )
}.mkString("Lexicon:\n\t","\n\t","")
}
// Use this to terminate parsers when we run out of sentences to give them.
case object Stop
case class RightHandSide(leftChild:String,rightChild:String)
case class Bracketing(leftSpanPoint:Int,rightSpanPoint:Int)
abstract class ToParse {
def size:Int
}
case class BracketedToParse(s:String,b:MHashSet[Bracketing]) extends ToParse {
def words = s.split(' ')
def size = words.size
}
case class StringToParse(s:String) extends ToParse {
def words = s.split(' ')
def size = words.size
}
/**
* This defines what a parser must have, without giving an explicit definition
* for certain functions we might want to change (such as re-estimation
* functions). This must be extended by providing at least the actual parsing
* functions synFill, lexFill, and populateChart. Other functions can of course
* be provided as well, for example computeOPWithEstimates to provide outside
* probability estimates.
*/
trait ShakesParser {
import math._
var parserID:ParserID
var g:ShakesPCNF
def firstStart:Unit // What happens when we first start?
// Remote actors register with the node
abstract class Entry(label:String) {
import collection.mutable.ArrayBuffer
import math._
/**
* Stored as a probability (not log-likelihoods) to reduce rounding error
* from exp and log over and over. Underflow is handled by scaling the
* probability of each word.
*/
var ip:Double = 1.0 // Initialization
/**
* Stored as a probability (not log-likelihoods) to reduce rounding error
* from exp and log over and over. Underflow is handled by scaling the
* probability of each word.
*/
var op:Double = 1.0 // initialization
var ipSetYet = false
var opSetYet = false
/**
* Keeps track of a node's children for the outside pass.
*/
var backMatcher = new ArrayBuffer[ArrayBuffer[RightHandSide]]
0 to (length-1) foreach( i => backMatcher += new ArrayBuffer[RightHandSide])
def size = backMatcher.size
var start = 0 // Init to something ridiculous for simplicity
var end = 0 // Init to something ridiculous for simplicity
def length = end - start + 1
val l = label
/**
* Get inside probability as a log-likelihood
* @return The inside probability of the node.
*/
def inScore = log(ip)
/**
* Get outside probability as a log-likelihood
* @return The outside probability of the node.
*/
def outScore = log(op)
/**
* Easily set the outside probability by providing a probability in
* log-space.
* @param x The amount (in log-space) to set the outside probability to.
*/
def setOPScore(x:Double)
{ opSetYet = true; op = exp(x) }
/**
* Easily increment the outside probability by providing a probability in
* log-space.
* @param x The amount (in log-space) to increment the outside probability by.
*/
def incOPScore(x:Double) {
if(!opSetYet)
setOPScore(x)
else
op = exp(x) + op
}
/**
* Easily set the outside probability by providing a probability not in
* log-space.
* @param x The amount to set the outside probability to.
*/
def setOPProb(x:Double)
{ opSetYet = true; op = x }
/**
* Easily increment the outside probability by providing a probability not
* in log-space.
* @param x The amount to increment the outside probability by.
*/
def incOPProb(x:Double) {
if(!opSetYet)
setOPProb(x)
else
op = x + op
}
/**
* Easily set the inside probability by providing a probability in
* log-space.
* @param x The amount (in log-space) to set the inside probability to.
*/
def setIPScore(x:Double)
{ ipSetYet = true; ip = exp(x) }
/**
* Easily increment the inside probability by providing a probability in
* log-space.
* @param x The amount (in log-space) to increment the inside probability by.
*/
def incIPScore(x:Double) {
if(!ipSetYet)
setIPScore(x)
else
ip = exp(x) + ip
}
/**
* Easily increment the inside probability by providing a probability not
* in log-space.
* @param x The amount to increment the inside probability by.
*/
def setIPProb(x:Double)
{ ipSetYet = true; ip = x }
/**
* Easily increment the inside probability by providing a probability not in
* log-space.
* @param x The amount to increment the inside probability by.
*/
def incIPProb(x:Double) {
if(! ipSetYet )
setIPProb(x)
else
ip = x + ip
}
/**
* Add a new expansion to the chart for Viterbi parsing. This is actually
* kind of hacky when adding a unary (terminal) expansion. This is absurdly
* inefficient, but good enough for now (and fast compared to the rest of
* the system)
*
* @param left The left child.
* @param right The right child.
* @param s The left index of the expansion span
* @param split The index of the split of the span
* @param e The right index of the expansion span
* @param prob The probability of the span
*/
def newVitExpansion(left:String,right:String,s:Int,split:Int,e:Int,prob:Double) {
if(end == 0) {
start = s
end = e
backMatcher = new ArrayBuffer[ArrayBuffer[RightHandSide]]
0 to (length-1) foreach( i =>
backMatcher += new ArrayBuffer[RightHandSide]
)
}
if( !ipSetYet | prob > ip ) {
backMatcher .clear
backMatcher = new ArrayBuffer[ArrayBuffer[RightHandSide]]
0 to (length-1) foreach( i =>
backMatcher += new ArrayBuffer[RightHandSide]
)
backMatcher( split - start ) += RightHandSide(left,right)
setIPProb( prob )
}
}
/**
* Add a new expansion to the chart. This is actually kind of hacky when
* adding a unary (terminal) expansion.
*
* @param left The left child.
* @param right The right child.
* @param s The left index of the expansion span
* @param split The index of the split of the span
* @param e The right index of the expansion span
* @param prob The probability of the span
*/
def newExpansion(left:String,right:String,s:Int,split:Int,e:Int,prob:Double) {
if(end == 0) {
start = s
end = e
backMatcher = new ArrayBuffer[ArrayBuffer[RightHandSide]]
0 to (length-1) foreach( i =>
backMatcher += new ArrayBuffer[RightHandSide]
)
}
backMatcher(split - start) += RightHandSide(left,right)
incIPProb( prob )
}
/**
* Return an entry to its initial state.
*/
def reset = {
ip = 0.0
op = 0.0
ipSetYet = false
opSetYet = false
0 to (length - 1) foreach( i => backMatcher +=
new ArrayBuffer[RightHandSide])
}
def viterbiString:String
}
/**
* Binary-branching non-terminal entries.
* @param label The label of the entry.
*/
case class SynEntry(label:String)
extends Entry(label) {
def viterbiString:String = {
import collection.mutable.ArrayBuffer
val spanInfo =
backMatcher.toArray.zipWithIndex.find( ! _._1.isEmpty ).toList.head
val spans:ArrayBuffer[RightHandSide] = spanInfo._1
val k = spanInfo._2
val RightHandSide(left:String,right:String) = spans(0)
"(" + label + " " +
chart(start)(start+k)(left) .viterbiString +
chart(start+k)(end)(right) .viterbiString +
")"
}
}
/**
* Unary-branching terminal entries.
* @param label The prt of spedch of the entry.
*/
case class LexEntry(label:String)
extends Entry(label) {
def viterbiString:String = {
backMatcher.toArray.zipWithIndex.find( !
_._1.isEmpty
).toList.head._1(0) match {
case RightHandSide(word,_) => "(" + label + " " + word + ")"
}
}
}
/**
* This is the chart itself.
*/
object chart {
//var triangMatrix = Array(Array(MHashMap[String,Entry]))
/**
* This is the data structure that stores the entries.
*/
var matrix = Array.fill( 0,0) (new collection.mutable.HashMap[String,Entry]{
override def default(s:String) = {
this += Pair( s, new SynEntry(s) )
this(s)
}
} )
/**
* Chart can be resized, which allows the same parser to parse sentences of
* different lengths. This is necessary so the same parser can parse
* multiple sentences without assuming a fixed upper bound on sentence
* length.
* @param chartSize The size of the chart.
*/
def resize(chartSize:Int) {
matrix = Array.fill( chartSize, chartSize )(
new collection.mutable.HashMap[String,Entry] {
override def default(s:String) = {
this += Pair( s, new SynEntry(s) )
this(s)
}
}
)
}
/**
* Access a hashmap of entries from the Chart
*
* @param n1 Start index of the span.
* @param n2 End index of the span.
* @return A hashmap of Entries over the span.
*/
def apply(n1:Int)(n2:Int) =
matrix(n1)(n2)
/**
* @return The size of the chart.
*/
def size = matrix.size
/**
* Stringify the chart.
* @return A human-readable(ish) string representation of the chart.
*/
override def toString =
matrix.map( i =>
Array.fill(matrix.size - i.length)( "<\t>\t").mkString("","","") +
i.map( j =>
"<" + {
if(j.isEmpty)
"\t"
else
j.keySet.map( k =>
k + ":" + String.format("%1.5f",
double2Double(j(k).ip)) +
"," + String.format("%1.5f",
double2Double(j(k).op))
).mkString("",",","")
} + ">"
).mkString("","\t","\n")
).mkString("","","\n")
}
/**
* @return The size of the chart
*/
def size = chart.size
/**
* @return The root cell of the chart
*/
def root = chart(0)( size - 1)
/**
* Resize the chart.
* @param sentLen The new size for the chart
*/
def resize(sentLen:Int) = chart.resize(sentLen)
/**
* Used in the CYK parser. Fills in one (non-terminal) span's worth of the
* chart.
* @param start The start index of the span.
* @param end The end index of the span.
*/
def synFill( start:Int, end:Int):Unit
var wordScale:Int// = wS
/**
* Used in the CYK parser. Fills in the parts-of-speech of a word.
* @param w The word.
* @param index The index of the word.
*/
def lexFill(w:String,index:Int):Unit
/**
* This is the CYK parsing algorithm. Same time complexity as Earley for
* completely ambiguous grammars, so (since we're doing full grammar
* induction) just use CYK. There's also a paper (Li and Alagappan something)
* suggesting it has better average-case space complexity for completely
* ambiguous grammars.
* @param s The input sentence (an array of terminals)
*/
def populateChart(s:Array[String]):Unit
/**
* @return The inside probability of the sentence, before de-scaling, and not
* in log-space.
*/
def scaledStringProb = chart(0)(size-1)("S").ip
/**
* @return The inside probability of the sentence not in log-space.
*/
def stringProb = scaledStringProb / pow( wordScale , size - 1 )
/**
* @return The inside probability of the sentence in log-space.
*/
def stringScore = log( stringProb )
/**
* Start at the root node and visit other nodes in a complete parse, making
* sure to visit a node only if all parent nodes are already visited, and
* apply a function to the entries of each node. Used for outside pass and
* gathering estimated counts. By allowing arbitrary functions of entries, we
* can change how we estimate a count easily; just call chartDescent but use
* a different estimation function.
* @param p The function to be applied
*/
def chartDescent( p: ( Entry => Unit ) ) = {
//import collection.mutable.{HashMap,HashSet}
if( chart(0)(chart.size - 1).contains("S") ) {
val toCompute = new MHashMap[(Int,Int),MHashSet[String]] {
override def default(key:(Int,Int)) = {
this += Pair(key, new MHashSet[String])
this(key)
}
}
toCompute(0, size - 1) += "S"
while( !toCompute.isEmpty) {
val(start,end) =
toCompute.keysIterator.foldLeft[(Int,Int)](0,0)( (a,b) =>
if( (a._2 - a._1) > (b._2 - b._1) ) a else b
)
val labels = toCompute( (start,end) )
toCompute -= Tuple2(start,end)
labels.foreach{ l =>
val rootCell = chart(start)(end)(l)
p( chart(start)(end)(l) )
(1 to (rootCell.backMatcher.length-1)).foreach{ split =>
val splitPoint = rootCell.start + split
rootCell.backMatcher(split).foreach{ children =>
children match {
case RightHandSide( left, right ) => {
if( splitPoint - rootCell.start > 1 ) {
toCompute( (rootCell.start, splitPoint)) += left
}
if( rootCell.end - splitPoint > 1) {
toCompute ( (splitPoint, rootCell.end) ) += right
}
}
case _ =>
}
}
}
}
}
}
}
}//end ShakesParser
@serializable case class F_Key(
start:Int,
end:Int,
lhs:String,
left:String,
right:String
)
@serializable case class G_Key(
index:Int,
pos:String,
word:String
)
@serializable case class H_Key(
start:Int,
end:Int,
label:String
)
trait EveryOneHundred {
var quietude = 100
}
trait EveryFive {
var quietude = 5
}
trait CountingDefinitions extends ShakesParser {
//import collection.immutable.HashMap
var quietude:Int
/**
* Compute the outside probability for one entry. Assumes that all referenced
* values are already computed.
* @param ent The entry to be scored.
*/
def computeOP(ent:Entry) {
import math._
List.range(0,ent.backMatcher.size - 1).foreach{ split =>
ent.backMatcher(split).foreach{ matches =>
matches match {
case RightHandSide( left, right ) => {
val splitPoint = split + ent.start
val ruleProb = g.phrases(NTExpansion(ent.l,left,right) )
val leftEnt = chart( ent.start )( splitPoint )( left )
val rightEnt = chart( splitPoint )( ent.end )( right )
val toAddLeft = ent.op * ruleProb * rightEnt.ip
leftEnt.incOPProb( toAddLeft )
val toAddRight = ent.op * ruleProb * leftEnt.ip
rightEnt.incOPProb( toAddRight )
}
}
}
}
}
/**
* Compute the outside probability for one entry and gather estimated counts
* based on the entry. Assumes that all referenced values are already
* computed.
* @param ent The entry to be scored and counted.
*/
def computeOPWithEstimates(ent:Entry) {
import math._
h_i += Pair( H_Key(ent.start,ent.end,ent.l), ent.op * ent.ip )
val f_toAdd = new MHashMap[ (String,String), Double] {
override def default(key:(String,String)) = 0D
}
(1 to (ent.backMatcher.size-1) ) foreach{ split =>
ent.backMatcher(split).foreach{ matches =>
val RightHandSide( left, right ) = matches
val ruleProb = g.phrases(NTExpansion(ent.l,left,right) )
val splitPoint = split + ent.start
val leftEnt = chart (ent.start) (splitPoint) (left)
val rightEnt = chart (splitPoint) (ent.end) (right)
leftEnt.incOPProb( ent.op * ruleProb * rightEnt.ip )
rightEnt.incOPProb( ent.op * ruleProb * leftEnt.ip )
if(leftEnt.end - leftEnt.start == 1) {
val RightHandSide( word, _ ) = leftEnt.backMatcher(0)(0)
g_i += Pair(
G_Key(leftEnt.start, leftEnt.l, word ),
leftEnt.ip * leftEnt.op
)
h_i += Pair(
H_Key( leftEnt.start, leftEnt.end, leftEnt.l),
leftEnt.ip * leftEnt.op
)
}
if(rightEnt.end - rightEnt.start == 1) {
val RightHandSide( word, _ ) = rightEnt.backMatcher(0)(0)
g_i += Pair(
G_Key(rightEnt.start, rightEnt.l, word ),
rightEnt.ip * rightEnt.op
)
h_i += Pair(
H_Key( rightEnt.start, rightEnt.end, rightEnt.l),
leftEnt.ip * leftEnt.op
)
}
val f_Summand =
ent.op * ruleProb * leftEnt.ip * rightEnt.ip
f_toAdd( (left,right) ) =
f_toAdd( (left,right) )+ f_Summand
}
}
f_toAdd .keysIterator.foreach{ k =>
val(left,right) = k
f_i( F_Key(ent.start,ent.end,ent.l,left,right) ) +=
f_toAdd(k)
}
}
/**
* This stores intermediate counts of binary-branching nodes for this sentence.
*/
@serializable val f_i = new MHashMap[F_Key,Double] {
override def default( key:F_Key ) = 0D
}
/**
* This stores intermediate counts of unary-branching nodes for this sentence.
*/
//var g_i = new IHashMap[(Int,String,String), Double] {
@serializable val g_i = new MHashMap[G_Key, Double] {
override def default( key:G_Key ) = 0D
}
/**
* This stores intermediate counts of non-terminal nodes for this sentence.
*/
@serializable val h_i = new MHashMap[H_Key, Double] {
override def default( key:H_Key ) = 0D
}
}
/**
* This provides all parsing functions. If we receive a bracketed sentence, use
* the brackets, otherwise do vanilla EM
*/
trait EstimationParser extends CountingDefinitions {
var g:ShakesPCNF
/**
* Fills in the parts-of-speech of a word.
* @param w The word.
* @param index The index of the word.
*/
def lexFill(w:String,index:Int) {
g.lexExps(w).foreach{ exp =>
val NTRevParent( pos, prob ) = exp
val l = new LexEntry(pos)
l.newExpansion(
w,w,
index,index,index+1,
wordScale * prob
)
chart(index)(index+1) += Pair( pos, l)
}
}
/**
* Fills in one (non-terminal) span's worth of the chart.
* @param start The start index of the span.
* @param end The end index of the span.
*/
def synFill( start:Int, end:Int) {
start+1 to (end-1) foreach{ k =>
chart(start)(k).keysIterator.foreach{ left =>
chart(k)(end).keysIterator.foreach{ right =>
g.phrExps( NTRevChild(left, right) ).foreach{ parent =>
val NTRevParent( lhs, expProb) = parent
val thisprob = expProb *
chart(start)(k)(left).ip *
chart(k)(end)(right).ip
chart(start)(end)(lhs).newExpansion(
left, right,
start,k,end,
thisprob
)
}
}
}
}
}
/*
* This is the CYK parsing algorithm. Same time complexity as Earley for
* completely ambiguous grammars, so (since we're doing full grammar
* induction) just use CYK. There's also a paper (Li and Alagappan something)
* suggesting it has better average-case space complexity for completely
* ambiguous grammars.
* @param s The input sentence (an array of terminals)
* @return A parse chart with labels and inside and outside probabilities.
*/
def populateChart(s:Array[String]) = {
1 to s.size foreach{ j =>
lexFill( s(j-1), j-1)
if( j > 1 )
((0 to (j-2)) reverse) foreach{ i =>
synFill(i, j)
}
}
chartDescent( computeOPWithEstimates )
}
var bracketing:MHashSet[Bracketing] = new MHashSet // Initialize to empty set