-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Morpher.cs
628 lines (572 loc) · 24 KB
/
Morpher.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using SIL.Extensions;
using SIL.Machine.Annotations;
using SIL.Machine.FeatureModel;
using SIL.Machine.Morphology.HermitCrab.MorphologicalRules;
using SIL.Machine.Rules;
using SIL.ObjectModel;
#if OUTPUT_ANALYSES
using System.IO;
#endif
#if !SINGLE_THREADED
using System.Collections.Concurrent;
using System.Threading.Tasks;
#endif
namespace SIL.Machine.Morphology.HermitCrab
{
public class Morpher : IMorphologicalAnalyzer, IMorphologicalGenerator
{
private readonly Language _lang;
private readonly IRule<Word, ShapeNode> _analysisRule;
private readonly IRule<Word, ShapeNode> _synthesisRule;
private readonly Dictionary<Stratum, RootAllomorphTrie> _allomorphTries;
private readonly ITraceManager _traceManager;
private readonly ReadOnlyObservableCollection<Morpheme> _morphemes;
private readonly IList<RootAllomorph> _lexicalPatterns = new List<RootAllomorph>();
public Morpher(ITraceManager traceManager, Language lang)
{
_lang = lang;
_traceManager = traceManager;
_allomorphTries = new Dictionary<Stratum, RootAllomorphTrie>();
var morphemes = new ObservableList<Morpheme>();
foreach (Stratum stratum in _lang.Strata)
{
var allomorphs = new HashSet<RootAllomorph>(stratum.Entries.SelectMany(entry => entry.Allomorphs));
var trie = new RootAllomorphTrie(ann => ann.Type() == HCFeatureSystem.Segment);
foreach (RootAllomorph allomorph in allomorphs)
{
if (allomorph.IsPattern)
_lexicalPatterns.Add(allomorph);
else
trie.Add(allomorph);
}
_allomorphTries[stratum] = trie;
morphemes.AddRange(stratum.Entries);
morphemes.AddRange(stratum.MorphologicalRules.OfType<AffixProcessRule>());
morphemes.AddRange(stratum.AffixTemplates.SelectMany(t => t.Slots).SelectMany(s => s.Rules).Distinct());
}
_analysisRule = lang.CompileAnalysisRule(this);
_synthesisRule = lang.CompileSynthesisRule(this);
MaxStemCount = 2;
MaxUnapplications = 0;
LexEntrySelector = entry => true;
RuleSelector = rule => true;
_morphemes = new ReadOnlyObservableCollection<Morpheme>(morphemes);
}
public ITraceManager TraceManager
{
get { return _traceManager; }
}
public int DeletionReapplications { get; set; }
public int MaxStemCount { get; set; }
/// <summary>
/// MaxUnapplications limits the number of unapplications to make it possible
/// to make it possible to debug words that take 30 minutes to parse
/// because there are too many unapplications.
/// </summary>
public int MaxUnapplications { get; set; }
public Func<LexEntry, bool> LexEntrySelector { get; set; }
public Func<IHCRule, bool> RuleSelector { get; set; }
public Language Language
{
get { return _lang; }
}
public IList<RootAllomorph> LexicalPatterns
{
get { return _lexicalPatterns; }
}
/// <summary>
/// Parses the specified surface form.
/// </summary>
public IEnumerable<Word> ParseWord(string word)
{
return ParseWord(word, out _, false);
}
public IEnumerable<Word> ParseWord(string word, out object trace)
{
return ParseWord(word, out trace, false);
}
/// <summary>
/// Parse the specified surface form, possibly tracing the parse.
/// If there are no analyses and guessRoot is true, then guess the root.
/// </summary>
public IEnumerable<Word> ParseWord(string word, out object trace, bool guessRoot)
{
// convert the word to its phonetic shape
Shape shape = _lang.SurfaceStratum.CharacterDefinitionTable.Segment(word);
var input = new Word(_lang.SurfaceStratum, shape);
input.Freeze();
if (_traceManager.IsTracing)
_traceManager.AnalyzeWord(_lang, input);
trace = input.CurrentTrace;
// Unapply rules
var analyses = new ConcurrentQueue<Word>(_analysisRule.Apply(input));
#if OUTPUT_ANALYSES
var lines = new List<string>();
foreach (Word w in analyses)
{
string shapeStr = w.ToString();
string rulesStr = string.Join(", ", w.MorphologicalRules.Select(r => r.Name));
lines.Add(string.Format("{0} : {1}", shapeStr, rulesStr));
}
File.WriteAllLines("analyses.txt", lines.OrderBy(l => l));
#endif
var origAnalyses = guessRoot ? analyses.ToList() : null;
var syntheses = Synthesize(word, analyses);
if (guessRoot && syntheses.Count() == 0)
{
// Guess roots when there are no results.
List<Word> matches = new List<Word>();
foreach (Word analysisWord in origAnalyses)
{
var lexicalGuesses = LexicalGuess(analysisWord).Distinct();
foreach (Word synthesisWord in lexicalGuesses)
{
foreach (Word validWord in _synthesisRule.Apply(synthesisWord).Where(IsWordValid))
{
if (IsMatch(word, validWord))
matches.Add(validWord);
}
}
}
matches.Sort((x, y) => y.Morphs.Count().CompareTo(x.Morphs.Count()));
return matches;
}
return syntheses;
}
/// <summary>
/// Generates surface forms from the specified word synthesis information.
/// </summary>
public IEnumerable<string> GenerateWords(
LexEntry rootEntry,
IEnumerable<Morpheme> otherMorphemes,
FeatureStruct realizationalFS
)
{
return GenerateWords(rootEntry, otherMorphemes, realizationalFS, out _);
}
public IEnumerable<string> GenerateWords(
LexEntry rootEntry,
IEnumerable<Morpheme> otherMorphemes,
FeatureStruct realizationalFS,
out object trace
)
{
Stack<Tuple<IMorphologicalRule, RootAllomorph>>[] rulePermutations = PermuteRules(otherMorphemes.ToArray())
.ToArray();
object rootTrace = _traceManager.IsTracing ? _traceManager.GenerateWords(_lang) : null;
trace = rootTrace;
var words = new ConcurrentBag<string>();
Exception exception = null;
Parallel.ForEach(
rootEntry.Allomorphs.SelectMany(
a => rulePermutations,
(a, p) => new { Allomorph = a, RulePermutation = p }
),
(synthesisInfo, state) =>
{
try
{
var synthesisWord = new Word(synthesisInfo.Allomorph, realizationalFS);
foreach (Tuple<IMorphologicalRule, RootAllomorph> rule in synthesisInfo.RulePermutation)
{
synthesisWord.MorphologicalRuleUnapplied(rule.Item1);
if (rule.Item2 != null)
synthesisWord.NonHeadUnapplied(new Word(rule.Item2, new FeatureStruct()));
}
synthesisWord.CurrentTrace = rootTrace;
if (_traceManager.IsTracing)
_traceManager.SynthesizeWord(_lang, synthesisWord);
synthesisWord.Freeze();
foreach (Word validWord in _synthesisRule.Apply(synthesisWord).Where(IsWordValid))
{
if (_traceManager.IsTracing)
_traceManager.Successful(_lang, validWord);
words.Add(validWord.Shape.ToString(_lang.SurfaceStratum.CharacterDefinitionTable, false));
}
}
catch (Exception e)
{
state.Stop();
exception = e;
}
}
);
if (exception != null)
throw exception;
return words.Distinct();
}
private IEnumerable<Stack<Tuple<IMorphologicalRule, RootAllomorph>>> PermuteRules(
Morpheme[] morphemes,
int index = 0
)
{
if (index == morphemes.Length)
{
yield return new Stack<Tuple<IMorphologicalRule, RootAllomorph>>();
}
else
{
if (morphemes[index] is LexEntry entry)
{
foreach (RootAllomorph allo in entry.Allomorphs)
{
foreach (
Stack<Tuple<IMorphologicalRule, RootAllomorph>> permutation in PermuteRules(
morphemes,
index + 1
)
)
{
permutation.Push(Tuple.Create((IMorphologicalRule)null, allo));
yield return permutation;
}
}
}
else
{
foreach (
Stack<Tuple<IMorphologicalRule, RootAllomorph>> permutation in PermuteRules(
morphemes,
index + 1
)
)
{
permutation.Push(Tuple.Create((IMorphologicalRule)morphemes[index], (RootAllomorph)null));
yield return permutation;
}
}
}
}
#if SINGLE_THREADED
private IEnumerable<Word> Synthesize(string word, IEnumerable<Word> analyses)
{
var matches = new HashSet<Word>(FreezableEqualityComparer<Word>.Default);
foreach (Word analysisWord in analyses)
{
foreach (Word synthesisWord in LexicalLookup(analysisWord))
{
foreach (Word validWord in _synthesisRule.Apply(synthesisWord).Where(IsWordValid))
{
if (IsMatch(word, validWord))
matches.Add(validWord);
}
}
}
return matches;
}
#else
private IEnumerable<Word> Synthesize(string word, ConcurrentQueue<Word> analyses)
{
var matches = new ConcurrentBag<Word>();
Exception exception = null;
Parallel.ForEach(
Partitioner.Create(0, analyses.Count),
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
(range, state) =>
{
try
{
for (int i = 0; i < range.Item2 - range.Item1; i++)
{
analyses.TryDequeue(out Word analysisWord);
foreach (Word synthesisWord in LexicalLookup(analysisWord))
{
foreach (Word validWord in _synthesisRule.Apply(synthesisWord).Where(IsWordValid))
{
if (IsMatch(word, validWord))
matches.Add(validWord);
}
}
}
}
catch (Exception e)
{
state.Stop();
exception = e;
}
}
);
if (exception != null)
throw exception;
return matches.Distinct(FreezableEqualityComparer<Word>.Default);
}
#endif
internal IEnumerable<RootAllomorph> SearchRootAllomorphs(Stratum stratum, Shape shape)
{
RootAllomorphTrie alloSearcher = _allomorphTries[stratum];
return alloSearcher.Search(shape).Distinct();
}
private IEnumerable<Word> LexicalLookup(Word input)
{
if (_traceManager.IsTracing)
_traceManager.LexicalLookup(input.Stratum, input);
foreach (
LexEntry entry in SearchRootAllomorphs(input.Stratum, input.Shape)
.Select(allo => allo.Morpheme)
.Cast<LexEntry>()
.Where(LexEntrySelector)
.Distinct()
)
{
foreach (RootAllomorph allomorph in entry.Allomorphs)
{
Word newWord = input.Clone();
newWord.RootAllomorph = allomorph;
if (_traceManager.IsTracing)
_traceManager.SynthesizeWord(_lang, newWord);
newWord.Freeze();
yield return newWord;
}
}
}
/// <summary>
/// Match the input against lexical patterns and return matches.
/// </summary>
private IEnumerable<Word> LexicalGuess(Word input)
{
if (_traceManager.IsTracing)
_traceManager.LexicalLookup(input.Stratum, input);
CharacterDefinitionTable table = input.Stratum.CharacterDefinitionTable;
IEnumerable<ShapeNode> shapeNodes = input.Shape.GetNodes(input.Range);
HashSet<string> shapeSet = new HashSet<string>();
foreach (RootAllomorph lexicalPattern in _lexicalPatterns)
{
IEnumerable<ShapeNode> shapePattern = lexicalPattern.Segments.Shape.GetNodes(
lexicalPattern.Segments.Shape.Range
);
foreach (List<ShapeNode> match in MatchNodesWithPattern(shapeNodes.ToList(), shapePattern.ToList()))
{
// Create a root allomorph for the guess.
string shapeString = match.ToString(table, false);
if (shapeSet.Contains(shapeString))
// Avoid duplicates caused by multiple paths through pattern (e.g. ([Seg])([Seg])).
continue;
shapeSet.Add(shapeString);
var root = new RootAllomorph(new Segments(table, shapeString)) { Guessed = true };
// Create a lexical entry to hold the root allomorph.
// (The root's Morpheme will point to the lexical entry.)
var lexEntry = new LexEntry
{
Id = shapeString,
SyntacticFeatureStruct = input.SyntacticFeatureStruct,
Gloss = shapeString,
Stratum = input.Stratum,
IsPartial = input.SyntacticFeatureStruct.IsEmpty
};
lexEntry.Allomorphs.Add(root);
// Point the root allomorph to the lexical pattern in FieldWorks.
if (lexicalPattern.Properties.ContainsKey("ID"))
root.Properties["ID"] = lexicalPattern.Properties["ID"];
if (lexicalPattern.Morpheme != null && lexicalPattern.Morpheme.Properties.ContainsKey("ID"))
root.Morpheme.Properties["ID"] = lexicalPattern.Morpheme.Properties["ID"];
// Create a new word that uses the root allomorph.
Word newWord = input.Clone();
newWord.RootAllomorph = root;
if (_traceManager.IsTracing)
_traceManager.SynthesizeWord(_lang, newWord);
newWord.Freeze();
yield return newWord;
}
}
}
/// <summary>
/// Match the shape nodes against the shape pattern.
/// This can produce multiple outputs if there is more than one path.
/// The outputs can be different because it unifies the nodes.
/// </summary>
public IEnumerable<List<ShapeNode>> MatchNodesWithPattern(
IList<ShapeNode> nodes,
IList<ShapeNode> pattern,
int n = 0,
int p = 0,
bool obligatory = false,
List<ShapeNode> prefix = null
)
{
var results = new List<List<ShapeNode>>();
if (prefix == null)
prefix = new List<ShapeNode>();
if (pattern.Count() == p)
{
if (nodes.Count() == n)
// We match because we are at the end of both the pattern and the nodes.
results.Add(prefix);
return results;
}
if (pattern[p].Annotation.Optional && !obligatory)
// Try skipping this item in the pattern.
results.AddRange(MatchNodesWithPattern(nodes, pattern, n, p + 1, false, prefix));
if (nodes.Count() == n)
{
// We fail to match because we are at the end of the nodes but not the pattern.
return results;
}
ShapeNode newNode = UnifyShapeNodes(nodes[n], pattern[p]);
if (newNode == null)
// We fail because the pattern didn't match the node here.
return results;
// Make a copy of prefix to avoid crosstalk and add newNode.
prefix = new List<ShapeNode>(prefix) { newNode };
if (pattern[p].Annotation.Iterative)
// Try using this item in the pattern again.
results.AddRange(MatchNodesWithPattern(nodes, pattern, n + 1, p, true, prefix));
// Try the remainder of the nodes against the remainder of the pattern.
results.AddRange(MatchNodesWithPattern(nodes, pattern, n + 1, p + 1, false, prefix));
return results;
}
ShapeNode UnifyShapeNodes(ShapeNode node, ShapeNode pattern)
{
FeatureStruct fs = null;
node.Annotation.FeatureStruct.Unify(pattern.Annotation.FeatureStruct, out fs);
if (fs == null)
return null;
if (fs.ValueEquals(node.Annotation.FeatureStruct))
return node;
return new ShapeNode(fs);
}
private bool IsWordValid(Word word)
{
if (
!word.RealizationalFeatureStruct.IsUnifiable(word.SyntacticFeatureStruct)
|| !word.IsAllMorphologicalRulesApplied
)
{
if (_traceManager.IsTracing)
_traceManager.Failed(_lang, word, FailureReason.PartialParse, null, null);
return false;
}
Feature feature = word.ObligatorySyntacticFeatures.FirstOrDefault(f =>
!ContainsFeature(
word.SyntacticFeatureStruct,
f,
new HashSet<FeatureStruct>(new ReferenceEqualityComparer<FeatureStruct>())
)
);
if (feature != null)
{
if (_traceManager.IsTracing)
_traceManager.Failed(_lang, word, FailureReason.ObligatorySyntacticFeatures, null, feature);
return false;
}
return word.Allomorphs.All(allo => allo.IsWordValid(this, word));
}
private bool IsMatch(string word, Word validWord)
{
if (_lang.SurfaceStratum.CharacterDefinitionTable.IsMatch(word, validWord.Shape))
{
if (_traceManager.IsTracing)
_traceManager.Successful(_lang, validWord);
return true;
}
else if (_traceManager.IsTracing)
{
_traceManager.Failed(_lang, validWord, FailureReason.SurfaceFormMismatch, null, word);
}
return false;
}
private bool ContainsFeature(FeatureStruct fs, Feature feature, ISet<FeatureStruct> visited)
{
if (visited.Contains(fs))
return false;
if (fs.ContainsFeature(feature))
return true;
if (fs.Features.OfType<ComplexFeature>().Any(cf => ContainsFeature(fs.GetValue(cf), feature, visited)))
return true;
return false;
}
public IEnumerable<WordAnalysis> AnalyzeWord(string word)
{
try
{
return ParseWord(word).Select(CreateWordAnalysis);
}
catch (InvalidShapeException)
{
return Enumerable.Empty<WordAnalysis>();
}
}
public IEnumerable<WordAnalysis> AnalyzeWord(string word, bool guessRoot)
{
try
{
return ParseWord(word, out _, guessRoot).Select(CreateWordAnalysis);
}
catch (InvalidShapeException)
{
return Enumerable.Empty<WordAnalysis>();
}
}
private WordAnalysis CreateWordAnalysis(Word result)
{
int rootMorphemeIndex = -1;
var morphemes = new List<IMorpheme>();
int i = 0;
foreach (Allomorph allo in result.AllomorphsInMorphOrder)
{
morphemes.Add(allo.Morpheme);
if (allo == result.RootAllomorph)
rootMorphemeIndex = i;
i++;
}
FeatureSymbol pos = result.SyntacticFeatureStruct.PartsOfSpeech().FirstOrDefault();
return new WordAnalysis(morphemes, rootMorphemeIndex, pos?.ID);
}
public IReadOnlyObservableCollection<IMorpheme> Morphemes
{
get { return _morphemes; }
}
public IEnumerable<string> GenerateWords(WordAnalysis wordAnalysis)
{
if (wordAnalysis.Morphemes.Count == 0)
return Enumerable.Empty<string>();
List<Morpheme> morphemes = wordAnalysis.Morphemes.Cast<Morpheme>().ToList();
var rootEntry = (LexEntry)morphemes[wordAnalysis.RootMorphemeIndex];
var realizationalFS = new FeatureStruct();
var results = new HashSet<string>();
foreach (
Stack<Morpheme> otherMorphemes in PermuteOtherMorphemes(
morphemes,
wordAnalysis.RootMorphemeIndex - 1,
wordAnalysis.RootMorphemeIndex + 1
)
)
{
results.UnionWith(GenerateWords(rootEntry, otherMorphemes, realizationalFS));
}
return results;
}
private IEnumerable<Stack<Morpheme>> PermuteOtherMorphemes(
List<Morpheme> morphemes,
int leftIndex,
int rightIndex
)
{
if (leftIndex == -1 && rightIndex == morphemes.Count)
{
yield return new Stack<Morpheme>();
}
else
{
if (rightIndex < morphemes.Count)
{
foreach (Stack<Morpheme> p in PermuteOtherMorphemes(morphemes, leftIndex, rightIndex + 1))
{
p.Push(morphemes[rightIndex]);
yield return p;
}
}
if (leftIndex > -1)
{
foreach (Stack<Morpheme> p in PermuteOtherMorphemes(morphemes, leftIndex - 1, rightIndex))
{
p.Push(morphemes[leftIndex]);
yield return p;
}
}
}
}
}
}