Repository navigation
Keep the final-template prune on in grammars with partial rules wherever no partial word can be involved #644
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
eee49b4
040930a
eeb63fa
df7f104
5b4dec2
d8a47dc
1dfe8fd
fe365e6
2952976
0896029
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using SIL.Machine.FeatureModel; | ||
| using SIL.Machine.Morphology.HermitCrab.MorphologicalRules; | ||
|
|
||
| namespace SIL.Machine.Morphology.HermitCrab | ||
| { | ||
| /// <summary> | ||
| /// Finds the affix templates that a partial word can reach in synthesis. A word is partial at a template only if a | ||
| /// partial affix-process rule that is neither a template-slot nor a clitic rule applied before it (a partial root | ||
| /// takes no template), in the template's stratum or an earlier one. Its part of speech is then whatever that rule | ||
| /// leaves, changed by any rules applied since. The search over-approximates: it tracks only the part-of-speech | ||
| /// feature, treats an unspecified or variable part of speech as every part of speech, ignores application counts, | ||
| /// rule order, template gating and every other feature, and lets every rule of a stratum apply any number of times. | ||
| /// A template it does not return can therefore never see a partial word. | ||
| /// </summary> | ||
| internal static class FinalTemplatePartialReachability | ||
| { | ||
| public static HashSet<AffixTemplate> Compute(Language lang) | ||
| { | ||
| var result = new HashSet<AffixTemplate>(); | ||
| SymbolicFeature posFeature = lang.SyntacticFeatureSystem.PartOfSpeechFeature; | ||
| HashSet<FeatureSymbol> all = | ||
| posFeature == null | ||
| ? new HashSet<FeatureSymbol>() | ||
| : new HashSet<FeatureSymbol>(posFeature.PossibleSymbols); | ||
|
|
||
| // Part-of-speech values a partial word may carry on leaving the strata processed so far. | ||
| var reach = new HashSet<FeatureSymbol>(); | ||
| bool anyPartial = false; | ||
| foreach (Stratum stratum in lang.Strata) // synthesis order | ||
| { | ||
| List<IMorphologicalRule> rules = stratum | ||
| .MorphologicalRules.Concat(stratum.AffixTemplates.SelectMany(t => t.Slots).SelectMany(s => s.Rules)) | ||
| .Distinct() | ||
| .ToList(); | ||
|
|
||
| foreach (AffixProcessRule rule in rules.OfType<AffixProcessRule>().Where(IsSynthesisPartial)) | ||
| { | ||
| anyPartial = true; | ||
| reach.UnionWith( | ||
| Apply(all, all, rule.RequiredSyntacticFeatureStruct, rule.OutSyntacticFeatureStruct) | ||
| ); | ||
| } | ||
| if (!anyPartial) | ||
| continue; | ||
| if (all.Count == 0) | ||
| { | ||
| // No parts of speech to tell templates apart: every later template is reachable. | ||
| result.UnionWith(stratum.AffixTemplates); | ||
| continue; | ||
| } | ||
|
|
||
| // Close the set under every rule of this stratum. | ||
| bool changed = true; | ||
| while (changed) | ||
| { | ||
| changed = false; | ||
| foreach (IMorphologicalRule rule in rules) | ||
| { | ||
| if (reach.Count == 0) | ||
| break; | ||
| IEnumerable<FeatureSymbol> next = ApplyRule(all, reach, rule); | ||
| foreach (FeatureSymbol symbol in next.ToList()) | ||
| changed |= reach.Add(symbol); | ||
| } | ||
| } | ||
|
|
||
| foreach (AffixTemplate template in stratum.AffixTemplates) | ||
| { | ||
| if (reach.Count == 0) | ||
| continue; | ||
| HashSet<FeatureSymbol> required = Constraint(all, template.RequiredSyntacticFeatureStruct); | ||
| if (required == null || required.Overlaps(reach)) | ||
| result.Add(template); | ||
| } | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| // Synthesis marks a word partial only for a non-template, non-clitic partial rule | ||
| // (SynthesisAffixProcessRule), and a slot or clitic rule is exempt from the final-template check. | ||
| internal static bool IsSynthesisPartial(AffixProcessRule rule) | ||
| { | ||
| return rule.IsPartial && !rule.IsTemplateRule && !rule.GetIsCliticRule(); | ||
| } | ||
|
|
||
| private static IEnumerable<FeatureSymbol> ApplyRule( | ||
| HashSet<FeatureSymbol> all, | ||
| HashSet<FeatureSymbol> input, | ||
| IMorphologicalRule rule | ||
| ) | ||
| { | ||
| switch (rule) | ||
| { | ||
| case AffixProcessRule apr: | ||
| return Apply(all, input, apr.RequiredSyntacticFeatureStruct, apr.OutSyntacticFeatureStruct); | ||
| case CompoundingRule cr: | ||
| return Apply(all, input, cr.HeadRequiredSyntacticFeatureStruct, cr.OutSyntacticFeatureStruct); | ||
| case RealizationalAffixProcessRule rr: | ||
| return Apply(all, input, rr.RequiredSyntacticFeatureStruct, rr.RealizationalFeatureStruct); | ||
| default: | ||
| // Unknown rule kind: assume it can produce any part of speech. | ||
| return all; | ||
| } | ||
| } | ||
|
|
||
| /// <summary>Unify with <paramref name="required"/>, then priority-union <paramref name="output"/>.</summary> | ||
| private static IEnumerable<FeatureSymbol> Apply( | ||
| HashSet<FeatureSymbol> all, | ||
| HashSet<FeatureSymbol> input, | ||
| FeatureStruct required, | ||
| FeatureStruct output | ||
| ) | ||
| { | ||
| HashSet<FeatureSymbol> req = Constraint(all, required); | ||
| bool applicable = req == null ? input.Count > 0 : req.Overlaps(input); | ||
| if (!applicable) | ||
| return Enumerable.Empty<FeatureSymbol>(); | ||
| HashSet<FeatureSymbol> outPos = Constraint(all, output); | ||
| if (outPos != null) | ||
| return outPos; | ||
| if (req == null) | ||
| return input; | ||
| return input.Where(req.Contains); | ||
| } | ||
|
|
||
| /// <summary>The part-of-speech values a feature structure allows, or null if it leaves them open.</summary> | ||
| private static HashSet<FeatureSymbol> Constraint(HashSet<FeatureSymbol> all, FeatureStruct fs) | ||
| { | ||
| if (fs == null) | ||
| return null; | ||
| if (!fs.TryGetValue(SyntacticFeatureSystem.PartOfSpeechID, out SymbolicFeatureValue value)) | ||
| return null; | ||
| if (value.IsVariable) | ||
| return null; | ||
| var symbols = new HashSet<FeatureSymbol>(value.Values); | ||
| // A value that names no known symbol is treated as unconstrained, to stay conservative. | ||
| return symbols.Count == 0 ? null : symbols; | ||
| } | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -68,6 +68,82 @@ public Morpher(ITraceManager traceManager, Language lang, int maxDegreeOfParalle | |
|
|
||
| _morphemes = new ReadOnlyObservableCollection<Morpheme>(morphemes); | ||
| HasPartialRules = GetPartialMorphemes().Any(morpheme => !(morpheme is LexEntry)); | ||
| if (HasPartialRules) | ||
| { | ||
| _partialReachableTemplates = FinalTemplatePartialReachability.Compute(lang); | ||
| _partialLookAhead = new PartialRuleLookAhead(lang); | ||
| // Only a final template can arm the prune, so without one nothing is tracked. | ||
| _canPruneFinalTemplates = lang | ||
| .Strata.SelectMany(s => s.AffixTemplates) | ||
| .Any(t => t.IsFinal && (_partialLookAhead.IsActive || !_partialReachableTemplates.Contains(t))); | ||
| _partialRules = lang | ||
| .Strata.SelectMany(s => | ||
| s.MorphologicalRules.Concat( | ||
| s.AffixTemplates.SelectMany(t => t.Slots).SelectMany(sl => sl.Rules) | ||
| ) | ||
| ) | ||
| .OfType<AffixProcessRule>() | ||
| .Where(FinalTemplatePartialReachability.IsSynthesisPartial) | ||
| .Distinct() | ||
| .ToList(); | ||
| } | ||
| } | ||
|
|
||
| private readonly HashSet<AffixTemplate> _partialReachableTemplates; | ||
| private readonly PartialRuleLookAhead _partialLookAhead; | ||
| private readonly bool _canPruneFinalTemplates; | ||
| private readonly IReadOnlyList<AffixProcessRule> _partialRules; | ||
|
|
||
| /// <summary> | ||
| /// Traces the drop of an analysis that still owes a partial rule as an unapplied | ||
| /// <see cref="FailureReason.OwedPartialCannotUnapply"/> template, with the partial rules as the failure | ||
| /// object. | ||
| /// </summary> | ||
| internal void TraceOwedPartialDropped(Word input) | ||
| { | ||
| if (_traceManager.IsTracing && input.OwedPartialTemplate != null) | ||
| { | ||
| _traceManager.EndUnapplyTemplate( | ||
| input.OwedPartialTemplate, | ||
| input, | ||
| false, | ||
| FailureReason.OwedPartialCannotUnapply, | ||
| _partialRules | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Whether analysis records the template state: the prune is on, or some final template can be pruned in a | ||
| /// grammar with partial rules. Otherwise the state would only split equivalent analyses. | ||
| /// </summary> | ||
| internal bool TracksFinalTemplateState => | ||
| !HasPartialRules || AlwaysEnforceFinalTemplates || _canPruneFinalTemplates; | ||
|
|
||
| /// <summary> | ||
| /// Whether analysis may refuse to unapply a final template that follows a non-template rule. The synthesis | ||
| /// derivation this refuses has a non-partial rule after the final template, which is allowed only when the | ||
| /// word is partial there: a partial rule applied before the template. A partial rule leaves the analysis | ||
| /// state at none, so it never arms this. Templates no partial word can reach are pruned outright, and | ||
| /// others when the shape shows that no partial rule can still be unapplied. In a grammar with both partial | ||
| /// rules and lexical families this can drop a duplicate analysis that master returns: a family member | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. FYI: F13. "a duplicate analysis that master returns" describes the code relative to a branch. After merge, master is this code, so the sentence stops making sense. |
||
| /// that replaces the root is a fresh word that forgets the pending final template. Only a duplicate is | ||
| /// lost, never a distinct analysis. FieldWorks never writes a family. | ||
| /// </summary> | ||
| internal bool IsFinalTemplatePrunable(AffixTemplate template, Word input) | ||
| { | ||
| if (!HasPartialRules || AlwaysEnforceFinalTemplates) | ||
| return true; | ||
| return !_partialReachableTemplates.Contains(template) || !_partialLookAhead.PartialRuleMayUnapply(input); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Whether the analysis still owes a partial rule that its shape rules out for it and for anything derived | ||
| /// from it. | ||
| /// </summary> | ||
| internal bool OwesImpossiblePartial(Word input) | ||
| { | ||
| return input.NeedsPartial && !_partialLookAhead.PartialRuleMayUnapply(input); | ||
| } | ||
|
|
||
| public IEnumerable<Morpheme> GetPartialMorphemes() | ||
|
|
@@ -135,8 +211,9 @@ public bool PruneRequiredSlots | |
| public bool MergeEquivalentAnalyses { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// True if any morpheme other than a <see cref="LexEntry"/> is partial. Analysis may prune a final | ||
| /// template that follows a non-template rule only when this is false or | ||
| /// True if any morpheme other than a <see cref="LexEntry"/> is partial. Synthesis lets a non-template rule | ||
| /// follow a final template when the word or the rule is partial, so analysis prunes a final template that | ||
| /// follows a non-template rule only where no partial word can be involved, unless | ||
| /// <see cref="AlwaysEnforceFinalTemplates"/> is set. | ||
| /// </summary> | ||
| public bool HasPartialRules { get; } | ||
|
|
@@ -234,7 +311,8 @@ public IEnumerable<Word> ParseWord(string word, out object trace, bool guessRoot | |
| { | ||
| // Guess roots when there are no results. | ||
| List<Word> matches = new List<Word>(); | ||
| foreach (Word analysisWord in origAnalyses) | ||
| // A partial root takes no template, so the slot rule a flagged analysis owes is never applied. | ||
| foreach (Word analysisWord in origAnalyses.Where(w => !w.NeedsPartial)) | ||
| { | ||
| var lexicalGuesses = LexicalGuess(analysisWord).Distinct(); | ||
| foreach (Word synthesisWord in lexicalGuesses) | ||
|
|
@@ -387,6 +465,12 @@ private IEnumerable<Word> SynthesizeSequential(string word, IEnumerable<Word> an | |
| int alternativeCount = 0; | ||
| foreach (Word analysisWord in analyses) | ||
| { | ||
| // No partial rule was unapplied below the final template that followed a non-template rule. | ||
| if (analysisWord.NeedsPartial) | ||
|
claude[bot] marked this conversation as resolved.
Resolved
|
||
| { | ||
| TraceOwedPartialDropped(analysisWord); | ||
| continue; | ||
| } | ||
| foreach (Word synthesisWord in LexicalLookup(analysisWord)) | ||
| { | ||
| foreach (Word alternative in synthesisWord.ExpandAlternatives()) | ||
|
|
@@ -420,6 +504,11 @@ private IEnumerable<Word> SynthesizeParallel(string word, ConcurrentQueue<Word> | |
| for (int i = 0; i < range.Item2 - range.Item1; i++) | ||
| { | ||
| analyses.TryDequeue(out Word analysisWord); | ||
| if (analysisWord.NeedsPartial) | ||
| { | ||
| TraceOwedPartialDropped(analysisWord); | ||
| continue; | ||
| } | ||
| foreach (Word synthesisWord in LexicalLookup(analysisWord)) | ||
| { | ||
| foreach (Word alternative in synthesisWord.ExpandAlternatives()) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FYI: F12. A trace can show one owed-partial drop twice.
Applypasses the sameinputto bothApplyTemplatesandApplyMorphologicalRules, and each one checksOwesImpossiblePartialand callsTraceOwedPartialDropped. So a word that enters a stratum already owing gets twoOwedPartialCannotUnapplynodes. Check and trace once inApplybefore buildingmruleOutWords. Unverified: read from the code.ParseWord_OwedPartialDropped_IsTracedasserts onlyIs.Not.Empty.