Skip to content
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

Relex2Logic test cases. #110

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions build.xml
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@
includeantruntime="false"
source="${source}" target="${target}">
<src path="src/java_test"/>
<exclude name="**/LogicCases.java" />
<exclude name="**/LogicViewTest.java" />
<exclude name="**/RegexMatcher.java" />
<classpath refid="relex.classpath"/>
</javac>
</target>
Expand Down
94 changes: 94 additions & 0 deletions src/java_test/relex/output/LogicCases.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package relex.output;

import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import org.odftoolkit.simple.SpreadsheetDocument;
import org.odftoolkit.simple.table.Row;
import org.odftoolkit.simple.table.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;


public class LogicCases {

private static final Logger log = LoggerFactory
.getLogger(LogicCases.class);
private static final String RELEX2LOGIC_TEST_PATH = "/relex2logic.ods";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ceefour I just noticed this, and I was curious: what was the contents of relex2logic.ods?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I imagine this should have some meaning for me. I have a wild imagination. ???


On Fri, 9/12/14, Cosmo Harrigan [email protected] wrote:

Subject: Re: [relex] Relex2Logic test cases. (#110)
To: "opencog/relex" [email protected]
Date: Friday, September 12, 2014, 6:12 PM

In
src/java_test/relex/output/LogicCases.java:

+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+
+
+public class LogicCases {
+

  • private static final Logger log = LoggerFactory
  •        .getLogger(LogicCases.class);
    
  • private static final String RELEX2LOGIC_TEST_PATH =
    "/relex2logic.ods";

@ceefour I just
noticed this, and I was curious: what was the contents of
relex2logic.ods?


Reply to this email directly or view
it on GitHub.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@anitzkin What do you mean by meaning? :)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On Sat, Sep 13, 2014 at 12:19 PM, Cosmo Harrigan [email protected]
wrote:

In src/java_test/relex/output/LogicCases.java:

+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+
+
+public class LogicCases {
+

  • private static final Logger log = LoggerFactory
  •       .getLogger(LogicCases.class);
    
  • private static final String RELEX2LOGIC_TEST_PATH = "/relex2logic.ods";

@anitzkin https://github.com/anitzkin What do you mean by meaning? :)

“Don't for heaven's sake, be afraid of talking nonsense! But you must pay
attention to your nonsense.” -- Wittgenstein

... i.e., Meaning is paying attention to your nonsense.

QED
;)
ben


protected Iterator<Row> inputIterator(Object... args) {
URL logicOds = Preconditions.checkNotNull(LogicCases.class.getResource(RELEX2LOGIC_TEST_PATH),
"Cannot load '%s' from classpath", RELEX2LOGIC_TEST_PATH);
log.info("Loading '{}'...", logicOds);
// TODO: Java 7 try-with-resources please
try {
SpreadsheetDocument doc = SpreadsheetDocument.loadDocument(logicOds.openStream());
try {
Table table = doc.getTableList().get(0);
boolean firstRow = true;
final List<Row> realRows = new ArrayList<Row>();
for (Iterator<Row> iter = table.getRowIterator(); iter.hasNext(); ) {
Row row = iter.next();
if (firstRow) {
firstRow = false;
continue;
}
if (row.getCellByIndex(0).getStringValue().trim().isEmpty()) {
break;
}
realRows.add(row);
}
log.info("Got {} out of {} rows in table {}", realRows.size(), table.getRowCount(), table.getTableName());
return realRows.iterator();
} finally {
doc.close();
}
} catch (Exception e) {
throw new RuntimeException("Cannot read " + logicOds, e);
}
}

protected Object[] parse(Row row, Object... args) {
String sentence = row.getCellByIndex(0).getStringValue();
String expectedLinkGrammar = row.getCellByIndex(1).getStringValue();
Set<String> expectedBinaries = ImmutableSet.copyOf( Splitter.on("\n").split(row.getCellByIndex(2).getStringValue()) );
Set<String> expectedUnaries = ImmutableSet.copyOf( Splitter.on("\n").split(row.getCellByIndex(3).getStringValue()) );
Iterable<String> logicStrs = Splitter.on(Pattern.compile("\n(?=[(])")).split(row.getCellByIndex(4).getStringValue());
ImmutableSet<Pattern> expectedLogics = FluentIterable.from(logicStrs).transform(new Function<String, Pattern>() {
public Pattern apply(String input) {
String regex = input.trim();
regex = Pattern.compile("( |\n)+", Pattern.MULTILINE).matcher(regex).replaceAll(" ");
regex = regex.replace("(", "[(]")
.replace(")", "[)]")
.replace("+", ".+");
regex = "^" + regex + "$";
return Pattern.compile(regex);
}
}).toSet();
log.debug("Test case: \"{}\" grammar={} primary={} attributes={} logics={}",
sentence, expectedLinkGrammar, expectedBinaries, expectedUnaries, expectedLogics);
return new Object[] { sentence, expectedLinkGrammar, expectedBinaries, expectedUnaries, expectedLogics };
}

public static Object[] provideLogic() {
final LogicCases cases = new LogicCases();
return FluentIterable.from(ImmutableList.copyOf(cases.inputIterator()))
.transform(new Function<Row, Object[]>() {
public Object[] apply(Row input) {
return cases.parse(input);
}
}).toArray(Object[].class);
}

}
125 changes: 125 additions & 0 deletions src/java_test/relex/output/LogicViewTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package relex.output;

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;

import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import junitparams.JUnitParamsRunner;

import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import relex.ParsedSentence;
import relex.RelationExtractor;
import relex.Sentence;

import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;

/**
* @author ceefour
*
*/
@RunWith(JUnitParamsRunner.class)
public class LogicViewTest {

private static final Logger log = LoggerFactory
.getLogger(LogicViewTest.class);


private static final int max_parses = 1;
private static final String lang = "en";

private static RelationExtractor re;
private static LogicView lv;
private static OpenCogScheme oc;

/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpClass() throws Exception {
re = new RelationExtractor(false);
re.setLanguage(lang);
re.setMaxParses(max_parses);
if (1000 < max_parses) {
re.setMaxLinkages(max_parses + 100);
}

lv = new LogicView();
lv.loadRules();

oc = new OpenCogScheme();
oc.setShowLinkage(true);
oc.setShowRelex(true);
oc.setShowAnaphora(true);
}

/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}

@Test
@junitparams.Parameters(source=LogicCases.class)
public void printRelationsNew(String sentence,
String expectedLinkGrammar,
Set<String> expectedBinaries, Set<String> expectedUnaries,
Set<Pattern> expectedLogics) {
System.err.println("Info: sentence: \"" + sentence + "\"");
Sentence sntc = re.processSentence(sentence);
assertThat("No parses!", sntc.getParses(), not(empty()));
int np = Math.min(max_parses, sntc.getParses().size());
assertThat(np, greaterThan(0));

int pn;
for (pn = 0; pn < np; pn++) {
ParsedSentence parse = sntc.getParses().get(pn);
// Print the phrase string ... handy for debugging.
log.info("; #{}: {}", pn + 1, parse.getPhraseString());

Set<String> binaries = ImmutableSet.copyOf(Splitter.on("\n").omitEmptyStrings().split(SimpleView.printBinaryRelations(parse)));
Set<String> unaries = ImmutableSet.copyOf(Splitter.on("\n").omitEmptyStrings().split(SimpleView.printUnaryRelations(parse)));
log.debug("Binary relations: {}", binaries);
log.debug("Unary relations: {}", unaries);

oc.setParse(parse);
String openCogSchemeStr = oc.toString();
System.out.println("(ListLink (stv 1 1)");
System.out.println(" (AnchorNode \"# New Parsed Sentence\")");
System.out.println(" (SentenceNode \"" + sntc.getID() + "\")");
System.out.println(")\n");

final List<String> logics = Splitter.on("\n").omitEmptyStrings().splitToList(lv.printRelationsNew(parse));
log.info("Logic relations: {}", logics);

assertThat(binaries, equalTo(expectedBinaries));
assertThat(unaries, equalTo(expectedUnaries));
Set<Matcher<? super String>> logicMatchers = FluentIterable.from(expectedLogics)
.transform(new Function<Pattern, Matcher<? super String>>() {
public Matcher<? super String> apply(Pattern input) {
return RegexMatcher.matches(input);
}
}).toSet();
assertThat("Logic relations", logics, Matchers.containsInAnyOrder(logicMatchers));
assertThat("OpenCog Scheme relations is empty", openCogSchemeStr.trim(), not(Matchers.isEmptyString()));
}
}

}
35 changes: 35 additions & 0 deletions src/java_test/relex/output/RegexMatcher.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package relex.output;

import java.util.regex.Pattern;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;

public class RegexMatcher extends BaseMatcher<String> {
private final Pattern regex;

public RegexMatcher(String regex) {
this.regex = Pattern.compile(regex);
}

public RegexMatcher(Pattern regex) {
this.regex = regex;
}

public boolean matches(Object o) {
return regex.matcher((String) o).matches();
}

public void describeTo(Description description) {
description.appendText("matches " + regex);
}

public static RegexMatcher matches(String regex) {
return new RegexMatcher(regex);
}

public static RegexMatcher matches(Pattern regex) {
return new RegexMatcher(regex);
}

}
Binary file added src/test/resources/relex2logic.ods
Binary file not shown.