public virtual void TestEnv()
        {
            SemanticGraph h = SemanticGraph.ValueOf("[married/VBN nsubjpass>Hughes/NNP auxpass>was/VBD nmod:to>Gracia/NNP]");

            h.GetFirstRoot().Set(typeof(PatternsAnnotations.PatternLabel1), "YES");
            //SemanticGraph t = SemanticGraph
            //  .valueOf("[loved/VBD\nnsubj:Hughes/NNP\ndobj:[wife/NN poss:his/PRP$ appos:Gracia/NNP]\nconj_and:[obsessed/JJ\ncop:was/VBD\nadvmod:absolutely/RB\nprep_with:[Elicia/NN poss:his/PRP$ amod:little/JJ nn:daughter/NN]]]");
            string macro = "macro WORD = married";
            Env    env   = new Env();

            env.Bind("pattern1", typeof(PatternsAnnotations.PatternLabel1));
            string pattern = "({pattern1:YES}=parent >>nsubjpass {}=node)";
            IList <SemgrexPattern> pats = SemgrexBatchParser.CompileStream(new ByteArrayInputStream(Sharpen.Runtime.GetBytesForString((macro + "\n" + pattern), StandardCharsets.Utf8)), env);
            SemgrexPattern         pat3 = pats[0];
            bool           ignoreCase   = true;
            SemgrexMatcher mat3         = pat3.Matcher(h, ignoreCase);

            if (mat3.Find())
            {
                string parent = mat3.GetNode("parent").Word();
                string node   = mat3.GetNode("node").Word();
                System.Console.Out.WriteLine("Result: parent is " + parent + " and node is " + node);
                NUnit.Framework.Assert.AreEqual(parent, "married");
                NUnit.Framework.Assert.AreEqual(node, "Hughes");
            }
            else
            {
                throw new Exception("failed!");
            }
        }
Example #2
0
        public virtual void TestNamedRelation()
        {
            SemanticGraph  graph   = SemanticGraph.ValueOf("[ate subj>Bill dobj>[muffins compound>blueberry]]");
            SemgrexPattern pattern = SemgrexPattern.Compile("{idx:0}=gov >>=foo {idx:3}=dep");
            SemgrexMatcher matcher = pattern.Matcher(graph);

            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetNode("gov").ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("dep").ToString());
            NUnit.Framework.Assert.AreEqual("compound", matcher.GetRelnString("foo"));
            NUnit.Framework.Assert.IsFalse(matcher.Find());
            pattern = SemgrexPattern.Compile("{idx:3}=dep <<=foo {idx:0}=gov");
            matcher = pattern.Matcher(graph);
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetNode("gov").ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("dep").ToString());
            NUnit.Framework.Assert.AreEqual("dobj", matcher.GetRelnString("foo"));
            NUnit.Framework.Assert.IsFalse(matcher.Find());
            pattern = SemgrexPattern.Compile("{idx:3}=dep <=foo {idx:2}=gov");
            matcher = pattern.Matcher(graph);
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("gov").ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("dep").ToString());
            NUnit.Framework.Assert.AreEqual("compound", matcher.GetRelnString("foo"));
            NUnit.Framework.Assert.IsFalse(matcher.Find());
            pattern = SemgrexPattern.Compile("{idx:2}=gov >=foo {idx:3}=dep");
            matcher = pattern.Matcher(graph);
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("gov").ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("dep").ToString());
            NUnit.Framework.Assert.AreEqual("compound", matcher.GetRelnString("foo"));
            NUnit.Framework.Assert.IsFalse(matcher.Find());
        }
        public override string ToString(bool hasPrecedence)
        {
            StringBuilder sb = new StringBuilder();

            if (isConj)
            {
                foreach (SemgrexPattern node in children)
                {
                    sb.Append(node.ToString());
                }
            }
            else
            {
                sb.Append('[');
                for (IEnumerator <SemgrexPattern> iter = children.GetEnumerator(); iter.MoveNext();)
                {
                    SemgrexPattern node = iter.Current;
                    sb.Append(node.ToString());
                    if (iter.MoveNext())
                    {
                        sb.Append(" |");
                    }
                }
                sb.Append(']');
            }
            return(sb.ToString());
        }
Example #4
0
        public static void RunTest(SemgrexPattern pattern, SemanticGraph graph, params string[] expectedMatches)
        {
            // results are not in the order I would expect.  Using a counter
            // allows them to be in any order
            IntCounter <string> counts = new IntCounter <string>();

            for (int i = 0; i < expectedMatches.Length; ++i)
            {
                counts.IncrementCount(expectedMatches[i]);
            }
            IntCounter <string> originalCounts = new IntCounter <string>(counts);
            SemgrexMatcher      matcher        = pattern.Matcher(graph);

            for (int i_1 = 0; i_1 < expectedMatches.Length; ++i_1)
            {
                if (!matcher.Find())
                {
                    throw new AssertionFailedError("Expected " + expectedMatches.Length + " matches for pattern " + pattern + " on " + graph + ", only got " + i_1);
                }
                string match = matcher.GetMatch().ToString();
                if (!counts.ContainsKey(match))
                {
                    throw new AssertionFailedError("Unexpected match " + match + " for pattern " + pattern + " on " + graph);
                }
                counts.DecrementCount(match);
                if (counts.GetCount(match) < 0)
                {
                    throw new AssertionFailedError("Found too many matches for " + match + " for pattern " + pattern + " on " + graph);
                }
            }
            if (matcher.FindNextMatchingNode())
            {
                throw new AssertionFailedError("Found more than " + expectedMatches.Length + " matches for pattern " + pattern + " on " + graph + "... extra match is " + matcher.GetMatch());
            }
        }
Example #5
0
        public static void OutputResults(SemgrexPattern pattern, SemanticGraph graph, params string[] ignored)
        {
            System.Console.Out.WriteLine("Matching pattern " + pattern + " to\n" + graph + "  :" + (pattern.Matcher(graph).Matches() ? "matches" : "doesn't match"));
            System.Console.Out.WriteLine();
            pattern.PrettyPrint();
            System.Console.Out.WriteLine();
            SemgrexMatcher matcher = pattern.Matcher(graph);

            while (matcher.Find())
            {
                System.Console.Out.WriteLine("  " + matcher.GetMatch());
                ICollection <string> nodeNames = matcher.GetNodeNames();
                if (nodeNames != null && nodeNames.Count > 0)
                {
                    foreach (string name in nodeNames)
                    {
                        System.Console.Out.WriteLine("    " + name + ": " + matcher.GetNode(name));
                    }
                }
                ICollection <string> relNames = matcher.GetRelationNames();
                if (relNames != null)
                {
                    foreach (string name in relNames)
                    {
                        System.Console.Out.WriteLine("    " + name + ": " + matcher.GetRelnString(name));
                    }
                }
            }
        }
Example #6
0
        public static void ComparePatternToString(string pattern)
        {
            SemgrexPattern semgrex  = SemgrexPattern.Compile(pattern);
            string         tostring = semgrex.ToString();

            tostring = tostring.ReplaceAll(" +", " ");
            NUnit.Framework.Assert.AreEqual(pattern.Trim(), tostring.Trim());
        }
        public virtual void TestSerialization()
        {
            SemgrexPattern pat3     = SemgrexPattern.Compile("({word:LIKE}=parent >>nn {word:/do/}=node)");
            File           tempfile = File.CreateTempFile("temp", "file");

            tempfile.DeleteOnExit();
            IOUtils.WriteObjectToFile(pat3, tempfile);
            SemgrexPattern pat4 = IOUtils.ReadObjectFromFile(tempfile);

            NUnit.Framework.Assert.AreEqual(pat3, pat4);
        }
Example #8
0
        public virtual void TestEqualsRelation()
        {
            SemanticGraph  graph   = SemanticGraph.ValueOf("[ate subj>Bill dobj>[muffins compound>blueberry]]");
            SemgrexPattern pattern = SemgrexPattern.Compile("{} >> ({}=a == {}=b)");
            SemgrexMatcher matcher = pattern.Matcher(graph);

            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("Bill", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("Bill", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsFalse(matcher.Find());
            // This split pattern should also work
            pattern = SemgrexPattern.Compile("{} >> {}=a >> {}=b : {}=a == {}=b");
            matcher = pattern.Matcher(graph);
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("Bill", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("Bill", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsFalse(matcher.Find());
        }
 public virtual void AddRelnToNodeCoord(SemgrexPattern child)
 {
     if (isNodeCoord)
     {
         foreach (SemgrexPattern c in children)
         {
             IList <SemgrexPattern> newChildren = new List <SemgrexPattern>();
             Sharpen.Collections.AddAll(newChildren, c.GetChildren());
             newChildren.Add(child);
             c.SetChild(new Edu.Stanford.Nlp.Semgraph.Semgrex.CoordinationPattern(false, newChildren, true));
         }
     }
 }
 internal override void SetChild(SemgrexPattern child)
 {
     if (isNodeCoord)
     {
         foreach (object c in children)
         {
             if (c is NodePattern)
             {
                 ((NodePattern)c).SetChild(child);
             }
         }
     }
 }
Example #11
0
        public virtual void TestMatchAll()
        {
            SemanticGraph             graph   = SemanticGraph.ValueOf("[ate subj>Bill dobj>[muffins compound>blueberry]]");
            ICollection <IndexedWord> words   = graph.VertexSet();
            SemgrexPattern            pattern = SemgrexPattern.Compile("{}");
            SemgrexMatcher            matcher = pattern.Matcher(graph);

            string[] expectedMatches = new string[] { "ate", "Bill", "muffins", "blueberry" };
            for (int i = 0; i < expectedMatches.Length; ++i)
            {
                NUnit.Framework.Assert.IsTrue(matcher.FindNextMatchingNode());
            }
            NUnit.Framework.Assert.IsFalse(matcher.FindNextMatchingNode());
        }
 public CoordinationMatcher(CoordinationPattern c, SemanticGraph sg, Alignment alignment, SemanticGraph sg_align, bool hypToText, IndexedWord n, IDictionary <string, IndexedWord> namesToNodes, IDictionary <string, string> namesToRelations, VariableStrings
                            variableStrings, bool ignoreCase)
     : base(sg, alignment, sg_align, hypToText, n, namesToNodes, namesToRelations, variableStrings)
 {
     // do all con/dis-juncts have to be considered to determine a match?
     // i.e. true if conj and not negated or disj and negated
     myNode   = c;
     children = new SemgrexMatcher[myNode.children.Count];
     for (int i = 0; i < children.Length; i++)
     {
         SemgrexPattern node = myNode.children[i];
         children[i] = node.Matcher(sg, alignment, sg_align, hypToText, n, namesToNodes, namesToRelations, variableStrings, ignoreCase);
     }
     currChild   = 0;
     considerAll = myNode.isConj ^ myNode.IsNegated();
 }
Example #13
0
        public virtual void TestExactDepthRelations()
        {
            SemanticGraph graph = MakeComplicatedGraph();

            RunTest("{} 2,3<< {word:A}", graph, "E", "F", "G", "I");
            RunTest("{} 2,2<< {word:A}", graph, "E");
            RunTest("{} 1,2<< {word:A}", graph, "B", "C", "D", "E");
            RunTest("{} 0,2<< {word:A}", graph, "B", "C", "D", "E");
            RunTest("{} 0,10<< {word:A}", graph, "B", "C", "D", "E", "F", "G", "H", "I", "J");
            RunTest("{} 0,10>> {word:J}", graph, "A", "B", "C", "D", "E", "F", "G", "H", "I");
            RunTest("{} 2,3>> {word:J}", graph, "B", "C", "D", "E", "F", "G", "H");
            RunTest("{} 2,2>> {word:J}", graph, "E", "H");
            // use this method to avoid the toString() test, since we expect it
            // to use 2,2>> instead of 2>>
            RunTest(SemgrexPattern.Compile("{} 2>> {word:J}"), graph, "E", "H");
            RunTest("{} 1,2>> {word:J}", graph, "E", "H", "I");
        }
        public virtual void TestPrettyPrint()
        {
            // SemgrexPattern pat = SemgrexPattern.compile("{} >sub {} & ?>ss {w:w}");
            // SemgrexPattern pat =
            // SemgrexPattern.compile("({} </nsubj|agent/ {pos:/VB.*/}=hypVerb) @ ({#} </nsubj|agent/ {pos:/VB.*/}=txtVerb)");
            // SemgrexPattern pat =
            // SemgrexPattern.compile("({sentIndex:4} <=hypReln {sentIndex:2}=hypGov) @ ({} <=hypReln ({} >conj_and ({} @ {}=hypGov)))");
            SemgrexPattern pat = SemgrexPattern.Compile("({}=partnerOne [[<prep_to ({word:/married/} >nsubjpass {}=partnerTwo)] | [<nsubjpass ({word:married} >prep_to {}=partnerTwo)]]) @ ({} [[>/nn|appos/ {lemma:/wife|husband/} >poss ({}=txtPartner @ {}=partnerTwo)] | [<poss (({}=txtPartner @ {}=partnerTwo) >/appos|nn/ {lemma:/wife|husband/})]])"
                                                        );

            // SemgrexPattern pat =
            // SemgrexPattern.compile("({pos:/VB.*/}=hVerb @ {pos:/VB.*/}=tVerb) >/nsubj|nsubjpass|dobj|iobj|prep.*/=hReln ({}=hWord @ ({}=tWord [ [ >/nsubj|nsubjpass|dobj|iobj|prep.*/=tReln {}=tVerb] | [ >appos ({} >/nsubj|nsubjpass|dobj|iobj|prep.*/=tReln {}=tVerb) ] | [ <appos ({} >/nsubj|nsubjpass|dobj|iobj|prep.*/=tReln {}=tVerb)] | ![> {}=tVerb]]))");
            // SemgrexPattern pat =
            // SemgrexPattern.compile("({}=partnerOne [[<prep_to ({word:married} >nsubjpass {}=partnerTwo)] | [<nsubjpass ({word:married} >prep_to {}=partnerTwo)]]) @ ({} [[>nn {lemma:/wife|husband/} >poss {}=txtPartner] | [<poss ({}=txtPartner >nn {lemma:/wife|husband/})]])");
            // @ ({} </nsubj|agent/ {pos:/VB.*/}=txtVerb)
            pat.PrettyPrint();
        }
Example #15
0
        public virtual void TestNamedNode()
        {
            SemanticGraph graph = MakeComplicatedGraph();

            RunTest("{} >dobj ({} >expl {})", graph, "A");
            SemgrexPattern pattern = SemgrexPattern.Compile("{} >dobj ({} >expl {}=foo)");
            SemgrexMatcher matcher = pattern.Matcher(graph);

            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(1, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("E", matcher.GetNode("foo").ToString());
            NUnit.Framework.Assert.AreEqual("A", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.IsFalse(matcher.Find());
            pattern = SemgrexPattern.Compile("{} >dobj ({} >expl {}=foo) >mod {}");
            matcher = pattern.Matcher(graph);
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(1, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("E", matcher.GetNode("foo").ToString());
            NUnit.Framework.Assert.AreEqual("A", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.IsFalse(matcher.Find());
            pattern = SemgrexPattern.Compile("{} >dobj ({} >expl {}=foo) >mod ({} >mark {})");
            matcher = pattern.Matcher(graph);
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(1, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("E", matcher.GetNode("foo").ToString());
            NUnit.Framework.Assert.AreEqual("A", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.IsFalse(matcher.Find());
            pattern = SemgrexPattern.Compile("{} >dobj ({} >expl {}=foo) >mod ({} > {})");
            matcher = pattern.Matcher(graph);
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(1, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("E", matcher.GetNode("foo").ToString());
            NUnit.Framework.Assert.AreEqual("A", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.IsFalse(matcher.Find());
            pattern = SemgrexPattern.Compile("{} >dobj ({} >expl {}=foo) >mod ({} > {}=foo)");
            matcher = pattern.Matcher(graph);
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(1, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("E", matcher.GetNode("foo").ToString());
            NUnit.Framework.Assert.AreEqual("A", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.IsFalse(matcher.Find());
            pattern = SemgrexPattern.Compile("{} >dobj ({} >expl {}=foo) >mod ({}=foo > {})");
            matcher = pattern.Matcher(graph);
            NUnit.Framework.Assert.IsFalse(matcher.Find());
        }
Example #16
0
        public virtual void TestInitialConditions()
        {
            SemanticGraph  graph   = MakeComplicatedGraph();
            SemgrexPattern pattern = SemgrexPattern.Compile("{}=a >> {}=b : {}=a >> {}=c");
            IDictionary <string, IndexedWord> variables = new Dictionary <string, IndexedWord>();

            variables["b"] = graph.GetNodeByIndex(5);
            variables["c"] = graph.GetNodeByIndex(2);
            SemgrexMatcher matcher = pattern.Matcher(graph, variables);

            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(3, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("A", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("E", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.AreEqual("B", matcher.GetNode("c").ToString());
            NUnit.Framework.Assert.AreEqual("A", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.IsFalse(matcher.Find());
        }
Example #17
0
        /// <exception cref="System.IO.IOException"/>
        private static IList <SemgrexPattern> Parse(BufferedReader reader, IDictionary <string, string> macros, Env env)
        {
            IList <SemgrexPattern> patterns = new List <SemgrexPattern>();

            for (string line; (line = reader.ReadLine()) != null;)
            {
                line = line.Trim();
                if (line.IsEmpty() || line.StartsWith("#"))
                {
                    continue;
                }
                if (line.StartsWith("macro "))
                {
                    continue;
                }
                line = ReplaceMacros(line, macros);
                SemgrexPattern pattern = SemgrexPattern.Compile(line, env);
                patterns.Add(pattern);
            }
            return(patterns);
        }
        public virtual void TestMacro()
        {
            SemanticGraph          h       = SemanticGraph.ValueOf("[married/VBN nsubjpass>Hughes/NNP auxpass>was/VBD nmod:to>Gracia/NNP]");
            string                 macro   = "macro WORD = married";
            string                 pattern = "({word:${WORD}}=parent >>nsubjpass {}=node)";
            IList <SemgrexPattern> pats    = SemgrexBatchParser.CompileStream(new ByteArrayInputStream(Sharpen.Runtime.GetBytesForString((macro + "\n" + pattern), StandardCharsets.Utf8)));
            SemgrexPattern         pat3    = pats[0];
            bool           ignoreCase      = true;
            SemgrexMatcher mat3            = pat3.Matcher(h, ignoreCase);

            if (mat3.Find())
            {
                string parent = mat3.GetNode("parent").Word();
                string node   = mat3.GetNode("node").Word();
                System.Console.Out.WriteLine("Result: parent is " + parent + " and node is " + node);
                NUnit.Framework.Assert.AreEqual(parent, "married");
                NUnit.Framework.Assert.AreEqual(node, "Hughes");
            }
            else
            {
                throw new Exception("failed!");
            }
        }
        public virtual void TestSiblingPatterns()
        {
            SemanticGraph sg = SemanticGraph.ValueOf("[loved/VBD-2\nnsubj>Hughes/NNP-1\ndobj>[wife/NN-4 nmod:poss>his/PRP$-3 appos>Gracia/NNP-5]\nconj:and>[obsessed/JJ-9\ncop>was/VBD-7\nadvmod>absolutely/RB-8\nnmod:with>[Elicia/NN-14 nmod:poss>his/PRP$-11 amod>little/JJ-12 compound>daughter/NN-13]]]"
                                                     );
            /* Test "." */
            SemgrexPattern pat1    = SemgrexPattern.Compile("{tag:NNP}=w1 . {tag:VBD}=w2");
            SemgrexMatcher matcher = pat1.Matcher(sg);

            if (matcher.Find())
            {
                string w1 = matcher.GetNode("w1").Word();
                string w2 = matcher.GetNode("w2").Word();
                NUnit.Framework.Assert.AreEqual("Hughes", w1);
                NUnit.Framework.Assert.AreEqual("loved", w2);
            }
            else
            {
                throw new Exception("failed!");
            }
            /* Test "$+" */
            SemgrexPattern pat2 = SemgrexPattern.Compile("{word:was}=w1 $+ {}=w2");

            matcher = pat2.Matcher(sg);
            if (matcher.Find())
            {
                string w1 = matcher.GetNode("w1").Word();
                string w2 = matcher.GetNode("w2").Word();
                NUnit.Framework.Assert.AreEqual("was", w1);
                NUnit.Framework.Assert.AreEqual("absolutely", w2);
            }
            else
            {
                throw new Exception("failed!");
            }
            /* Test "$-" */
            SemgrexPattern pat3 = SemgrexPattern.Compile("{word:absolutely}=w1 $- {}=w2");

            matcher = pat3.Matcher(sg);
            if (matcher.Find())
            {
                string w1 = matcher.GetNode("w1").Word();
                string w2 = matcher.GetNode("w2").Word();
                NUnit.Framework.Assert.AreEqual("absolutely", w1);
                NUnit.Framework.Assert.AreEqual("was", w2);
            }
            else
            {
                throw new Exception("failed!");
            }
            /* Test "$++" */
            SemgrexPattern pat4 = SemgrexPattern.Compile("{word:his}=w1 $++ {tag:NN}=w2");

            matcher = pat4.Matcher(sg);
            if (matcher.Find())
            {
                string w1 = matcher.GetNode("w1").Word();
                string w2 = matcher.GetNode("w2").Word();
                NUnit.Framework.Assert.AreEqual("his", w1);
                NUnit.Framework.Assert.AreEqual("daughter", w2);
            }
            else
            {
                throw new Exception("failed!");
            }
            /* Test "$--" */
            SemgrexPattern pat6 = SemgrexPattern.Compile("{word:daughter}=w1 $-- {tag:/PRP./}=w2");

            matcher = pat6.Matcher(sg);
            if (matcher.Find())
            {
                string w1 = matcher.GetNode("w1").Word();
                string w2 = matcher.GetNode("w2").Word();
                NUnit.Framework.Assert.AreEqual("daughter", w1);
                NUnit.Framework.Assert.AreEqual("his", w2);
            }
            else
            {
                throw new Exception("failed!");
            }
            /* Test for not matching. */
            SemgrexPattern pat5 = SemgrexPattern.Compile("{word:his}=w1 $-- {}=w2");

            matcher = pat5.Matcher(sg);
            if (matcher.Find())
            {
                throw new Exception("failed!");
            }
            /* Test for negation. */
            SemgrexPattern pat7 = SemgrexPattern.Compile("{word:his}=w1 !$-- {}");

            matcher = pat7.Matcher(sg);
            if (matcher.Find())
            {
                string w1 = matcher.GetNode("w1").Word();
                NUnit.Framework.Assert.AreEqual("his", w1);
            }
            else
            {
                throw new Exception("failed!");
            }
            SemgrexPattern pat8 = SemgrexPattern.Compile("{word:his}=w1 !$++ {}");

            matcher = pat8.Matcher(sg);
            if (matcher.Find())
            {
                throw new Exception("failed!");
            }
        }
        public virtual void TestFind()
        {
            SemanticGraph h = SemanticGraph.ValueOf("[married/VBN nsubjpass>Hughes/NNP auxpass>was/VBD prep_to>Gracia/NNP]");
            SemanticGraph t = SemanticGraph.ValueOf("[loved/VBD\nnsubj>Hughes/NNP\ndobj>[wife/NN poss>his/PRP$ appos>Gracia/NNP]\nconj_and>[obsessed/JJ\ncop>was/VBD\nadvmod>absolutely/RB\nprep_with>[Elicia/NN poss>his/PRP$ amod>little/JJ compound>daughter/NN]]]"
                                                    );
            string         s    = "(ROOT\n(S\n(NP (DT The) (NN chimney) (NNS sweeps))\n(VP (VBP do) (RB not)\n(VP (VB like)\n(S\n(VP (VBG working)\n(PP (IN on)\n(NP (DT an) (JJ empty) (NN stomach)))))))\n(. .)))";
            Tree           tree = Tree.ValueOf(s);
            SemanticGraph  sg   = SemanticGraphFactory.MakeFromTree(tree, SemanticGraphFactory.Mode.Collapsed, GrammaticalStructure.Extras.Maximal, null);
            SemgrexPattern pat  = SemgrexPattern.Compile("{}=gov ![>det {}] & > {word:/^(?!not).*$/}=dep");

            sg.PrettyPrint();
            // SemgrexPattern pat =
            // SemgrexPattern.compile("{} [[<prep_to ({word:married} >nsubjpass {})] | [<nsubjpass ({word:married} >prep_to {})]]");
            pat.PrettyPrint();
            SemgrexMatcher mat = pat.Matcher(sg);

            while (mat.Find())
            {
                // String match = mat.getMatch().word();
                string gov = mat.GetNode("gov").Word();
                // String reln = mat.getRelnString("reln");
                string dep = mat.GetNode("dep").Word();
                // System.out.println(match);
                System.Console.Out.WriteLine(dep + ' ' + gov);
            }
            SemgrexPattern pat2 = SemgrexPattern.Compile("{} [[>/nn|appos/ ({lemma:/wife|husband|partner/} >/poss/ {}=txtPartner)] | [<poss ({}=txtPartner >/nn|appos/ {lemma:/wife|husband|partner/})]" + "| [<nsubj ({$} >> ({word:/wife|husband|partner/} >poss {word:/his|her/} >/nn|appos/ {}))]]"
                                                         );
            SemgrexMatcher mat2 = pat2.Matcher(t);

            while (mat2.Find())
            {
                string match = mat2.GetMatch().Word();
                // String gov = mat.getNode("gov").word();
                // String reln = mat.getRelnString("reln");
                // String dep = mat.getNode("dep").word();
                System.Console.Out.WriteLine(match);
            }
            // System.out.println(dep + " " + gov);
            Dictionary <IndexedWord, IndexedWord> map = new Dictionary <IndexedWord, IndexedWord>();

            map[h.GetNodeByWordPattern("Hughes")] = t.GetNodeByWordPattern("Hughes");
            map[h.GetNodeByWordPattern("Gracia")] = t.GetNodeByWordPattern("Gracia");
            Alignment      alignment = new Alignment(map, 0, string.Empty);
            SemgrexPattern fullPat   = SemgrexPattern.Compile("({}=partnerOne [[<prep_to ({word:married} >nsubjpass {}=partnerTwo)] | [<nsubjpass ({word:married} >prep_to {}=partnerTwo)]]) @ ({} [[>/nn|appos/ ({lemma:/wife|husband|partner/} >/poss/ {}=txtPartner)] | [<poss ({}=txtPartner >/nn|appos/ {lemma:/wife|husband|partner/})]"
                                                              + "| [<nsubj ({$} >> ({word:/wife|husband|partner/} >poss {word:/his|her/} >/nn|appos/ {}=txtPartner))]])");

            fullPat.PrettyPrint();
            SemgrexMatcher fullMat = fullPat.Matcher(h, alignment, t);

            if (fullMat.Find())
            {
                System.Console.Out.WriteLine("woo: " + fullMat.GetMatch().Word());
                System.Console.Out.WriteLine(fullMat.GetNode("txtPartner"));
                System.Console.Out.WriteLine(fullMat.GetNode("partnerOne"));
                System.Console.Out.WriteLine(fullMat.GetNode("partnerTwo"));
            }
            else
            {
                System.Console.Out.WriteLine("boo");
            }
            SemgrexPattern pat3 = SemgrexPattern.Compile("({word:LIKE}=parent >>/aux.*/ {word:/do/}=node)");

            System.Console.Out.WriteLine("pattern is ");
            pat3.PrettyPrint();
            System.Console.Out.WriteLine("tree is ");
            sg.PrettyPrint();
            //checking if ignoring case or not
            SemgrexMatcher mat3 = pat3.Matcher(sg, true);

            if (mat3.Find())
            {
                string parent = mat3.GetNode("parent").Word();
                string node   = mat3.GetNode("node").Word();
                System.Console.Out.WriteLine("Result: parent is " + parent + " and node is " + node);
                NUnit.Framework.Assert.AreEqual(parent, "like");
                NUnit.Framework.Assert.AreEqual(node, "do");
            }
            else
            {
                NUnit.Framework.Assert.Fail();
            }
        }
Example #21
0
 public static void RunTest(string pattern, SemanticGraph graph, params string[] expectedMatches)
 {
     ComparePatternToString(pattern);
     RunTest(SemgrexPattern.Compile(pattern), graph, expectedMatches);
 }
 internal override void SetChild(SemgrexPattern n)
 {
     child = n;
 }
Example #23
0
 public static void OutputResults(string pattern, SemanticGraph graph, params string[] ignored)
 {
     OutputResults(SemgrexPattern.Compile(pattern), graph);
 }
 public NodePattern(GraphRelation r, bool negDesc, IDictionary <string, string> attrs, bool root, bool empty, string name, IList <Pair <int, string> > variableGroups)
 {
     // specifies the groups in a regex that are captured as
     // matcher-global string variables
     // TODO: there is no capacity for named variable groups in the parser right now
     this.reln    = r;
     this.negDesc = negDesc;
     attributes   = Generics.NewHashMap();
     descString   = "{";
     foreach (KeyValuePair <string, string> entry in attrs)
     {
         if (!descString.Equals("{"))
         {
             descString += ";";
         }
         string key   = entry.Key;
         string value = entry.Value;
         // Add the attributes for this key
         if (value.Equals("__"))
         {
             attributes[key] = Pair.MakePair(true, true);
         }
         else
         {
             if (value.Matches("/.*/"))
             {
                 bool isRegexp = false;
                 for (int i = 1; i < value.Length - 1; ++i)
                 {
                     char chr = value[i];
                     if (!((chr >= 'A' && chr <= 'Z') || (chr >= 'a' && chr <= 'z') || (chr >= '0' && chr <= '9')))
                     {
                         isRegexp = true;
                         break;
                     }
                 }
                 string patternContent = Sharpen.Runtime.Substring(value, 1, value.Length - 1);
                 if (isRegexp)
                 {
                     attributes[key] = Pair.MakePair(Pattern.Compile(patternContent), Pattern.Compile(patternContent, Pattern.CaseInsensitive | Pattern.UnicodeCase));
                 }
                 else
                 {
                     attributes[key] = Pair.MakePair(patternContent, patternContent);
                 }
             }
             else
             {
                 // raw description
                 attributes[key] = Pair.MakePair(value, value);
             }
         }
         //      if (value.equals("__")) {
         //        attributes.put(key, Pair.makePair(Pattern.compile(".*"), Pattern.compile(".*", Pattern.CASE_INSENSITIVE)));
         //      } else if (value.matches("/.*/")) {
         //        attributes.put(key, Pair.makePair(
         //            Pattern.compile(value.substring(1, value.length() - 1)),
         //            Pattern.compile(value.substring(1, value.length() - 1), Pattern.CASE_INSENSITIVE))
         //        );
         //      } else { // raw description
         //        attributes.put(key, Pair.makePair(
         //            Pattern.compile("^(" + value + ")$"),
         //            Pattern.compile("^(" + value + ")$", Pattern.CASE_INSENSITIVE))
         //        );
         //      }
         descString += (key + ':' + value);
     }
     if (root)
     {
         descString += "$";
     }
     else
     {
         if (empty)
         {
             descString += "#";
         }
     }
     descString         += '}';
     this.name           = name;
     this.child          = null;
     this.isRoot         = root;
     this.isEmpty        = empty;
     this.variableGroups = variableGroups;
 }
        /// <exception cref="Edu.Stanford.Nlp.Semgraph.Semgrex.ParseException"/>
        public SemgrexPattern SubNode(GraphRelation r)
        {
            SemgrexPattern result = null;
            SemgrexPattern child  = null;

            switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk)
            {
            case 13:
            {
                Jj_consume_token(13);
                result = SubNode(r);
                Jj_consume_token(14);
                switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk)
                {
                case SemgrexParserConstantsConstants.Relation:
                case SemgrexParserConstantsConstants.Alignreln:
                case SemgrexParserConstantsConstants.Identifier:
                case 17:
                case 18:
                case 19:
                {
                    child = RelationDisj();
                    break;
                }

                default:
                {
                    jj_la1[2] = jj_gen;
                    break;
                }
                }
                if (child != null)
                {
                    IList <SemgrexPattern> newChildren = new List <SemgrexPattern>();
                    Sharpen.Collections.AddAll(newChildren, result.GetChildren());
                    newChildren.Add(child);
                    result.SetChild(new CoordinationPattern(false, newChildren, true));
                }
                if (true)
                {
                    return(result);
                }
                break;
            }

            case 17:
            case 19:
            case 23:
            {
                result = ModNode(r);
                switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk)
                {
                case SemgrexParserConstantsConstants.Relation:
                case SemgrexParserConstantsConstants.Alignreln:
                case SemgrexParserConstantsConstants.Identifier:
                case 17:
                case 18:
                case 19:
                {
                    child = RelationDisj();
                    break;
                }

                default:
                {
                    jj_la1[3] = jj_gen;
                    break;
                }
                }
                if (child != null)
                {
                    result.SetChild(child);
                }
                if (true)
                {
                    return(result);
                }
                break;
            }

            default:
            {
                jj_la1[4] = jj_gen;
                Jj_consume_token(-1);
                throw new ParseException();
            }
            }
            throw new Exception("Missing return statement in function");
        }
Example #26
0
        public virtual void TestNotEquals()
        {
            SemanticGraph  graph   = SemanticGraph.ValueOf("[ate subj>Bill dobj>[muffins compound>blueberry]]");
            SemgrexPattern pattern = SemgrexPattern.Compile("{} >> {}=a >> {}=b : {}=a !== {}=b");
            SemgrexMatcher matcher = pattern.Matcher(graph);

            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("Bill", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("Bill", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("Bill", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("Bill", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsFalse(matcher.Find());
            // same as the first test, essentially, but with a more compact expression
            pattern = SemgrexPattern.Compile("{} >> {}=a >> ({}=b !== {}=a)");
            matcher = pattern.Matcher(graph);
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("Bill", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("Bill", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("Bill", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("Bill", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsTrue(matcher.Find());
            NUnit.Framework.Assert.AreEqual(2, matcher.GetNodeNames().Count);
            NUnit.Framework.Assert.AreEqual("ate", matcher.GetMatch().ToString());
            NUnit.Framework.Assert.AreEqual("blueberry", matcher.GetNode("a").ToString());
            NUnit.Framework.Assert.AreEqual("muffins", matcher.GetNode("b").ToString());
            NUnit.Framework.Assert.IsFalse(matcher.Find());
        }