-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhybrid.py
executable file
·2975 lines (2485 loc) · 181 KB
/
hybrid.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
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
# -*- coding: utf-8 -*-
import codecs
import collections
import gc
import math
import multiprocessing
import nltk
import numpy
import os
import queue
import resource
import scipy
import string
import sys
import time
import util
def filter(parse_tree, adapted_non_terminal):
"""
Filter for sub parse trees
"""
return parse_tree.node == adapted_non_terminal.symbol()
def compute_E_log_stick_weights(telescope_1, telescope_2):
"""
Compute the aggregate digamma values, for phi update.
"""
assert (telescope_1.shape == telescope_2.shape)
psi_telescope_1 = scipy.special.psi(telescope_1)
psi_telescope_2 = scipy.special.psi(telescope_2)
psi_telescope_all = scipy.special.psi(telescope_1 + telescope_2)
aggregate_psi_nu_2_minus_psi_nu_all_k = numpy.cumsum(psi_telescope_2 - psi_telescope_all, axis=1)
E_leftover_stick_weight = aggregate_psi_nu_2_minus_psi_nu_all_k[:, -1]
aggregate_psi_nu_2_minus_psi_nu_all_k = numpy.hstack(
(numpy.zeros((telescope_1.shape[0], 1)), aggregate_psi_nu_2_minus_psi_nu_all_k[:, :-1]))
assert (aggregate_psi_nu_2_minus_psi_nu_all_k.shape == telescope_1.shape)
E_stick_weights = psi_telescope_1 - psi_telescope_all + aggregate_psi_nu_2_minus_psi_nu_all_k
assert numpy.all(E_stick_weights < 0), (E_stick_weights, E_stick_weights < 0, telescope_1, telescope_2)
return E_stick_weights, E_leftover_stick_weight
def compute_log_stick_weights(telescope_1, telescope_2):
"""
Compute the aggregate digamma values, for phi update.
"""
assert (telescope_1.shape == telescope_2.shape)
log_telescope_1 = numpy.log(telescope_1)
log_telescope_2 = numpy.log(telescope_2)
log_telescope_all = numpy.log(telescope_1 + telescope_2)
aggregate_log_nu_2_minus_log_nu_all_k = numpy.cumsum(log_telescope_2 - log_telescope_all, axis=1)
E_leftover_stick_weight = aggregate_log_nu_2_minus_log_nu_all_k[:, -1]
aggregate_log_nu_2_minus_log_nu_all_k = numpy.hstack(
(numpy.zeros((telescope_1.shape[0], 1)), aggregate_log_nu_2_minus_log_nu_all_k[:, :-1]))
assert (aggregate_log_nu_2_minus_log_nu_all_k.shape == telescope_1.shape)
E_stick_weights = log_telescope_1 - log_telescope_all + aggregate_log_nu_2_minus_log_nu_all_k
assert numpy.all(E_stick_weights < 0), (E_stick_weights, E_stick_weights < 0, telescope_1, telescope_2)
return E_stick_weights, E_leftover_stick_weight
def reverse_cumulative_sum_matrix_over_axis(matrix, axis):
cumulative_sum = numpy.zeros(matrix.shape)
(k, n) = matrix.shape
if axis == 1:
for j in range(n - 2, -1, -1):
cumulative_sum[:, j] = cumulative_sum[:, j + 1] + matrix[:, j + 1]
elif axis == 0:
for i in range(k - 2, -1, -1):
cumulative_sum[i, :] = cumulative_sum[i + 1, :] + matrix[i + 1, :]
return cumulative_sum
def retrieve_tokens_by_pre_order_traversal_of_adapted_non_terminal(production_list, adapted_non_terminal):
token_list = []
for candidate_production in production_list:
if isinstance(candidate_production, util.AdaptedProduction):
token_list += candidate_production.retrieve_tokens_of_adapted_non_terminal(adapted_non_terminal)
else:
continue
return token_list
'''
def sample_tree_by_pre_order_traversal(hybrid, current_hyper_node, input_string, adapted_sufficient_statistics=None, pcfg_sufficient_statistics=None):
if pcfg_sufficient_statistics!=None:
if current_hyper_node._node not in pcfg_sufficient_statistics:
pcfg_sufficient_statistics[current_hyper_node._node] = numpy.zeros((1, len(hybrid._gamma_index_to_pcfg_production_of_lhs[current_hyper_node._node])))
sampled_production, unsampled_hyper_nodes, log_probability_of_sampled_production = current_hyper_node.random_sample_derivation()
if isinstance(sampled_production, util.AdaptedProduction):
# if sampled production is an adapted production
assert (unsampled_hyper_nodes==None or len(unsampled_hyper_nodes)==0), "incomplete adapted production: %s" % sampled_production
#nu_index = self._active_adapted_production_to_nu_index_of_lhs[current_hyper_node._node][sampled_production]
#adapted_sufficient_statistics[current_hyper_node._node][0, nu_index] += 1
if adapted_sufficient_statistics!=None:
if sampled_production not in adapted_sufficient_statistics:
adapted_sufficient_statistics[sampled_production] = 0
adapted_sufficient_statistics[sampled_production] += 1
return [sampled_production]
elif isinstance(sampled_production, nltk.grammar.Production):
# if sampled production is an pcfg production
gamma_index = hybrid._pcfg_production_to_gamma_index_of_lhs[current_hyper_node._node][sampled_production]
if pcfg_sufficient_statistics!=None:
pcfg_sufficient_statistics[current_hyper_node._node][0, gamma_index] += 1
# if sampled production is a pre-terminal pcfg production
if unsampled_hyper_nodes==None or len(unsampled_hyper_nodes)==0:
assert (not hybrid.is_adapted_non_terminal(current_hyper_node._node)), "adapted pre-terminal found: %s" % current_hyper_node._node
return [sampled_production]
# if sampled production is a regular pcfg production
production_list = [sampled_production]
for unsampled_hyper_node in unsampled_hyper_nodes:
production_list += sample_tree_by_pre_order_traversal(hybrid, unsampled_hyper_node, input_string, adapted_sufficient_statistics, pcfg_sufficient_statistics)
# if current node is a non-adapted non-terminal node
if not hybrid.is_adapted_non_terminal(current_hyper_node._node):
return production_list
new_adapted_production = util.AdaptedProduction(current_hyper_node._node, input_string[current_hyper_node._span[0]:current_hyper_node._span[1]], production_list)
if adapted_sufficient_statistics!=None:
if new_adapted_production not in adapted_sufficient_statistics:
adapted_sufficient_statistics[new_adapted_production] = 0
adapted_sufficient_statistics[new_adapted_production] += 1
return [new_adapted_production]
else:
sys.stderr.write("Error in recognizing the production class %s @ checkpoint 2...\n" % sampled_production.__class__)
sys.exit()
'''
class Process_E_Step_dict(multiprocessing.Process):
def __init__(self,
task_queue,
hybrid,
# for training
adapted_sufficient_statistics_dict_queue=None,
new_adapted_sufficient_statistics_dict_queue=None,
pcfg_sufficient_statistics_dict_queue=None,
# for testing
retrieve_tokens_at_adapted_non_terminal=None,
result_output_path=None,
result_model_name=None,
number_of_samples=10
):
multiprocessing.Process.__init__(self)
self._task_queue = task_queue
self._hybrid = hybrid
self._number_of_samples = number_of_samples
# for training only
self._pcfg_sufficient_statistics_dict_queue = pcfg_sufficient_statistics_dict_queue
self._adapted_sufficient_statistics_dict_queue = adapted_sufficient_statistics_dict_queue
self._new_adapted_sufficient_statistics_dict_queue = new_adapted_sufficient_statistics_dict_queue
# for testing only
self._retrieve_tokens_at_adapted_non_terminal = retrieve_tokens_at_adapted_non_terminal
self._result_output_path = result_output_path
self._result_model_name = result_model_name
# @profile
def run(self):
E_log_stick_weights, E_log_theta = self._hybrid.propose_pcfg()
if self._result_output_path != None:
output_truth_file_stream = open(os.path.join(self._result_output_path, "%s.%s.avg.truth.%s" % (
self._retrieve_tokens_at_adapted_non_terminal, self._result_model_name, self.name)), 'w')
output_test_file_stream = open(os.path.join(self._result_output_path, "%s.%s.avg.test.%s" % (
self._retrieve_tokens_at_adapted_non_terminal, self._result_model_name, self.name)), 'w')
else:
pcfg_sufficient_statistics = {}
for non_terminal in E_log_theta:
pcfg_sufficient_statistics[non_terminal] = numpy.zeros(E_log_theta[non_terminal].shape)
adapted_sufficient_statistics = {}
for adapted_non_terminal in E_log_stick_weights:
adapted_sufficient_statistics[adapted_non_terminal] = numpy.zeros(
E_log_stick_weights[adapted_non_terminal].shape)
new_adapted_sufficient_statistics = {}
for adapted_non_terminal in E_log_stick_weights:
new_adapted_sufficient_statistics[adapted_non_terminal] = {}
while not self._task_queue.empty():
try:
(input_string, reference_string) = self._task_queue.get_nowait()
except queue.Empty:
continue
parsed_string = input_string.split()
root_node = self._hybrid.compute_inside_probabilities(E_log_stick_weights, E_log_theta, parsed_string)
for sample_index in range(self._number_of_samples):
if self._result_output_path is not None:
production_list = self._hybrid._sample_tree_process_dict(root_node, parsed_string)
retrieved_tokens = retrieve_tokens_by_pre_order_traversal_of_adapted_non_terminal(production_list,
self._retrieve_tokens_at_adapted_non_terminal)
output_truth_file_stream.write("%s\n" % (reference_string))
output_test_file_stream.write("%s\n" % (" ".join(retrieved_tokens)))
else:
production_list = self._hybrid._sample_tree_process_dict(root_node, parsed_string,
adapted_sufficient_statistics,
new_adapted_sufficient_statistics,
pcfg_sufficient_statistics)
del root_node
self._task_queue.task_done()
if self._result_output_path is not None:
output_truth_file_stream.close()
output_test_file_stream.close()
else:
self._adapted_sufficient_statistics_dict_queue.put(adapted_sufficient_statistics)
self._new_adapted_sufficient_statistics_dict_queue.put(new_adapted_sufficient_statistics)
self._pcfg_sufficient_statistics_dict_queue.put(pcfg_sufficient_statistics)
'''
(adapted_sufficient_statistics_mutex, new_adapted_sufficient_statistics_mutex, pcfg_sufficient_statistics_mutex) = self._sufficient_statistics_mutex
(adapted_sufficient_statistics_dict, new_adapted_sufficient_statistics_dict, pcfg_sufficient_statistics_dict) = self._sufficient_statistics_dict
adapted_sufficient_statistics_mutex.acquire()
try:
for adapted_non_terminal in adapted_sufficient_statistics:
temp_sufficient_statistics = self._adapted_sufficient_statistics_dict_queue[adapted_non_terminal]
#print "+++++ adapted +++++", self.name, adapted_non_terminal, adapted_sufficient_statistics[adapted_non_terminal].shape, temp_sufficient_statistics.shape
if temp_sufficient_statistics.shape!=adapted_sufficient_statistics[adapted_non_terminal].shape:
print temp_sufficient_statistics.shape, adapted_sufficient_statistics[adapted_non_terminal].shape
print temp_sufficient_statistics,
print adapted_sufficient_statistics[adapted_non_terminal]
temp_sufficient_statistics += adapted_sufficient_statistics[adapted_non_terminal]
self._adapted_sufficient_statistics_dict_queue[adapted_non_terminal] = temp_sufficient_statistics
finally:
adapted_sufficient_statistics_mutex.release()
new_adapted_sufficient_statistics_mutex.acquire()
try:
for adapted_non_terminal in new_adapted_sufficient_statistics:
#print "+++++ new-adapted +++++", self.name, adapted_non_terminal, len(new_adapted_sufficient_statistics[adapted_non_terminal])
temp_sufficient_statistics = self._new_adapted_sufficient_statistics_dict_queue[adapted_non_terminal]
for new_adapted_production in new_adapted_sufficient_statistics[adapted_non_terminal]:
if new_adapted_production not in temp_sufficient_statistics:
temp_sufficient_statistics[new_adapted_production] = 0
temp_sufficient_statistics[new_adapted_production] += new_adapted_sufficient_statistics[adapted_non_terminal][new_adapted_production]
self._new_adapted_sufficient_statistics_dict_queue[adapted_non_terminal] = temp_sufficient_statistics
finally:
new_adapted_sufficient_statistics_mutex.release()
pcfg_sufficient_statistics_mutex.acquire()
try:
for non_terminal in pcfg_sufficient_statistics:
#print "+++++ pcfg +++++", self.name, non_terminal, pcfg_sufficient_statistics[non_terminal].shape
temp_sufficient_statistics = self._pcfg_sufficient_statistics_dict_queue[non_terminal]
temp_sufficient_statistics += pcfg_sufficient_statistics[non_terminal]
self._pcfg_sufficient_statistics_dict_queue[non_terminal] = temp_sufficient_statistics
finally:
pcfg_sufficient_statistics_mutex.release()
'''
class Process_E_Step_queue(multiprocessing.Process):
def __init__(self,
task_queue,
hybrid,
E_log_theta,
E_log_stick_weights,
result_queue_adapted_sufficient_statistics=None,
result_queue_pcfg_sufficient_statistics=None,
retrieve_tokens_at_adapted_non_terminal=None,
result_output_path=None,
result_model_name=None,
number_of_samples=10
):
multiprocessing.Process.__init__(self)
self._task_queue = task_queue
self._hybrid = hybrid
self._number_of_samples = number_of_samples
self._E_log_theta = E_log_theta
self._E_log_stick_weights = E_log_stick_weights
# for training only
self._result_queue_pcfg_sufficient_statistics = result_queue_pcfg_sufficient_statistics
self._result_queue_adapted_sufficient_statistics = result_queue_adapted_sufficient_statistics
# for testing only
# self._result_queue_production_list = result_queue_production_list
self._retrieve_tokens_at_adapted_non_terminal = retrieve_tokens_at_adapted_non_terminal
self._result_output_path = result_output_path
self._result_model_name = result_model_name
# @profile
def run(self):
if self._result_output_path is not None:
output_truth_file_stream = open(os.path.join(self._result_output_path, "%s.%s.avg.truth.%s" % (
self._retrieve_tokens_at_adapted_non_terminal, self._result_model_name, self.name)), 'w')
output_test_file_stream = open(os.path.join(self._result_output_path, "%s.%s.avg.test.%s" % (
self._retrieve_tokens_at_adapted_non_terminal, self._result_model_name, self.name)), 'w')
while not self._task_queue.empty():
try:
(input_string, reference_string) = self._task_queue.get_nowait()
except queue.Empty:
continue
parsed_string = input_string.split()
root_node = self._hybrid.compute_inside_probabilities(self._E_log_stick_weights, self._E_log_theta,
parsed_string)
for sample_index in range(self._number_of_samples):
if self._result_output_path is not None:
production_list = self._hybrid._sample_tree_process_queue(root_node, parsed_string)
retrieved_tokens = retrieve_tokens_by_pre_order_traversal_of_adapted_non_terminal(production_list,
self._retrieve_tokens_at_adapted_non_terminal)
output_truth_file_stream.write("%s\n" % (reference_string))
output_test_file_stream.write("%s\n" % (" ".join(retrieved_tokens)))
else:
production_list = self._hybrid._sample_tree_process_queue(root_node, parsed_string,
self._result_queue_adapted_sufficient_statistics,
self._result_queue_pcfg_sufficient_statistics)
self.model_state_assertion()
del root_node
self._task_queue.task_done()
if self._result_output_path is not None:
output_truth_file_stream.close()
output_test_file_stream.close()
class Hybrid(object):
def __init__(self,
start_symbol,
pcfg_productions,
adapted_non_terminals,
number_of_samples=10
):
self._number_of_samples = number_of_samples
self._start_symbol = start_symbol
self._adapted_non_terminals = set(adapted_non_terminals)
self._non_terminals = set(pcfg_production.lhs() for pcfg_production in pcfg_productions)
self._terminals = set()
for pcfg_production in pcfg_productions:
self._terminals |= set(pcfg_production.rhs()) - self._non_terminals
print("terminals:", " ".join(self._terminals))
print("non-terminals:", self._non_terminals)
print("adapted non-terminal:", self._adapted_non_terminals)
assert (self._non_terminals.isdisjoint(self._terminals))
assert (self._adapted_non_terminals.isdisjoint(self._terminals))
assert (self._adapted_non_terminals.issubset(self._non_terminals))
self._pcfg_productions = collections.defaultdict(set)
self._number_of_productions = 0
self._number_of_productions_prime = 0
self._lhs_to_pcfg_production = collections.defaultdict(set)
self._rhs_to_pcfg_production = collections.defaultdict(set)
self._lhs_rhs_to_pcfg_production = collections.defaultdict()
self._rhs_to_unary_pcfg_production = collections.defaultdict(set)
self._gamma_index_to_pcfg_production_of_lhs = collections.defaultdict(collections.defaultdict)
self._pcfg_production_to_gamma_index_of_lhs = collections.defaultdict(collections.defaultdict)
for pcfg_production in pcfg_productions:
# make sure all pcfg production is in CNF
assert (len(pcfg_production.rhs()) >= 1 and len(pcfg_production.rhs()) <= 2)
lhs_node = pcfg_production.lhs()
rhs_nodes = pcfg_production.rhs()
self._pcfg_productions[(lhs_node, rhs_nodes)].add(pcfg_production)
self._lhs_rhs_to_pcfg_production[(lhs_node, rhs_nodes)] = pcfg_production
self._lhs_to_pcfg_production[lhs_node].add(pcfg_production)
self._rhs_to_pcfg_production[rhs_nodes].add(pcfg_production)
if len(rhs_nodes) == 1:
self._rhs_to_unary_pcfg_production[rhs_nodes[0]].add(pcfg_production)
self._gamma_index_to_pcfg_production_of_lhs[lhs_node][
len(self._gamma_index_to_pcfg_production_of_lhs[lhs_node])] = pcfg_production
self._pcfg_production_to_gamma_index_of_lhs[lhs_node][pcfg_production] = len(
self._pcfg_production_to_gamma_index_of_lhs[lhs_node])
topology_order, order_topology = self._topological_sort()
self._incremental_build_up = False
self._non_terminal_to_level = topology_order
self._level_to_non_terminal = order_topology
self._ordered_adaptor_top_down = []
for x in range(len(order_topology)):
for non_terminal in order_topology[x]:
if non_terminal in self._adapted_non_terminals:
self._ordered_adaptor_top_down.append(non_terminal)
self._ordered_adaptor_down_top = self._ordered_adaptor_top_down[::-1]
print("adaptors in top-down order:", self._ordered_adaptor_top_down)
def _initialize(self,
number_of_strings,
batch_size,
tau=1.,
kappa=0.5,
alpha_pi=None,
beta_pi=None,
alpha_theta=None,
truncation_level=None,
reorder_interval=10,
table_relabel_interval=500,
table_relabel_iterations=100,
sufficient_statistics_scale=0,
# pcfg_rhs_scale_coefficient=10
):
self._number_of_strings = number_of_strings
self._batch_size = batch_size
self._counter = 0
self._tau = tau
self._kappa = kappa
self._epsilon = pow(self._tau + self._counter, -self._kappa)
self._reorder_interval = reorder_interval
self._table_relabel_iterations = 500 // batch_size
self._table_relabel_interval = table_relabel_interval
self._initial_table_relable = False
self._alpha_theta = {}
if alpha_theta == None:
for non_terminal in self._non_terminals:
# self._alpha_theta[non_terminal] = numpy.ones((1, len(self._gamma_index_to_pcfg_production_of_lhs[non_terminal]))) / 10
self._alpha_theta[non_terminal] = numpy.ones(
(1, len(self._gamma_index_to_pcfg_production_of_lhs[non_terminal]))) / len(
self._gamma_index_to_pcfg_production_of_lhs[non_terminal])
# self._alpha_theta[non_terminal] = 1. / len(self._gamma_index_to_pcfg_production_of_lhs[non_terminal])
self._gamma = {}
self._pcfg_sufficient_statistics_of_lhs = {}
self._pcfg_production_usage_counts_of_lhs = {}
for non_terminal in self._non_terminals:
self._gamma[non_terminal] = numpy.ones(
(1, len(self._gamma_index_to_pcfg_production_of_lhs[non_terminal]))) / len(
self._gamma_index_to_pcfg_production_of_lhs[non_terminal])
# self._gamma[non_terminal] = numpy.ones((1, len(self._gamma_index_to_pcfg_production_of_lhs[non_terminal]))) / 10
# for gamma_index in xrange(len(self._gamma_index_to_pcfg_production_of_lhs[non_terminal])):
# self._gamma[non_terminal][0, gamma_index] *= len(self._gamma_index_to_pcfg_production_of_lhs[non_terminal][gamma_index].rhs())
self._pcfg_sufficient_statistics_of_lhs[non_terminal] = numpy.zeros(
(1, len(self._gamma_index_to_pcfg_production_of_lhs[non_terminal])))
self._pcfg_production_usage_counts_of_lhs[non_terminal] = numpy.zeros(
(1, len(self._gamma_index_to_pcfg_production_of_lhs[non_terminal])), dtype=int)
'''
# TODO: scale the thetas
for pcfg_production in self._pcfg_production_to_gamma_index_of_lhs[non_terminal]:
gamma_index = self._pcfg_production_to_gamma_index_of_lhs[non_terminal][pcfg_production]
self._alpha_theta[non_terminal][0, gamma_index] *= pcfg_rhs_scale_coefficient**(len(pcfg_production.rhs())-1)
self._gamma[non_terminal][0, gamma_index] *= pcfg_rhs_scale_coefficient**(len(pcfg_production.rhs())-1)
#print self._alpha_theta[non_terminal], self._gamma[non_terminal]
'''
if truncation_level is None:
truncation_level = {}
for adapted_non_terminal in self._ordered_adaptor_top_down[::-1]:
truncation_level[adapted_non_terminal] = 1000
self._truncation_level = truncation_level
assert (len(self._truncation_level) == len(self._adapted_non_terminals))
print("desired_truncation_level:", self._truncation_level)
if sufficient_statistics_scale <= 0:
self._ranking_statistics_scale = 1.0 / pow(self._tau, -self._kappa)
# self._ranking_statistics_scale = 1.0
self._lhs_rhs_to_active_adapted_production = collections.defaultdict(set)
self._lhs_to_active_adapted_production = collections.defaultdict(set)
self._rhs_to_active_adapted_production = collections.defaultdict(set)
if alpha_pi is None:
alpha_pi = {}
for adapted_non_terminal in self._adapted_non_terminals:
alpha_pi[adapted_non_terminal] = 1e3
self._alpha_pi = alpha_pi
assert (len(self._alpha_pi) == len(self._adapted_non_terminals))
print("alpha_pi:", self._alpha_pi)
if beta_pi is None:
beta_pi = {}
for adapted_non_terminal in self._adapted_non_terminals:
beta_pi[adapted_non_terminal] = 0
self._beta_pi = beta_pi
assert (len(self._beta_pi) == len(self._adapted_non_terminals))
print("beta_pi:", self._beta_pi)
self._nu_1 = {}
self._nu_2 = {}
self._nu_index_to_active_adapted_production_of_lhs = {}
self._active_adapted_production_to_nu_index_of_lhs = {}
self._active_adapted_production_sufficient_statistics_of_lhs = {}
self._active_adapted_production_usage_counts_of_lhs = {}
self._active_adapted_production_length_of_lhs = {}
for adapted_non_terminal in self._adapted_non_terminals:
self._nu_index_to_active_adapted_production_of_lhs[adapted_non_terminal] = {}
self._active_adapted_production_to_nu_index_of_lhs[adapted_non_terminal] = {}
self._nu_1[adapted_non_terminal] = numpy.ones(
(1, len(self._nu_index_to_active_adapted_production_of_lhs[adapted_non_terminal])))
self._nu_2[adapted_non_terminal] = numpy.ones(
(1, len(self._nu_index_to_active_adapted_production_of_lhs[adapted_non_terminal]))) * self._alpha_pi[
adapted_non_terminal]
self._active_adapted_production_sufficient_statistics_of_lhs[adapted_non_terminal] = numpy.zeros(
(1, len(self._nu_index_to_active_adapted_production_of_lhs[adapted_non_terminal])))
self._active_adapted_production_usage_counts_of_lhs[adapted_non_terminal] = numpy.zeros(
(1, len(self._nu_index_to_active_adapted_production_of_lhs[adapted_non_terminal])), dtype=int)
self._active_adapted_production_length_of_lhs[adapted_non_terminal] = numpy.zeros(
(1, len(self._nu_index_to_active_adapted_production_of_lhs[adapted_non_terminal])), dtype=int)
# self._adapted_production_sufficient_statistics_of_lhs[adapted_non_terminal] = nltk.probability.FreqDist()
# self._adapted_production_usage_freqdist = collections.defaultdict(nltk.probability.FreqDist)
self._adapted_production_usage_freqdist = nltk.probability.FreqDist()
self._adapted_production_dependents_of_adapted_production = collections.defaultdict(set)
self._adapted_production_sufficient_statistics_of_lhs = collections.defaultdict(nltk.probability.FreqDist)
def _topological_sort(self):
dag = collections.defaultdict(set)
# unlinked_nodes[self._start_symbol] = set()
unlinked_nodes = set()
unlinked_nodes.add(self._start_symbol)
while (len(unlinked_nodes) > 0):
candidate_node = unlinked_nodes.pop()
for candidate_pcfg_production in self.get_pcfg_productions(lhs=candidate_node):
for non_terminal in candidate_pcfg_production.rhs():
if not isinstance(non_terminal, nltk.grammar.Nonterminal):
continue
if non_terminal == candidate_node:
continue
dag[candidate_node].add(non_terminal)
unlinked_nodes.add(non_terminal)
topology_ordering = {}
ordering_topology = collections.defaultdict(set)
topology_ordering[self._start_symbol] = 0
ordering_topology[0].add(self._start_symbol)
unprocessed_nodes = [(self._start_symbol, 0)]
while len(unprocessed_nodes) > 0:
(unprocessed_node, depth) = unprocessed_nodes.pop(0)
for child_node in dag[unprocessed_node]:
if child_node in topology_ordering:
# topology_ordering[child_node] = min(depth+1, topology_ordering[child_node])
topology_ordering[child_node] = max(depth + 1, topology_ordering[child_node])
ordering_topology[max(depth + 1, topology_ordering[child_node])].add(child_node)
else:
topology_ordering[child_node] = depth + 1
ordering_topology[depth + 1].add(child_node)
unprocessed_nodes.append((child_node, topology_ordering[child_node]))
print("topological ordering is:", topology_ordering)
return topology_ordering, ordering_topology
def propose_pcfg(self):
E_log_stick_weights = {}
E_log_left_over_stick_weights = {}
for adapted_non_terminal in self._adapted_non_terminals:
if len(self._nu_index_to_active_adapted_production_of_lhs[adapted_non_terminal]) <= 0:
E_log_stick_weights[adapted_non_terminal] = numpy.zeros(
(1, len(self._nu_index_to_active_adapted_production_of_lhs[adapted_non_terminal])))
E_log_left_over_stick_weights[adapted_non_terminal] = 0
else:
E_log_stick_weights[adapted_non_terminal], E_log_left_over_stick_weights[
adapted_non_terminal] = compute_E_log_stick_weights(self._nu_1[adapted_non_terminal],
self._nu_2[adapted_non_terminal])
# E_log_stick_weights[adapted_non_terminal], E_log_left_over_stick_weights[adapted_non_terminal] = compute_log_stick_weights(self._nu_1[adapted_non_terminal], self._nu_2[adapted_non_terminal])
assert E_log_stick_weights[adapted_non_terminal].shape == (
1, len(self._nu_index_to_active_adapted_production_of_lhs[adapted_non_terminal])), (
adapted_non_terminal, len(self._nu_index_to_active_adapted_production_of_lhs[adapted_non_terminal]),
E_log_stick_weights[adapted_non_terminal].shape,
E_log_left_over_stick_weights[adapted_non_terminal].shape)
E_log_theta = {}
for non_terminal in self._non_terminals:
E_log_theta[non_terminal] = scipy.special.psi(self._gamma[non_terminal]) - scipy.special.psi(
numpy.sum(self._gamma[non_terminal]))
assert (E_log_theta[non_terminal].shape == (
1, len(self._gamma_index_to_pcfg_production_of_lhs[non_terminal])))
if self.is_adapted_non_terminal(non_terminal):
E_log_theta[non_terminal] += E_log_left_over_stick_weights[non_terminal]
return E_log_stick_weights, E_log_theta
def compute_inside_probabilities(self, E_log_stick_weights, E_log_theta, input_sequence, sentence_root=None,
candidate_adaptors=None):
# E_log_stick_weights, E_log_theta = self.propose_pcfg()
if candidate_adaptors is None:
candidate_adaptors = self._adapted_non_terminals
sequence_length = len(input_sequence)
root_and_position_to_node = collections.defaultdict(dict)
position_and_root_to_node = collections.defaultdict(dict)
for span in range(1, sequence_length + 1):
for i in range(sequence_length - span + 1):
j = i + span
for non_terminal in self._non_terminals:
lhs = non_terminal
# find the adapted production that spans over i to j
if non_terminal in candidate_adaptors:
# print self._active_adapted_production_to_nu_index_of_lhs[non_terminal]
candidate_adapted_productions = self.get_adapted_productions(lhs=non_terminal,
rhs=tuple(input_sequence[i:j]))
for candidate_adapted_production in candidate_adapted_productions:
nu_index = self._active_adapted_production_to_nu_index_of_lhs[lhs][
candidate_adapted_production]
# this is to prevent searching new sampled rules
if nu_index >= E_log_stick_weights[lhs].shape[1]:
continue
if (i, j) not in root_and_position_to_node[lhs]:
hyper_node = util.HyperNode(lhs, (i, j))
root_and_position_to_node[lhs][(i, j)] = hyper_node
position_and_root_to_node[(i, j)][lhs] = hyper_node
# print("checkpoint a", candidate_adapted_production)
root_and_position_to_node[lhs][(i, j)].add_new_derivation(candidate_adapted_production,
E_log_stick_weights[lhs][
0, nu_index],
hyper_nodes=None)
# find the pcfg productions
candidate_pcfg_productions = self.get_pcfg_productions(lhs=non_terminal, rhs=None)
for candidate_pcfg_production in candidate_pcfg_productions:
# make sure all pcfg production is in CNF
# assert(len(candidate_pcfg_production.rhs())==1 or len(candidate_pcfg_production.rhs())==2)
rhs_0 = candidate_pcfg_production.rhs()[0]
gamma_index = self._pcfg_production_to_gamma_index_of_lhs[lhs][candidate_pcfg_production]
if len(candidate_pcfg_production.rhs()) == 1:
if span == 1:
if rhs_0 == input_sequence[i:j][0]:
# this is a terminal initialization rule, otherwise, we don't consider
hyper_node = util.HyperNode(lhs, (i, j))
# print("checkpoint b", candidate_pcfg_production)
hyper_node.add_new_derivation(candidate_pcfg_production,
E_log_theta[lhs][0, gamma_index], hyper_nodes=None)
root_and_position_to_node[lhs][(i, j)] = hyper_node
position_and_root_to_node[(i, j)][lhs] = hyper_node
else:
continue
else:
continue
elif len(candidate_pcfg_production.rhs()) == 2:
if rhs_0 not in root_and_position_to_node:
continue
rhs_1 = candidate_pcfg_production.rhs()[1]
assert (self.is_non_terminal(rhs_1))
if rhs_1 in root_and_position_to_node:
for k in range(i + 1, j):
if (i, k) not in root_and_position_to_node[rhs_0]:
continue
if (k, j) not in root_and_position_to_node[rhs_1]:
continue
if (i, j) not in root_and_position_to_node[lhs]:
hyper_node = util.HyperNode(lhs, (i, j))
root_and_position_to_node[lhs][(i, j)] = hyper_node
position_and_root_to_node[(i, j)][lhs] = hyper_node
log_probability = E_log_theta[lhs][0, gamma_index] + \
root_and_position_to_node[rhs_0][
(i, k)]._accumulated_log_probability + \
root_and_position_to_node[rhs_1][
(k, j)]._accumulated_log_probability
# print("checkpoint c", candidate_pcfg_production)
root_and_position_to_node[lhs][(i, j)].add_new_derivation(candidate_pcfg_production,
log_probability, [
root_and_position_to_node[
rhs_0][(i, k)],
root_and_position_to_node[
rhs_1][(k, j)]])
# root_and_position_to_node[lhs][(i, j)].add_new_derivation(candidate_pcfg_production, E_log_theta[lhs][0, gamma_index], [root_and_position_to_node[rhs_0][(i, k)], root_and_position_to_node[rhs_1][(k, j)]])
else:
sys.stderr.write('Error: pcfg production not in CNF...\n')
sys.exit()
unary_node_set = set(position_and_root_to_node[(i, j)])
while len(unary_node_set) > 0:
non_terminal = unary_node_set.pop()
unary_productions = self.get_unary_pcfg_productions_by_rhs(rhs=non_terminal)
for unary_production in unary_productions:
if len(unary_production.rhs()) != 1:
continue
unary_node_set.add(unary_production.lhs())
lhs = unary_production.lhs()
rhs = unary_production.rhs()[0]
gamma_index = self._pcfg_production_to_gamma_index_of_lhs[lhs][unary_production]
if (i, j) not in root_and_position_to_node[lhs]:
hyper_node = util.HyperNode(lhs, (i, j))
root_and_position_to_node[lhs][(i, j)] = hyper_node
position_and_root_to_node[(i, j)][lhs] = hyper_node
log_probability = E_log_theta[lhs][0, gamma_index] + root_and_position_to_node[rhs][
(i, j)]._accumulated_log_probability
# print("checkpoint d", unary_production)
root_and_position_to_node[lhs][(i, j)].add_new_derivation(unary_production, log_probability, [
root_and_position_to_node[rhs][(i, j)]])
# root_and_position_to_node[lhs][(i, j)].add_new_derivation(unary_production, E_log_theta[lhs][0, gamma_index], [root_and_position_to_node[rhs][(i, j)]])
if sentence_root is None:
return root_and_position_to_node[self._start_symbol][(0, sequence_length)]
else:
assert isinstance(sentence_root, nltk.grammar.Nonterminal)
return root_and_position_to_node[sentence_root][(0, sequence_length)]
'''
def e_step_inference(self, input_strings, reference_strings, retrieve_tokens_at_adapted_non_terminal, output_path, model_name, number_of_samples=10):
assert(retrieve_tokens_at_adapted_non_terminal in self._adapted_non_terminals)
#if number_of_samples==None:
#number_of_samples = self._number_of_samples
output_average_truth_file = open(os.path.join(output_path, "%s.%s.avg.truth" % (retrieve_tokens_at_adapted_non_terminal, model_name)), 'w')
output_average_test_file = open(os.path.join(output_path, "%s.%s.avg.test" % (retrieve_tokens_at_adapted_non_terminal, model_name)), 'w')
#output_maximum_truth_file = open(os.path.join(output_path, "%s.%s.max.truth" % (retrieve_tokens_at_adapted_non_terminal, model_name)), 'w')
#output_maximum_test_file = open(os.path.join(output_path, "%s.%s.max.test" % (retrieve_tokens_at_adapted_non_terminal, model_name)), 'w')
pcfg_sufficient_statistics = {}
adapted_sufficient_statistics = {}
E_log_stick_weights, E_log_theta = self.propose_pcfg()
counter = 0
for (input_string, reference_string) in zip(input_strings, reference_strings):
retrieved_tokens_lists = nltk.probability.FreqDist()
#parsed_string = [ch for ch in input_string if ch not in string.whitespace]
parsed_string = input_string.split()
root_node = self.compute_inside_probabilities(E_log_stick_weights, E_log_theta, parsed_string, )
for sample_index in xrange(number_of_samples):
production_list = self._sample_tree(root_node, parsed_string, pcfg_sufficient_statistics, adapted_sufficient_statistics, inference_mode=True)
#production_list = sample_tree_by_pre_order_traversal(self, root_node, parsed_string, None, None)
#output_average_test_file.write("%s\n" % production_list)
retrieved_tokens = retrieve_tokens_by_pre_order_traversal_of_adapted_non_terminal(production_list, retrieve_tokens_at_adapted_non_terminal)
#retrieved_tokens_lists[input_string].append(" ".join(retrieved_tokens))
retrieved_tokens_lists.inc(" ".join(retrieved_tokens), 1)
assert(retrieved_tokens_lists.N()==number_of_samples)
maximum_tokens = retrieved_tokens_lists.max()
#output_maximum_truth_file.write("%s\n" % reference_string)
#output_maximum_test_file.write("%s\n" % maximum_tokens)
for average_tokens in retrieved_tokens_lists.samples():
for x in xrange(retrieved_tokens_lists[average_tokens]):
output_average_truth_file.write("%s\n" % reference_string)
output_average_test_file.write("%s\n" % average_tokens)
counter += 1
if counter % 5000 == 0:
print "processed %g%% data..." % (counter * 100.0 / len(input_strings))
return
'''
def e_step(self, input_strings, number_of_samples, inference_parameter=None):
if inference_parameter is None:
reference_strings = None
retrieve_tokens_at_adapted_non_terminal = None
output_path = None
model_name = None
else:
(reference_strings, retrieve_tokens_at_adapted_non_terminal, output_path, model_name) = inference_parameter
# assert retrieve_tokens_at_adapted_non_terminal in self._adapted_non_terminals, (
# retrieve_tokens_at_adapted_non_terminal, self._adapted_non_terminals)
assert len(input_strings) == len(reference_strings)
output_average_truth_file = open(
os.path.join(output_path, "%s.%s.avg.truth" % (retrieve_tokens_at_adapted_non_terminal, model_name)),
'w')
output_average_test_file = open(
os.path.join(output_path, "%s.%s.avg.test" % (retrieve_tokens_at_adapted_non_terminal, model_name)),
'w')
if inference_parameter is None:
pcfg_sufficient_statistics = {}
for non_terminal in self._non_terminals:
pcfg_sufficient_statistics[non_terminal] = numpy.zeros(
(1, len(self._gamma_index_to_pcfg_production_of_lhs[non_terminal])))
adapted_sufficient_statistics = {}
for adapted_non_terminal in self._adapted_non_terminals:
adapted_sufficient_statistics[adapted_non_terminal] = numpy.zeros(
(1, len(self._nu_index_to_active_adapted_production_of_lhs[adapted_non_terminal])))
else:
pcfg_sufficient_statistics = None
adapted_sufficient_statistics = None
log_likelihood = 0
E_log_stick_weights, E_log_theta = self.propose_pcfg()
# for input_string in input_strings:
for string_index in range(len(input_strings)):
input_string = input_strings[string_index]
parsed_string = input_string.split()
root_node = self.compute_inside_probabilities(E_log_stick_weights, E_log_theta, parsed_string)
self.model_state_assertion()
if inference_parameter is not None:
retrieved_tokens_lists = nltk.probability.FreqDist()
# sample_tree_clock = time.time()
for sample_index in range(number_of_samples):
production_list = self._sample_tree(root_node, parsed_string, pcfg_sufficient_statistics,
adapted_sufficient_statistics)
if inference_parameter is not None:
log_likelihood += self._compute_log_likelihood(production_list, E_log_stick_weights, E_log_theta)
'''
for sampled_production in production_list:
if isinstance(sampled_production, util.AdaptedProduction):
nu_index = self._active_adapted_production_to_nu_index_of_lhs[sampled_production.lhs()][sampled_production]
log_likelihood += E_log_stick_weights[sampled_production.lhs()][0, nu_index]
else:
gamma_index = self._pcfg_production_to_gamma_index_of_lhs[sampled_production.lhs()][sampled_production]
log_likelihood += E_log_theta[sampled_production.lhs()][0, gamma_index]
'''
retrieved_tokens = retrieve_tokens_by_pre_order_traversal_of_adapted_non_terminal(production_list,
retrieve_tokens_at_adapted_non_terminal)
retrieved_tokens_lists[" ".join(retrieved_tokens)] += 1
if inference_parameter is not None:
assert (retrieved_tokens_lists.N() == number_of_samples)
reference_string = reference_strings[string_index]
# for average_tokens in retrieved_tokens_lists.samples():
for average_tokens in retrieved_tokens_lists:
for x in range(retrieved_tokens_lists[average_tokens]):
output_average_truth_file.write("%s\n" % reference_string)
output_average_test_file.write("%s\n" % average_tokens)
if inference_parameter is None:
return pcfg_sufficient_statistics, adapted_sufficient_statistics
else:
log_likelihood -= numpy.log(number_of_samples)
print("Held-out likelihood of test data is %g..." % log_likelihood)
def _compute_log_likelihood(self, production_list, E_log_stick_weights, E_log_theta):
log_likelihood = 0
for sampled_production in production_list:
if isinstance(sampled_production, util.AdaptedProduction):
if sampled_production in self._active_adapted_production_to_nu_index_of_lhs[sampled_production.lhs()]:
nu_index = self._active_adapted_production_to_nu_index_of_lhs[sampled_production.lhs()][
sampled_production]
log_likelihood += E_log_stick_weights[sampled_production.lhs()][0, nu_index]
else:
log_likelihood += self._compute_log_likelihood(sampled_production.get_production_list(),
E_log_stick_weights, E_log_theta)
else:
gamma_index = self._pcfg_production_to_gamma_index_of_lhs[sampled_production.lhs()][sampled_production]
log_likelihood += E_log_theta[sampled_production.lhs()][0, gamma_index]
return log_likelihood
def _sample_tree(self, current_hyper_node, input_string, pcfg_sufficient_statistics=None,
adapted_sufficient_statistics=None):
assert (pcfg_sufficient_statistics is None and adapted_sufficient_statistics is None) or (
pcfg_sufficient_statistics is not None and adapted_sufficient_statistics is not None)
sampled_production, unsampled_hyper_nodes, log_probability_of_sampled_production = current_hyper_node.random_sample_derivation()
if isinstance(sampled_production, util.AdaptedProduction):
# if sampled production is an adapted production
assert (unsampled_hyper_nodes is None or len(
unsampled_hyper_nodes) == 0), "incomplete adapted production: %s" % sampled_production
nu_index = self._active_adapted_production_to_nu_index_of_lhs[current_hyper_node._node][sampled_production]
if adapted_sufficient_statistics is not None:
adapted_sufficient_statistics[current_hyper_node._node][0, nu_index] += 1
return [sampled_production]
elif isinstance(sampled_production, nltk.grammar.Production):
# if sampled production is an pcfg production
gamma_index = self._pcfg_production_to_gamma_index_of_lhs[current_hyper_node._node][sampled_production]
if pcfg_sufficient_statistics is not None:
pcfg_sufficient_statistics[current_hyper_node._node][0, gamma_index] += 1
# if sampled production is a pre-terminal pcfg production
if unsampled_hyper_nodes is None or len(unsampled_hyper_nodes) == 0:
assert (not self.is_adapted_non_terminal(
current_hyper_node._node)), "adapted pre-terminal found: %s" % current_hyper_node._node
return [sampled_production]
# if sampled production is a regular pcfg production
production_list = [sampled_production]
for unsampled_hyper_node in unsampled_hyper_nodes:
production_list += self._sample_tree(unsampled_hyper_node, input_string, pcfg_sufficient_statistics,
adapted_sufficient_statistics)
# if current node is a non-adapted non-terminal node
if not self.is_adapted_non_terminal(current_hyper_node._node):
return production_list
'''
# if current hyper-node is an adapted non-terminal, and sampled production is a pcfg production
for candidate_production in production_list:
if isinstance(candidate_production, util.AdaptedProduction):
nu_index = self._active_adapted_production_to_nu_index_of_lhs[candidate_production.lhs()][candidate_production]
adapted_sufficient_statistics[candidate_production.lhs()][0, nu_index] -= 1
elif isinstance(candidate_production, nltk.grammar.Production):
gamma_index = self._pcfg_production_to_gamma_index_of_lhs[candidate_production.lhs()][candidate_production]
pcfg_sufficient_statistics[candidate_production.lhs()][0, gamma_index] -= 1
else:
print "Error in recognizing the production @ checkpoint 1..."
'''
new_adapted_production = util.AdaptedProduction(
current_hyper_node._node,
input_string[current_hyper_node._span[0]:current_hyper_node._span[1]],
production_list)
if pcfg_sufficient_statistics is None and adapted_sufficient_statistics is None:
return [new_adapted_production]
if new_adapted_production not in self.get_adapted_productions(lhs=current_hyper_node._node, rhs=tuple(
input_string[current_hyper_node._span[0]:current_hyper_node._span[1]])):
# if this is an inactive adapted production
adapted_production_count = 0
pcfg_production_count = 0
for candidate_production in production_list:
if isinstance(candidate_production, util.AdaptedProduction):
adapted_production_count += 1
# print candidate_production.rhs(), len(candidate_production.rhs())
if len(candidate_production.rhs()) == 1:
print("skip singleton adapted production:", candidate_production)
continue
nu_index = self._active_adapted_production_to_nu_index_of_lhs[candidate_production.lhs()][
candidate_production]
# Warning: if you are using nltk 2.x, please use inc()
# self._adapted_production_usage_freqdist.inc(candidate_production, 1)
self._adapted_production_usage_freqdist[candidate_production] += 1
self._adapted_production_dependents_of_adapted_production[candidate_production].add(
new_adapted_production)
self._active_adapted_production_usage_counts_of_lhs[candidate_production.lhs()][
0, nu_index] += 1
elif isinstance(candidate_production, nltk.grammar.Production):
pcfg_production_count += 1
gamma_index = self._pcfg_production_to_gamma_index_of_lhs[candidate_production.lhs()][
candidate_production]
self._pcfg_production_usage_counts_of_lhs[candidate_production.lhs()][0, gamma_index] += 1
else:
sys.stderr.write("Error in recognizing the production @ checkpoint 1...\n")
sys.exit()
# activate this adapted rule
self._lhs_rhs_to_active_adapted_production[(current_hyper_node._node, tuple(
input_string[current_hyper_node._span[0]:current_hyper_node._span[1]]))].add(new_adapted_production)
self._lhs_to_active_adapted_production[current_hyper_node._node].add(new_adapted_production)
self._rhs_to_active_adapted_production[
tuple(input_string[current_hyper_node._span[0]:current_hyper_node._span[1]])].add(
new_adapted_production)