diff --git a/.classpath b/.classpath
index dfc913d2..96023dca 100644
--- a/.classpath
+++ b/.classpath
@@ -1,10 +1,11 @@
+
-
\ No newline at end of file
+
diff --git a/out/production/Java-SNePS-3.0/.project b/out/production/Java-SNePS-3.0/.project
index d756504d..ff1494d7 100644
--- a/out/production/Java-SNePS-3.0/.project
+++ b/out/production/Java-SNePS-3.0/.project
@@ -5,13 +5,7 @@
-
- org.eclipse.jdt.core.javabuilder
-
-
-
- org.eclipse.jdt.core.javanature
diff --git a/src/sneps/network/Network.java b/src/sneps/network/Network.java
index 5a376ca8..fa47dcc0 100644
--- a/src/sneps/network/Network.java
+++ b/src/sneps/network/Network.java
@@ -1088,6 +1088,8 @@ private static boolean isToBePattern(Object[][] array) {
* the case frame implemented by the new pattern or proposition node.
*
* @return the newly created pattern node or proposition node.
+ * @throws NodeNotFoundInNetworkException
+ * @throws NotAPropositionNodeException
*
* @throws Exception
* if the semantic class specified by the case frame was not
@@ -1095,7 +1097,7 @@ private static boolean isToBePattern(Object[][] array) {
*/
@SuppressWarnings("rawtypes")
- private static Node createPatNode(Object[][] relNodeSet, CaseFrame caseFrame) {
+ private static Node createPatNode(Object[][] relNodeSet, CaseFrame caseFrame) throws NotAPropositionNodeException, NodeNotFoundInNetworkException {
LinkedList dCables = new LinkedList();
for (int i = 0; i < relNodeSet.length; i++) {
@@ -1136,7 +1138,7 @@ else if (caseFrame == RelationsRestrictedCaseFrame.whenDo)
}
- private static Node createPatNode(Object[][] relNodeSet, RelationsRestrictedCaseFrame caseFrame) {
+ private static Node createPatNode(Object[][] relNodeSet, RelationsRestrictedCaseFrame caseFrame) throws NotAPropositionNodeException, NodeNotFoundInNetworkException {
LinkedList dCables = new LinkedList();
for (int i = 0; i < relNodeSet.length; i++) {
dCables.add(new DownCable((Relation) relNodeSet[i][0], (NodeSet) relNodeSet[i][1]));
@@ -1188,6 +1190,8 @@ else if (caseFrame == RelationsRestrictedCaseFrame.whenDo)
* the case frame implemented by the new closed or proposition node.
*
* @return the newly created closed or proposition node.
+ * @throws NodeNotFoundInNetworkException
+ * @throws NotAPropositionNodeException
*
* @throws Exception
* if the semantic class specified by the case frame was not
@@ -1195,7 +1199,7 @@ else if (caseFrame == RelationsRestrictedCaseFrame.whenDo)
*/
@SuppressWarnings("rawtypes")
- private static Node createClosedNode(Object[][] relNodeSet, CaseFrame caseFrame) {
+ private static Node createClosedNode(Object[][] relNodeSet, CaseFrame caseFrame) throws NotAPropositionNodeException, NodeNotFoundInNetworkException {
LinkedList dCables = new LinkedList();
for (int i = 0; i < relNodeSet.length; i++) {
dCables.add(new DownCable((Relation) relNodeSet[i][0], (NodeSet) relNodeSet[i][1]));
@@ -1231,7 +1235,7 @@ private static Node createClosedNode(Object[][] relNodeSet, CaseFrame caseFrame)
}
@SuppressWarnings("rawtypes")
- private static Node createClosedNode(Object[][] relNodeSet, RelationsRestrictedCaseFrame caseFrame) {
+ private static Node createClosedNode(Object[][] relNodeSet, RelationsRestrictedCaseFrame caseFrame) throws NotAPropositionNodeException, NodeNotFoundInNetworkException {
LinkedList dCables = new LinkedList();
for (int i = 0; i < relNodeSet.length; i++) {
dCables.add(new DownCable((Relation) relNodeSet[i][0], (NodeSet) relNodeSet[i][1]));
diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java
index 5ba506c1..bb329d00 100644
--- a/src/sneps/network/Node.java
+++ b/src/sneps/network/Node.java
@@ -6,7 +6,9 @@
import sneps.network.cables.UpCableSet;
import sneps.network.classes.Semantic;
import sneps.network.classes.setClasses.NodeSet;
+import sneps.network.classes.setClasses.VarNodeSet;
import sneps.network.classes.term.Molecular;
+import sneps.network.classes.term.Open;
import sneps.network.classes.term.Term;
import sneps.snebr.Context;
import sneps.snip.channels.Channel;
@@ -94,7 +96,10 @@ public String getSemanticSuperClass() {
* @return the name or the label of the current node.
*/
public String getIdentifier() {
- return this.term.getIdentifier();
+ if(this.term != null)
+ return this.term.getIdentifier();
+ else
+ return "";
}
/**
@@ -120,7 +125,9 @@ public NodeSet getParentNodes() {
*/
@Override
public String toString() {
- return this.term.toString();
+ if(this.term != null)
+ return this.term.toString();
+ return null;
}
/**
@@ -266,5 +273,52 @@ public void setTemp(boolean temp) {
public void updateUpCables() {
((Molecular) this.getTerm()).updateUpCables(this);
}
+
+ public boolean hasSameFreeVariablesAs(Node n) {
+ //this Node is a VariableNode
+ if(this instanceof VariableNode) {
+ //Node to be compared with is also a VariableNode
+ if(n instanceof VariableNode) {
+ if(this.equals(((VariableNode) n)))
+ return true;
+ }
+
+ //Node to be compared with is an Open node
+ if(n.getTerm() instanceof Open) {
+ VarNodeSet freeVars = ((Open) n.getTerm()).getFreeVariables();
+ if((freeVars.size() == 1) && (this.equals(freeVars.getVarNode(0))))
+ return true;
+ }
+ }
+
+ //this Node is an Open node
+ if(this.getTerm() instanceof Open) {
+ VarNodeSet n1freeVars = ((Open) this.getTerm()).getFreeVariables();
+
+ //Node to be compared with is a VariableNode
+ if(n instanceof VariableNode) {
+ if((n1freeVars.size() == 1) &&
+ (n1freeVars.getVarNode(0).equals(((VariableNode) n))))
+ return true;
+ }
+
+ //Node to be compared with is an Open node
+ if(n.getTerm() instanceof Open) {
+ VarNodeSet n2freeVars = ((Open) n.getTerm()).getFreeVariables();
+ if(n1freeVars.size() != n2freeVars.size())
+ return false;
+
+ for(int i = 0; i < n1freeVars.size(); i++) {
+ if(!(n2freeVars.contains(n1freeVars.getVarNode(i)))) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ }
+
+ return false;
+ }
}
diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java
index 79c4b448..8ecd8831 100644
--- a/src/sneps/network/PropositionNode.java
+++ b/src/sneps/network/PropositionNode.java
@@ -15,10 +15,14 @@
import sneps.exceptions.NotAPropositionNodeException;
import java.util.Hashtable;
+import java.util.Set;
+import sneps.snebr.Context;
import sneps.snebr.Support;
+import sneps.snip.InferenceTypes;
import sneps.snip.Pair;
import sneps.snip.Report;
+import sneps.snip.ReportInstances;
import sneps.snip.Runner;
import sneps.snip.channels.AntecedentToRuleChannel;
import sneps.snip.channels.Channel;
@@ -28,54 +32,35 @@
import sneps.snip.matching.LinearSubstitutions;
import sneps.snip.matching.Substitutions;
-public class PropositionNode extends Node implements Serializable{
- private Support basicSupport;
-
+public class PropositionNode extends Node implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ protected Support basicSupport;
protected ChannelSet outgoingChannels;
protected ChannelSet incomingChannels;
- protected ReportSet knownInstances;
+ protected ReportInstances knownInstances;
protected ReportSet newInstances;
public PropositionNode() {
outgoingChannels = new ChannelSet();
incomingChannels = new ChannelSet();
- knownInstances = new ReportSet();
+ knownInstances = new ReportInstances();
newInstances = new ReportSet();
}
-
+
public PropositionNode(Term trm) {
super(Semantic.proposition, trm);
outgoingChannels = new ChannelSet();
incomingChannels = new ChannelSet();
- knownInstances = new ReportSet();
- newInstances = new ReportSet();
- setTerm(trm);
- }
- public PropositionNode(Term trm, Semantic sem) {
- this();
- setTerm(trm);
- setSemanticType(sem);
- }
- public PropositionNode(Semantic sym, Term trm){
- super(sym, trm);
- outgoingChannels = new ChannelSet();
- incomingChannels = new ChannelSet();
- knownInstances = new ReportSet();
- newInstances = new ReportSet();
- }
- public PropositionNode(Semantic sym){
- super(sym);
- outgoingChannels = new ChannelSet();
- incomingChannels = new ChannelSet();
- knownInstances = new ReportSet();
+ knownInstances = new ReportInstances();
newInstances = new ReportSet();
}
- public void processSingleChannelReports(Channel currentChannel) {
+ /*public void processSingleChannelReports(Channel currentChannel) {
ReportSet reports = currentChannel.getReportsBuffer();
for (Report currentReport : reports) {
- Report alteredReport = new Report(currentReport.getSubstitutions(), currentReport.getSupports(),
- currentReport.getSign(), currentReport.getContextName());
+ Report alteredReport = new Report(currentReport.getSubstitutions(), currentReport.getSupport(),
+ currentReport.getSign(), InferenceTypes.BACKWARD);
if (knownInstances.contains(alteredReport)) {
continue;
}else{
@@ -87,12 +72,12 @@ public void processSingleChannelReports(Channel currentChannel) {
currentChannel.clearReportsBuffer();
}
currentChannel.clearReportsBuffer();
- }
+ }*/
- public void processReports() {
+ /*public void processReports() {
for (Channel inChannel : incomingChannels)
processSingleChannelReports(inChannel);
- }
+ }*/
public void broadcastReport(Report report) {
newInstances.addReport(report);
@@ -222,43 +207,88 @@ public boolean alreadyWorking(Channel channel) {
public Support getBasicSupport() {
return basicSupport;
}
+
public void setBasicSupport() throws NotAPropositionNodeException, NodeNotFoundInNetworkException {
this.basicSupport = new Support(this.getId());
}
+
public ChannelSet getOutgoingChannels() {
return outgoingChannels;
}
+
public void setOutgoingChannels(ChannelSet outgoingChannels) {
this.outgoingChannels = outgoingChannels;
}
+
public ChannelSet getIncomingChannels() {
return incomingChannels;
}
+
public void setIncomingChannels(ChannelSet incomingChannels) {
this.incomingChannels = incomingChannels;
}
- public ReportSet getKnownInstances() {
+
+ public ReportInstances getKnownInstances() {
return knownInstances;
}
- public void setKnownInstances(ReportSet knownInstances) {
+
+ public void setKnownInstances(ReportInstances knownInstances) {
this.knownInstances = knownInstances;
}
+
public Hashtable getAssumptionBasedSupport() {
return basicSupport.getAssumptionBasedSupport();
}
+
public Hashtable getJustificationSupport() {
return basicSupport.getJustificationSupport();
}
+
public void addJustificationBasedSupport(PropositionSet propSet) throws NodeNotFoundInPropSetException, NotAPropositionNodeException, NodeNotFoundInNetworkException{
basicSupport.addJustificationBasedSupport(propSet);
}
+
public boolean removeNodeFromSupports(PropositionNode propNode) {
- return basicSupport.removeNodeFromSupports(propNode);
-
+ return basicSupport.removeNodeFromSupports(propNode);
}
public ReportSet getNewInstances() {
return newInstances;
}
+
+ protected Set getOutgoingAntecedentRuleChannels() {
+ return outgoingChannels.getAntRuleChannels();
+ }
+
+ protected Set getOutgoingRuleConsequentChannels() {
+ return outgoingChannels.getRuleConsChannels();
+ }
+
+ protected Set getOutgoingMatchChannels() {
+ return outgoingChannels.getMatchChannels();
+ }
+
+ protected Set getIncomingAntecedentRuleChannels() {
+ return incomingChannels.getAntRuleChannels();
+ }
+
+ protected Set getIncomingRuleConsequentChannels() {
+ return incomingChannels.getRuleConsChannels();
+ }
+
+ protected Set getIncomingMatchChannels() {
+ return incomingChannels.getMatchChannels();
+ }
+
+ public boolean assertedInContext(Context reportContext) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public Channel establishChannel(ChannelTypes rulecons, Node n, LinearSubstitutions linearSubstitutions,
+ LinearSubstitutions linearSubstitutions2, Context currentContext, int j) {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java
index 49a58941..2771a52f 100644
--- a/src/sneps/network/RuleNode.java
+++ b/src/sneps/network/RuleNode.java
@@ -1,13 +1,11 @@
-
package sneps.network;
import java.io.Serializable;
+
+import java.util.ArrayList;
import java.util.HashSet;
-import java.util.Hashtable;
import java.util.Set;
-import sneps.network.classes.Semantic;
-import sneps.network.classes.setClasses.ContextRuisSet;
import sneps.network.classes.setClasses.FlagNodeSet;
import sneps.network.classes.setClasses.NodeSet;
import sneps.network.classes.setClasses.PropositionSet;
@@ -16,9 +14,6 @@
import sneps.network.classes.setClasses.VarNodeSet;
import sneps.network.classes.term.Molecular;
import sneps.network.classes.term.Open;
-import sneps.network.classes.term.Term;
-import sneps.network.classes.term.Variable;
-import sneps.snebr.Context;
import sneps.snebr.Controller;
import sneps.snip.Report;
import sneps.snip.channels.AntecedentToRuleChannel;
@@ -27,85 +22,134 @@
import sneps.snip.channels.RuleToConsequentChannel;
import sneps.snip.classes.FlagNode;
import sneps.snip.classes.RuisHandler;
+import sneps.snip.classes.RuleResponse;
import sneps.snip.classes.RuleUseInfo;
import sneps.snip.classes.SIndex;
+import sneps.snip.matching.LinearSubstitutions;
public abstract class RuleNode extends PropositionNode implements Serializable{
private static final long serialVersionUID = 3891988384679269734L;
- private NodeSet consequents;
+
+ protected NodeSet consequents;
+ protected NodeSet antecedents;
+
/**
- * a NodeSet containing all the pattern antecedents attached to this Node
+ * A NodeSet containing all the pattern antecedents attached to this RuleNode.
*/
protected NodeSet antNodesWithVars;
protected NodeSet antNodesWithoutVars;
protected Set antNodesWithVarsIDs;
protected Set antNodesWithoutVarsIDs;
+
+ /**
+ * Set to true if all the antecedents with variables share the same
+ * variables, false otherwise.
+ */
protected boolean shareVars;
- protected VarNodeSet sharedVars;
- protected ContextRuisSet contextRuisSet;
- private Hashtable contextConstantRUI;
+
+ /**
+ * A VarNodeSet of the common free VariableNodes shared between the antecedents.
+ */
+ protected Set sharedVars;
+
+ /**
+ * A ContextRuisSet that is used to map each context to its appropriate
+ * RuiHandler for this RuleNode.
+ */
+ //protected ContextRuisSet contextRuisSet;
+
+ /**
+ * A RuisHandler that is used to keep track of all the RUIs for this RuleNode.
+ */
+ protected RuisHandler ruisHandler;
+
+ /**
+ * A single RUI that contains all the constant instances found that do not
+ * dominate variables for this RuleNode.
+ */
+ protected RuleUseInfo constantRUI;
+
+ /**
+ * Used for testing.
+ */
+ protected ArrayList reportsToBeSent;
+
- public RuleNode(){
- super();
+ public RuleNode() {
consequents = new NodeSet();
+ antecedents = new NodeSet();
antNodesWithoutVars = new NodeSet();
antNodesWithoutVarsIDs = new HashSet();
antNodesWithVars = new NodeSet();
antNodesWithVarsIDs = new HashSet();
shareVars = false;
- sharedVars = new VarNodeSet();
- contextRuisSet = new ContextRuisSet();
- contextConstantRUI = new Hashtable();
+ sharedVars = new HashSet();
+ reportsToBeSent = new ArrayList();
}
-
- public RuleNode(Semantic sym){
- super(sym);
+
+ public RuleNode(Molecular syn) {
+ super(syn);
consequents = new NodeSet();
+ antecedents = new NodeSet();
antNodesWithoutVars = new NodeSet();
antNodesWithoutVarsIDs = new HashSet();
antNodesWithVars = new NodeSet();
antNodesWithVarsIDs = new HashSet();
shareVars = false;
- sharedVars = new VarNodeSet();
- contextRuisSet = new ContextRuisSet();
- contextConstantRUI = new Hashtable();
+ sharedVars = new HashSet();
+ reportsToBeSent = new ArrayList();
+ }
+
+ public RuisHandler getRuisHandler() {
+ return ruisHandler;
+ }
+
+ public int getAntSize(){
+ return antNodesWithoutVars.size() + antNodesWithVars.size();
}
- public RuleNode(Term syn) {
- super(syn);
- consequents = new NodeSet();
- antNodesWithoutVars = new NodeSet();
- antNodesWithoutVarsIDs = new HashSet();
- antNodesWithVars = new NodeSet();
- antNodesWithVarsIDs = new HashSet();
- shareVars = false;
- sharedVars = new VarNodeSet();
- contextRuisSet = new ContextRuisSet();
- contextConstantRUI = new Hashtable();
+ public NodeSet getAntsWithoutVars() {
+ return antNodesWithoutVars;
+ }
+
+ public NodeSet getAntsWithVars() {
+ return antNodesWithVars;
+ }
+
+ public NodeSet getAntecedents() {
+ return antecedents;
}
- public RuleNode(Semantic sym, Term syn) {
- super(sym, syn);
- consequents = new NodeSet();
- antNodesWithoutVars = new NodeSet();
- antNodesWithoutVarsIDs = new HashSet();
- antNodesWithVars = new NodeSet();
- antNodesWithVarsIDs = new HashSet();
- shareVars = false;
- sharedVars = new VarNodeSet();
- contextRuisSet = new ContextRuisSet();
- contextConstantRUI = new Hashtable();
+ public void setAntecedents(NodeSet antecedents) {
+ this.antecedents = antecedents;
+ }
+
+ public NodeSet getConsequents() {
+ return consequents;
+ }
+
+ public void setConsequents(NodeSet consequents) {
+ this.consequents = consequents;
+ }
+
+ public ArrayList getReplies() {
+ return reportsToBeSent;
}
- protected void sendReportToConsequents(Report reply) {
+ /*protected void sendReportToConsequents(Report reply) {
if(!knownInstances.contains(reply))
newInstances.addReport(reply);
for (Channel outChannel : outgoingChannels)
if(outChannel instanceof RuleToConsequentChannel)
outChannel.addReport(reply);
- }
+ }*/
- protected void processNodes(NodeSet antNodes) {
+ /**
+ * Process antecedent nodes, used for initialization.
+ *
+ * @param antNodes
+ */
+ public void processNodes(NodeSet antNodes) {
this.splitToNodesWithVarsAndWithout(antNodes, antNodesWithVars, antNodesWithoutVars);
for (Node n : antNodesWithVars) {
antNodesWithVarsIDs.add(n.getId());
@@ -117,188 +161,292 @@ protected void processNodes(NodeSet antNodes) {
sharedVars = getSharedVarsNodes(antNodesWithVars);
}
- public void applyRuleHandler(Report report, Node signature) {
- String contextID = report.getContextName();
+ /**
+ * The main method that does all the inference process in the RuleNode. Creates
+ * a RUI for the given report, and inserts it into the appropriate RuisHandler
+ * for this RuleNode. It instantiates a RuisHandler if this is the first report
+ * from a pattern antecedent received. It then applies the inference rules of this
+ * RuleNode on the current stored RUIs.
+ *
+ * @param report
+ * @param signature
+ * The instance that is being reported by the report.
+ * @return
+ */
+ public ArrayList applyRuleHandler(Report report, Node signature) {
+ //System.out.println("---------------------");
+ ArrayList responseList = new ArrayList();
+ ArrayList response = new ArrayList();
+
RuleUseInfo rui;
+ PropositionSet propSet = report.getSupport();
+ FlagNodeSet fns = new FlagNodeSet();
+
if (report.isPositive()) {
- PropositionSet propSet = report.getSupports();
- FlagNodeSet fns = new FlagNodeSet();
fns.insert(new FlagNode(signature, propSet, 1));
- rui = new RuleUseInfo(report.getSubstitutions(),
- 1, 0, fns);
+ rui = new RuleUseInfo(report.getSubstitutions(), 1, 0, fns,
+ report.getInferenceType());
} else {
- PropositionSet propSet = report.getSupports();
- FlagNodeSet fns = new FlagNodeSet();
fns.insert(new FlagNode(signature, propSet, 2));
- rui = new RuleUseInfo(report.getSubstitutions(), 0, 1, fns);
+ rui = new RuleUseInfo(report.getSubstitutions(), 0, 1, fns,
+ report.getInferenceType());
}
- RuisHandler crtemp = contextRuisSet.getByContext(contextID);
- if(crtemp == null){
- crtemp = addContextRUIS(contextID);
+
+ //System.out.println(rui);
+
+ if(antNodesWithoutVars.contains(signature)) {
+ addConstantRui(rui);
+ if (ruisHandler == null) {
+ response = applyRuleOnRui(constantRUI);
+ if(response != null)
+ responseList.addAll(response);
+ }
+ else {
+ RuleUseInfoSet combined = ruisHandler.combineConstantRUI(constantRUI);
+ for (RuleUseInfo tRui : combined) {
+ response = applyRuleOnRui(tRui);
+ if(response != null)
+ responseList.addAll(response);
+ }
+ }
}
-
- RuleUseInfoSet res = crtemp.insertRUI(rui);
- if (res == null)
- res = new RuleUseInfoSet();
- for (RuleUseInfo tRui : res) {
- applyRuleOnRui(tRui, contextID);
+ else {
+ // This is the first report received from a pattern antecedent, so a
+ // ruisHandler is created
+ if(ruisHandler == null)
+ ruisHandler = addRuiHandler();
+
+ // The RUI created for the given report is inserted to the RuisHandler
+ RuleUseInfoSet res = ruisHandler.insertRUI(rui);
+
+ if(constantRUI != null) {
+ RuleUseInfo combined;
+ for (RuleUseInfo tRui : res) {
+ combined = tRui.combine(constantRUI);
+ if(combined != null) {
+ response = applyRuleOnRui(combined);
+ if(response != null)
+ responseList.addAll(response);
+ }
+ }
+ }
+ else {
+ for (RuleUseInfo tRui : res) {
+ response = applyRuleOnRui(tRui);
+ if(response != null)
+ responseList.addAll(response);
+ }
+ }
}
+
+ if(responseList.isEmpty())
+ return null;
+
+ return responseList;
}
- abstract protected void applyRuleOnRui(RuleUseInfo tRui, String contextID);
+ abstract protected ArrayList applyRuleOnRui(RuleUseInfo tRui);
+ /**
+ *
+ * Clears all the information saved by this RuleNode about the instances received.
+ */
public void clear() {
- contextRuisSet.clear();
- contextConstantRUI.clear();
+ if(ruisHandler != null)
+ ruisHandler.clear();
+ constantRUI = null;
+ reportsToBeSent.clear();
}
-
+
+ /**
+ * Returns true if all the nodes in the given NodeSet share the same set of
+ * VariableNodes, and false otherwise.
+ *
+ * @param nodes
+ * @return boolean
+ */
public boolean allShareVars(NodeSet nodes) {
if (nodes.isEmpty())
return false;
- VariableNode n = (VariableNode) nodes.getNode(0);
- boolean res = true;
+ Node n = nodes.getNode(0);
for (int i = 1; i < nodes.size(); i++) {
- if (!n.hasSameFreeVariablesAs((VariableNode) nodes.getNode(i))) {
- res = false;
- break;
+ if (!(n.hasSameFreeVariablesAs(nodes.getNode(i)))) {
+ return false;
}
}
- return res;
- }
-
- public NodeSet getConsequents() {
- return consequents;
+
+ return true;
}
- public void addAntecedent(Node ant){
+ public void addAntecedent(Node ant) {
if(ant instanceof VariableNode || ant.getTerm() instanceof Open)
antNodesWithVars.addNode(ant);
else
antNodesWithoutVars.addNode(ant);
}
-
- public ContextRuisSet getContextRuisSet() {
- return contextRuisSet;
- }
-
- public VarNodeSet getSharedVarsNodes(NodeSet nodes) {
- VarNodeSet res = new VarNodeSet();
- VarNodeSet temp = new VarNodeSet();
+
+ /**
+ * Returns a VarNodeSet of VariableNodes that are shared among all the Nodes in
+ * the given NodeSet.
+ *
+ * @param nodes
+ * @return VarNodeSet
+ */
+ public Set getSharedVarsNodes(NodeSet nodes) {
+ Set res = new HashSet();
+
if (nodes.isEmpty())
return res;
-
- for(Node curNode : nodes){
- if(curNode instanceof VariableNode){
- if(temp.contains((VariableNode)curNode))
- res.addVarNode((VariableNode)curNode);
- else
- temp.addVarNode((VariableNode) curNode);
+
+ if(nodes.getNode(0) instanceof VariableNode)
+ res.add((VariableNode) nodes.getNode(0));
+ else if(nodes.getNode(0).getTerm() instanceof Open) {
+ VarNodeSet freeVars = ((Open) nodes.getNode(0).getTerm()).getFreeVariables();
+ for(VariableNode v : freeVars)
+ res.add(v);
+ }
+
+ if(nodes.size() == 1)
+ return res;
+
+ for(int i = 1; i < nodes.size(); i++) {
+ Set vars = new HashSet();
+ if(nodes.getNode(i) instanceof VariableNode)
+ vars.add((VariableNode) nodes.getNode(i));
+ else if(nodes.getNode(i).getTerm() instanceof Open) {
+ VarNodeSet freeVars = ((Open) nodes.getNode(i).getTerm()).getFreeVariables();
+ for(VariableNode v : freeVars)
+ vars.add(v);
}
- if(curNode.getTerm() instanceof Open){
- VarNodeSet free = ((Open)curNode.getTerm()).getFreeVariables();
- for(VariableNode var : free)
- if(temp.contains(var))
- res.addVarNode(var);
- else
- temp.addVarNode(var);
- }
+ res.retainAll(vars);
}
+
return res;
}
+ /**
+ * Returns a NodeSet of the nodes that are being pointed at, by this RuleNode,
+ * with the DownCables that have the same relation name as the given String.
+ *
+ * @param name
+ * Relation name.
+ * @return NodeSet
+ */
public NodeSet getDownNodeSet(String name) {
- if(term != null && term instanceof Molecular)
+ if(term != null && term instanceof Molecular &&
+ ((Molecular) term).getDownCableSet().getDownCable(name) != null)
return ((Molecular)term).getDownCableSet().getDownCable(name).getNodeSet();
return null;
}
+ /**
+ * Returns a NodeSet of the antecedents down cable set, and in case of AndOr or
+ * Thresh, returns the arguments down cable set.
+ *
+ * @return NodeSet
+ */
public abstract NodeSet getDownAntNodeSet();
+
+ public abstract NodeSet getDownConsqNodeSet();
public NodeSet getUpNodeSet(String name) {
return this.getUpCableSet().getUpCable(name).getNodeSet();
}
- public RuisHandler getContextRuiHandler(String cntxt) {
- return contextRuisSet.getByContext(cntxt);
- }
-
- public RuisHandler addContextRUIS(String contextName) {
+ /**
+ * Creates an appropriate RuisHandler for this RuleNode, according to whether all,
+ * some or none of the variables in the antecedents are shared.
+ *
+ * @return RuisHandler
+ */
+ public RuisHandler addRuiHandler() {
if (sharedVars.size() != 0) {
SIndex si = null;
+ // Antecedents with variables share the same set of variables
if (shareVars)
- si = new SIndex(contextName, sharedVars, SIndex.SINGLETONRUIS);
+ si = new SIndex(SIndex.SINGLETON, sharedVars, antNodesWithVars);
+ // Antecedents share some but not all variables
else
- si = new SIndex(contextName, sharedVars, getSIndexContextType());
- return this.addContextRUIS(si);
- } else {
- return this.addContextRUIS(contextName,createRuisHandler(contextName));
+ si = new SIndex(getSIndexType(), sharedVars, antNodesWithVars);
+
+ return si;
+ }
+
+ else {
+ // PTree in case of and-entailment
+ // RUISet otherwise
+ return createRuisHandler();
}
}
- private RuleUseInfoSet addContextRUIS(SIndex si) {
- // TODO Auto-generated method stub
- return null;
- }
-
- public int getAntSize(){
- return antNodesWithoutVars.size() + antNodesWithVars.size();
- }
+ protected abstract RuisHandler createRuisHandler();
- public RuisHandler addContextRUIS(String cntxt, RuisHandler cRuis) {
- return this.contextRuisSet.addHandlerSet(cntxt, cRuis);
- }
-
- protected abstract RuisHandler createRuisHandler(String contextName);
-
- protected RuleUseInfoSet createContextRUISNonShared(String contextName) {
- return new RuleUseInfoSet(contextName, false);
- }
-
- protected byte getSIndexContextType() {
- return SIndex.RUIS;
- }
-
- protected NodeSet getPatternNodes() {
- return antNodesWithVars;
- }
+ /**
+ * Returns a byte that represents an appropriate SIndex type that is used in case
+ * the antecedents share some but not all variables.
+ * SIndex.PTree: in AndEntailment
+ * SIndex.RUIS: in other rule nodes
+ * @return byte
+ */
+ protected abstract byte getSIndexType();
public void splitToNodesWithVarsAndWithout(NodeSet allNodes, NodeSet withVars, NodeSet WithoutVars) {
for (int i = 0; i < allNodes.size(); i++) {
Node n = allNodes.getNode(i);
- if (isConstantNode(n))
- WithoutVars.addNode(n);
- else
- withVars.addNode(n);
+ addAntecedent(n);
}
}
- public RuleUseInfo addConstantRuiToContext(String context, RuleUseInfo rui) {
- Context contxt = (Context) Controller.getContextByName(context);
- RuleUseInfo tRui = contextConstantRUI.get(contxt);
- if (tRui != null)
- tRui = rui.combine(tRui);
+ public RuleUseInfo addConstantRui(RuleUseInfo rui) {
+ if (constantRUI != null)
+ constantRUI = rui.combine(constantRUI);
else
- tRui = rui;
- if (tRui == null)
+ constantRUI = rui;
+ if (constantRUI == null)
throw new NullPointerException(
- "The existed RUI could not be merged " + "with the given rui so check your code again");
- contextConstantRUI.put(contxt, tRui);
- return tRui;
+ "The existed RUI could not be merged " +
+ "with the given rui so check your code again");
+ return constantRUI;
}
- public RuleUseInfo getConstantRui(Context con) {
- RuleUseInfo tRui = contextConstantRUI.get(con);
- return tRui;
+ public RuleUseInfo getConstantRui() {
+ return constantRUI;
}
-
- public RuleUseInfo getConstantRUI(String context) {
- return contextConstantRUI.get(context);
- }
-
- public static boolean isConstantNode(Node n) {
- return !(n.getTerm() instanceof Molecular) || (n.getTerm() instanceof Variable);
+
+ /**
+ * This method returns all the rule to consequent channels corresponding to a
+ * given report. The send method filters which reports should actually be sent.
+ * @param r
+ * Report
+ * @return
+ * Set
+ */
+ protected Set getOutgoingChannelsForReport(Report r) {
+ // getOutgoingRuleConsequentChannels() returns all the RuleToConsequent
+ // channels already established from before
+ Set outgoingChannels = getOutgoingRuleConsequentChannels();
+ Set replyChannels = new HashSet();
+ for(Node n : consequents) {
+ if(outgoingChannels != null) {
+ // Checking that the same channel has not already been established before
+ for(Channel c : outgoingChannels) {
+ if(c.getRequester().getId() == n.getId() &&
+ r.getSubstitutions().isSubSet(c.getFilter().getSubstitution())) {
+ replyChannels.add(c);
+ break;
+ }
+ }
+ }
+
+ Channel ch = establishChannel(ChannelTypes.RuleCons, n,
+ new LinearSubstitutions(), (LinearSubstitutions)
+ r.getSubstitutions(), Controller.getCurrentContext(), -1);
+ replyChannels.add(ch);
+ }
+
+ return replyChannels;
}
@Override
@@ -346,11 +494,11 @@ public void processReports() {
ReportSet channelReports = currentChannel.getReportsBuffer();
for (Report currentReport : channelReports) {
if (currentChannel instanceof AntecedentToRuleChannel) {
- applyRuleHandler(currentReport, currentChannel.getReporter());
+ //applyRuleHandler(currentReport, currentChannel.getReporter());
}
}
currentChannel.clearReportsBuffer();
}
}
-
+
}
diff --git a/src/sneps/network/VariableNode.java b/src/sneps/network/VariableNode.java
index fb8475e5..3b8f0158 100644
--- a/src/sneps/network/VariableNode.java
+++ b/src/sneps/network/VariableNode.java
@@ -3,13 +3,14 @@
import java.io.Serializable;
import sneps.network.classes.Semantic;
+import sneps.network.classes.setClasses.VarNodeSet;
import sneps.network.classes.setClasses.VariableSet;
+import sneps.network.classes.term.Open;
import sneps.network.classes.term.Term;
import sneps.network.classes.term.Variable;
public class VariableNode extends Node implements Serializable{
private VariableSet freeVariables;
-
private boolean snepslogFlag;
public VariableNode() {
@@ -31,18 +32,6 @@ public VariableNode(Semantic sem, Term trm) {
snepslogFlag = false;
}
- public boolean hasSameFreeVariablesAs(VariableNode node) {
- int i = 0;
- for (Variable var : freeVariables) {
- if (!var.equals(node.getFreeVariables().getVariable(i))) {
- return false;
- } else {
- i++;
- }
- }
- return true;
- }
-
public boolean isSnepslogFlag() {
return snepslogFlag;
}
@@ -54,4 +43,5 @@ public void setSnepslogFlag(boolean snepslogFlag) {
public VariableSet getFreeVariables() {
return freeVariables;
}
+
}
diff --git a/src/sneps/network/classes/setClasses/ChannelSet.java b/src/sneps/network/classes/setClasses/ChannelSet.java
index f9d3b4b9..c78a1e46 100644
--- a/src/sneps/network/classes/setClasses/ChannelSet.java
+++ b/src/sneps/network/classes/setClasses/ChannelSet.java
@@ -1,34 +1,82 @@
package sneps.network.classes.setClasses;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Hashtable;
import java.util.Iterator;
+import java.util.Set;
+import sneps.snip.channels.AntecedentToRuleChannel;
import sneps.snip.channels.Channel;
+import sneps.snip.channels.ChannelTypes;
+import sneps.snip.channels.RuleToConsequentChannel;
-import java.io.Serializable;
-import java.util.HashSet;
-
-/**
- * @className ChannelSet.java
- *
- * @author Amgad Ashraf
- *
- * @version 3.00 31/5/2018
- */
-public class ChannelSet implements Iterable, Serializable {
- private static final long serialVersionUID = -7019589602404627084L;
- private HashSet channels;
+public class ChannelSet implements Iterable {
+ private Hashtable> channels;
public ChannelSet() {
- channels = new HashSet();
+ channels = new Hashtable>();
+ }
+
+ public void addChannel(Channel channel) {
+ ChannelTypes channelType;
+ if (channel instanceof AntecedentToRuleChannel)
+ channelType = ChannelTypes.RuleAnt;
+ else if (channel instanceof RuleToConsequentChannel)
+ channelType = ChannelTypes.RuleCons;
+ else
+ channelType = ChannelTypes.MATCHED;
+ Set targetSet = channels.get(channelType);
+ targetSet.add(channel);
+ channels.put(channelType, targetSet);
}
@Override
public Iterator iterator() {
- return channels.iterator();
+ Set allMergedChannels = new HashSet();
+ Collection> collectionOfSets = channels.values();
+ for (Set set : collectionOfSets)
+ allMergedChannels.addAll(set);
+ return allMergedChannels.iterator();
+ }
+
+ /***
+ * Method acting as a filter for quick HashSet filtering applied on channels
+ * based on request processing status.
+ *
+ * @param processedRequest boolean expressing filter criteria
+ * @return newly created ChannelSet
+ */
+ public ChannelSet getFilteredRequestChannels(boolean processedRequest) {
+ ChannelSet processedRequestsChannels = new ChannelSet();
+ Set allMergedChannels = new HashSet();
+ Collection> collectionOfSets = channels.values();
+ for (Set set : collectionOfSets)
+ allMergedChannels.addAll(set);
+ for (Channel channel : allMergedChannels) {
+ if (channel.isRequestProcessed() == processedRequest)
+ processedRequestsChannels.addChannel(channel);
+ }
+ return processedRequestsChannels;
+ }
+
+ public Set getChannels() {
+ Set allMergedChannels = new HashSet();
+ Collection> collectionOfSets = channels.values();
+ for (Set set : collectionOfSets)
+ allMergedChannels.addAll(set);
+ return allMergedChannels;
}
- public void addChannel(Channel newChannel) {
- channels.add(newChannel);
+ public Set getAntRuleChannels() {
+ return channels.get(ChannelTypes.RuleAnt);
}
+ public Set getRuleConsChannels() {
+ return channels.get(ChannelTypes.RuleCons);
+ }
+
+ public Set getMatchChannels() {
+ return channels.get(ChannelTypes.MATCHED);
+ }
}
diff --git a/src/sneps/network/classes/setClasses/ContextRuisSet.java b/src/sneps/network/classes/setClasses/ContextRuisSet.java
deleted file mode 100644
index 251fb7ef..00000000
--- a/src/sneps/network/classes/setClasses/ContextRuisSet.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package sneps.network.classes.setClasses;
-
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-import sneps.snip.classes.RuisHandler;
-
-public class ContextRuisSet{
- private Hashtable ruisHandlers;
-
- public ContextRuisSet() {
- ruisHandlers = new Hashtable();
- }
-
- /**
- * Adds the given RuisHandler by contextName into this.ruisHandlers
- * @param contextName
- * @param handler
- * @return
- */
- public RuisHandler addHandlerSet(String contextName, RuisHandler handler){
- return ruisHandlers.put(contextName, handler);
- }
-
- /**
- * Checks whether this.ruisHandlers has an entry for the given contextName
- * @param contextID
- * @return
- */
- public boolean hasContext(String contextName) {
- RuisHandler set = ruisHandlers.get(contextName);
- if(set == null)
- return false;
- return true;
- }
-
- /**
- * Gets the stored entry for the given contextName
- * @param contextID
- * @return
- */
- public RuisHandler getByContext(String contextName) {
- return ruisHandlers.get(contextName);
- }
-
- /**
- * Checks whether this.ruisHandlers contains the given handler
- * @param handler
- * @return
- */
- public boolean contains(RuisHandler handler){
- return ruisHandlers.contains(handler);
- }
- public boolean containsKey(String handlerKey){
- return ruisHandlers.containsKey(handlerKey);
- }
- public RuisHandler getHandler(RuisHandler handler){
- return ruisHandlers.get(handler);
- }
- public Enumeration getKeys(){
- return ruisHandlers.keys();
- }
- public int size(){
- return ruisHandlers.size();
- }
- public void remove(String contextName, RuisHandler handler){
- ruisHandlers.remove(handler, handler);
- }
-
- public void clear() {
- ruisHandlers.clear();
- }
-}
diff --git a/src/sneps/network/classes/setClasses/FlagNodeSet.java b/src/sneps/network/classes/setClasses/FlagNodeSet.java
index 25dfe2b0..e683cb21 100644
--- a/src/sneps/network/classes/setClasses/FlagNodeSet.java
+++ b/src/sneps/network/classes/setClasses/FlagNodeSet.java
@@ -5,13 +5,6 @@
import sneps.snip.classes.FlagNode;
-/**
- * @className FlagNodeSet.java
- *
- * @author Amgad Ashraf
- *
- * @version 3.00 31/5/2018
- */
public class FlagNodeSet implements Iterable {
private HashSet flagNodes;
@@ -40,8 +33,7 @@ public boolean isNew() {
* FlagNode
*/
public void insert(FlagNode fn) {
- if (!this.contains(fn))
- flagNodes.add(fn);
+ flagNodes.add(fn);
}
/**
@@ -66,15 +58,18 @@ public FlagNodeSet union(FlagNodeSet f) {
for (FlagNode fn : flagNodes) {
res.insert(fn);
}
+
for (FlagNode fn : f) {
res.insert(fn);
}
+
return res;
}
public int size() {
return flagNodes.size();
}
+
/**
* Check if fn is in this
*
@@ -92,4 +87,29 @@ public void addAll(FlagNodeSet fns) {
for(FlagNode fn : fns)
flagNodes.add(fn);
}
+
+ public String toString() {
+ String res = null;
+ for(FlagNode fn : flagNodes) {
+ if(res != null)
+ res += fn.toString() + "\n";
+ else
+ res = fn.toString() + "\n";
+ }
+
+ return res;
+ }
+
+ public NodeSet getAllNodes() {
+ NodeSet res = new NodeSet();
+ for(FlagNode fn : flagNodes) {
+ res.addNode(fn.getNode());
+ }
+
+ return res;
+ }
+
+ public void clear() {
+ flagNodes.clear();
+ }
}
diff --git a/src/sneps/network/classes/setClasses/PropositionSet.java b/src/sneps/network/classes/setClasses/PropositionSet.java
index f9d9ac02..baaa1936 100644
--- a/src/sneps/network/classes/setClasses/PropositionSet.java
+++ b/src/sneps/network/classes/setClasses/PropositionSet.java
@@ -89,7 +89,7 @@ public static int[] removeDuplicates(int[] props) {
*
* @return an int array containing the props
*/
- private int[] getProps() {
+ public int[] getProps() {
return props;
}
diff --git a/src/sneps/network/classes/setClasses/ReportSet.java b/src/sneps/network/classes/setClasses/ReportSet.java
index 3abadb94..8f33f9e3 100644
--- a/src/sneps/network/classes/setClasses/ReportSet.java
+++ b/src/sneps/network/classes/setClasses/ReportSet.java
@@ -6,13 +6,6 @@
import sneps.snip.Report;
-/**
- * @className ReportSet.java
- *
- * @author Amgad Ashraf
- *
- * @version 3.00 31/5/2018
- */
public class ReportSet implements Iterable, Serializable {
private static final long serialVersionUID = 508832573392879123L;
private HashSet reports;
@@ -21,12 +14,12 @@ public ReportSet() {
reports = new HashSet();
}
- public void addReport(Report rport){
+ public void addReport(Report rport) {
reports.add(rport);
}
@Override
- public Iterator iterator(){
+ public Iterator iterator() {
return reports.iterator();
}
@@ -37,7 +30,6 @@ public boolean contains(Report report) {
public void clear() {
reports = new HashSet();
}
-
public boolean isEmpty() {
return reports.isEmpty();
diff --git a/src/sneps/network/classes/setClasses/RuleUseInfoSet.java b/src/sneps/network/classes/setClasses/RuleUseInfoSet.java
index 0b953455..094377a7 100644
--- a/src/sneps/network/classes/setClasses/RuleUseInfoSet.java
+++ b/src/sneps/network/classes/setClasses/RuleUseInfoSet.java
@@ -1,28 +1,27 @@
package sneps.network.classes.setClasses;
-import java.util.HashSet;
+import java.util.HashSet;
import java.util.Iterator;
import sneps.snip.classes.RuisHandler;
import sneps.snip.classes.RuleUseInfo;
-/**
- * @className RuleUseInfoSet.java
- *
- * @author Amgad Ashraf
- *
- * @version 3.00 31/5/2018
- */
-public class RuleUseInfoSet extends RuisHandler implements Iterable {
+public class RuleUseInfoSet implements RuisHandler, Iterable {
private HashSet ruis;
-
- public RuleUseInfoSet(String contextName, boolean b) {
- super(contextName);
+
+ /**
+ * A boolean indicating whether this RuleUseInfoSet is treated as a single
+ * RuleUseInfo.
+ */
+ private boolean singleton;
+
+ public RuleUseInfoSet() {
ruis = new HashSet();
}
- public RuleUseInfoSet() {
+ public RuleUseInfoSet(boolean singleton) {
ruis = new HashSet();
+ this.singleton = singleton;
}
@Override
@@ -30,34 +29,78 @@ public Iterator iterator() {
return ruis.iterator();
}
- public boolean add(RuleUseInfo rui) {
- return ruis.add(rui);
+ public RuleUseInfoSet add(RuleUseInfo rui) {
+ ruis.add(rui);
+ return this;
}
+ @Override
+ public RuleUseInfoSet insertRUI(RuleUseInfo rui) {
+ //In case of inserting into a RUI set
+ if(!singleton)
+ return combineAdd(rui);
+
+ //In case of inserting into a singleton RUI
+ if(isEmpty())
+ return add(rui);
+
+ ruis = combine(rui).getRuis();
+ return this;
+ }
+
+ /**
+ * Combines rui with every RUI in this RUISet.
+ * @param rui
+ * @return RuleUseInfoSet
+ */
+ public RuleUseInfoSet combine(RuleUseInfo rui) {
+ RuleUseInfoSet res = new RuleUseInfoSet();
+ for (RuleUseInfo tRui : ruis) {
+ RuleUseInfo tmp = rui.combine(tRui);
+ if (tmp != null)
+ res.add(tmp);
+ }
+
+ return res;
+ }
+
+ /**
+ * Combines every RUI in this RUISet with every RUI in second.
+ * @param second
+ * RUISet
+ * @return
+ * Combined RUISet
+ */
public RuleUseInfoSet combine(RuleUseInfoSet second) {
- RuleUseInfoSet res = new RuleUseInfoSet(this.context, false);
+ RuleUseInfoSet res = new RuleUseInfoSet(false);
for(RuleUseInfo rui1 : this){
- for(RuleUseInfo rui2: second){
- if(rui1.isDisjoint(rui2))
+ for(RuleUseInfo rui2 : second){
+ //if(rui1.isDisjoint(rui2))
res.add(rui1.combine(rui2));
}
}
+
return res;
}
- @Override
- public RuleUseInfoSet insertRUI(RuleUseInfo rui) {
- ruis.add(rui);
+ /**
+ * Adds all the RUIs in rootRUIS to this RUISet.
+ * @param rootRUIS
+ * @return boolean
+ */
+ public RuleUseInfoSet addAll(RuleUseInfoSet rootRUIS) {
+ for(RuleUseInfo rui : rootRUIS)
+ ruis.add(rui);
+
return this;
}
-
- public boolean addAll(RuleUseInfoSet rootRUIS) {
- boolean flag = true;
- for(RuleUseInfo rui : rootRUIS){
- if(!ruis.add(rui))
- flag = false;
- }
- return flag;
+
+ public RuleUseInfoSet combineAdd(RuleUseInfo rui) {
+ RuleUseInfoSet temp = this.combine(rui);
+ temp.add(rui);
+ this.addAll(temp);
+
+ return this;
}
public boolean contains(RuleUseInfo rui){
@@ -67,4 +110,30 @@ public boolean contains(RuleUseInfo rui){
public boolean isEmpty() {
return ruis.isEmpty();
}
+
+ public int size() {
+ return ruis.size();
+ }
+
+ public void clear() {
+ ruis.clear();
+ }
+
+ public HashSet getRuis() {
+ return ruis;
+ }
+
+ public String toString() {
+ String res = null;
+ for(RuleUseInfo rui : ruis) {
+ res = rui.toString() + " ";
+ }
+
+ return res;
+ }
+
+ @Override
+ public RuleUseInfoSet combineConstantRUI(RuleUseInfo rui) {
+ return combine(rui);
+ }
}
diff --git a/src/sneps/network/classes/setClasses/VarNodeSet.java b/src/sneps/network/classes/setClasses/VarNodeSet.java
index 12d662c3..5072bcb3 100644
--- a/src/sneps/network/classes/setClasses/VarNodeSet.java
+++ b/src/sneps/network/classes/setClasses/VarNodeSet.java
@@ -5,13 +5,6 @@
import sneps.network.VariableNode;
-/**
- * @className VarNodeSet.java
- *
- * @author Amgad Ashraf
- *
- * @version 3.00 31/5/2018
- */
public class VarNodeSet implements Iterable {
protected Vector variables;
@@ -24,18 +17,19 @@ public Iterator iterator() {
return variables.iterator();
}
- public VariableNode getVarNode(int index){
+ public VariableNode getVarNode(int index) {
return variables.get(index);
}
public void addVarNode(VariableNode n) {
- variables.add(n);
+ if(!(variables.contains(n))) {
+ variables.add(n);
+ }
}
public void addAll(VarNodeSet allVariables) {
- for (int i = 0; i < variables.size(); i++) {
- this.addVarNode(allVariables.getVarNode(i));
- }
+ for (VariableNode v : allVariables)
+ this.addVarNode(v);
}
public int size() {
@@ -54,11 +48,24 @@ public void remove(VariableNode variable) {
variables.remove(variable);
}
- public static VarNodeSet union(VarNodeSet v1, VarNodeSet v2){
- VarNodeSet v3 = v2;
- for(VariableNode var : v1)
- if(!v3.contains(var))
- v3.addVarNode(var);
- return v3;
+ public static VarNodeSet union(VarNodeSet v1, VarNodeSet v2) {
+ VarNodeSet union = new VarNodeSet();
+ for(VariableNode v : v1)
+ union.addVarNode(v);
+ for(VariableNode v : v2)
+ union.addVarNode(v);
+
+ return union;
+ }
+
+ public String toString() {
+ String res = null;
+ for(VariableNode v : variables) {
+ if(res == null)
+ res = v + " ";
+ else
+ res += v + " ";
+ }
+ return res;
}
}
diff --git a/src/sneps/network/classes/term/Molecular.java b/src/sneps/network/classes/term/Molecular.java
index 5125c56c..59dc279b 100644
--- a/src/sneps/network/classes/term/Molecular.java
+++ b/src/sneps/network/classes/term/Molecular.java
@@ -26,6 +26,10 @@ public Molecular(String identifier, DownCableSet downCableSet){
super(identifier);
this.downCableSet = downCableSet;
}
+
+ public Molecular(String id) {
+ super(id);
+ }
public DownCableSet getDownCableSet() {
return this.downCableSet;
diff --git a/src/sneps/network/classes/term/Open.java b/src/sneps/network/classes/term/Open.java
index a87ab1d3..a6602b49 100644
--- a/src/sneps/network/classes/term/Open.java
+++ b/src/sneps/network/classes/term/Open.java
@@ -28,9 +28,19 @@ public Open(String identifier, DownCableSet dCableSet) {
this.variables = new VarNodeSet();
this.updateFreeVariables();
}
+
+ public Open(String id) {
+ super(id);
+ this.variables = new VarNodeSet();
+ }
+
public VarNodeSet getFreeVariables() {
return variables;
}
+
+ public void addFreeVariable(VariableNode n) {
+ variables.addVarNode(n);
+ }
/**
* The method that populate the list of free variables by the
diff --git a/src/sneps/snebr/Support.java b/src/sneps/snebr/Support.java
index 55132e67..029522fa 100644
--- a/src/sneps/snebr/Support.java
+++ b/src/sneps/snebr/Support.java
@@ -26,6 +26,10 @@ public class Support implements Serializable{
private boolean hasChildren;
private boolean TreeComputed;
+ public Support() {
+
+ }
+
public Support(int id) throws NotAPropositionNodeException, NodeNotFoundInNetworkException {
this.id = id;
assumptionBasedSupport = new Hashtable();
diff --git a/src/sneps/snip/InferenceTypes.java b/src/sneps/snip/InferenceTypes.java
new file mode 100644
index 00000000..244cc4ec
--- /dev/null
+++ b/src/sneps/snip/InferenceTypes.java
@@ -0,0 +1,5 @@
+package sneps.snip;
+
+public enum InferenceTypes {
+ FORWARD, BACKWARD;
+}
diff --git a/src/sneps/snip/Report.java b/src/sneps/snip/Report.java
index c0164d10..b621d830 100644
--- a/src/sneps/snip/Report.java
+++ b/src/sneps/snip/Report.java
@@ -1,41 +1,84 @@
package sneps.snip;
+import sneps.exceptions.NodeNotFoundInNetworkException;
+import sneps.exceptions.NotAPropositionNodeException;
+import sneps.network.Network;
+import sneps.network.PropositionNode;
import sneps.network.classes.setClasses.PropositionSet;
+import sneps.snebr.Context;
import sneps.snip.matching.Substitutions;
-/**
- * @className Report.java
- *
- * @author Amgad Ashraf
- *
- * @version 3.00 31/5/2018
- */
public class Report {
private Substitutions substitution;
- private PropositionSet supports;
+ private PropositionSet support;
private boolean sign;
- private String contextName;
+ private InferenceTypes inferenceType;
- public Report(Substitutions substitution, PropositionSet set, boolean sign, String contextID) {
- this.substitution = substitution;
- this.supports = set;
- this.sign = sign;
- this.contextName = contextID;
- }
+ public Report(Substitutions substitution, PropositionSet suppt, boolean sign, InferenceTypes inference) {
+ this.substitution = substitution;
+ this.support = suppt;
+ this.sign = sign;
+ this.inferenceType = inference;
+ }
+
+ public boolean anySupportAssertedInContext(Context reportContext)
+ throws NotAPropositionNodeException, NodeNotFoundInNetworkException {
+ int[] reportSupportsSet = support.getProps();
+ int currentPropNodeId;
+ for (int i = 0; i < reportSupportsSet.length; i++) {
+ currentPropNodeId = reportSupportsSet[i];
+ PropositionNode retrievedNode = (PropositionNode) Network.getNodeById(currentPropNodeId);
+ if (retrievedNode.assertedInContext(reportContext))
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * This method first checks if the substitutions of this report and the given
+ * report are compatible. If they are, it returns a new report with the combined
+ * subs and supports of the two reports.
+ * @param r
+ * Report
+ * @return
+ */
+ public Report combine(Report r) {
+ if(substitution.isCompatible(r.getSubstitutions())) {
+ Substitutions combinedSubs = substitution.union(r.getSubstitutions());
+ PropositionSet combinedSupport = new PropositionSet();
+ try {
+ combinedSupport = support.union(r.getSupport());
+ } catch (NotAPropositionNodeException |
+ NodeNotFoundInNetworkException e1) {
+ }
+
+ InferenceTypes resultingType;
+ if(inferenceType.equals(InferenceTypes.FORWARD) ||
+ r.getInferenceType().equals(InferenceTypes.FORWARD))
+ resultingType = InferenceTypes.FORWARD;
+ else
+ resultingType = InferenceTypes.BACKWARD;
+
+ return new Report(combinedSubs,
+ combinedSupport, sign, resultingType);
+ }
+
+ return null;
+ }
public Substitutions getSubstitutions() {
return substitution;
}
- public PropositionSet getSupports() {
- return supports;
+ public PropositionSet getSupport() {
+ return support;
}
@Override
public boolean equals(Object report) {
Report castedReport = (Report) report;
- return this.substitution.equals(castedReport.substitution) && this.sign == castedReport.sign
- && this.contextName == castedReport.contextName;
+ return this.substitution.equals(castedReport.substitution) &&
+ this.sign == castedReport.sign;
}
public boolean getSign() {
@@ -50,11 +93,21 @@ public boolean isNegative() {
return !sign;
}
- public String toString() {
- return "ContextID : " + contextName + "\nSign: " + sign + "\nSubstitution: " + substitution + "\nSupport: " + supports.toString();
+ public void toggleSign() {
+ this.sign = !this.sign;
}
- public String getContextName() {
- return contextName;
+ public String toString() {
+ return "Sign: " + sign + "\nSubstitution: " + substitution + "\nSupport: "
+ + support + "\nType: " + inferenceType;
}
-}
+
+ public InferenceTypes getInferenceType() {
+ return inferenceType;
+ }
+
+ public void setInferenceType(InferenceTypes inferenceType) {
+ this.inferenceType = inferenceType;
+ }
+
+}
\ No newline at end of file
diff --git a/src/sneps/snip/ReportInstances.java b/src/sneps/snip/ReportInstances.java
new file mode 100644
index 00000000..5f30ed36
--- /dev/null
+++ b/src/sneps/snip/ReportInstances.java
@@ -0,0 +1,41 @@
+package sneps.snip;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.Set;
+
+import sneps.snip.matching.Substitutions;
+
+public class ReportInstances implements Iterable {
+ Hashtable> instances;
+
+ public ReportInstances() {
+ instances = new Hashtable>();
+ }
+
+ public void addReport(Report report) {
+ Substitutions reportSubs = report.getSubstitutions();
+ Set reportsSet = instances.remove(reportSubs);
+ reportsSet.add(report);
+ instances.put(reportSubs, reportsSet);
+ }
+
+ public Set getReportBySubstitutions(Substitutions subs) {
+ return instances.get(subs);
+ }
+
+ public Iterator iterator() {
+ Set allMergedReports = new HashSet();
+ Collection> collectionOfSets = instances.values();
+ for (Set set : collectionOfSets)
+ allMergedReports.addAll(set);
+ return allMergedReports.iterator();
+ }
+
+ public boolean isEmpty() {
+ return instances.isEmpty();
+ }
+
+}
\ No newline at end of file
diff --git a/src/sneps/snip/Runner.java b/src/sneps/snip/Runner.java
index a5d97de5..16f70eb8 100644
--- a/src/sneps/snip/Runner.java
+++ b/src/sneps/snip/Runner.java
@@ -2,68 +2,96 @@
import java.util.ArrayDeque;
import java.util.Deque;
+import java.util.Hashtable;
import java.util.Queue;
import sneps.network.ActNode;
import sneps.network.Node;
+import sneps.network.PropositionNode;
public class Runner {
-
- private static Queue highQueue;
- private static Queue lowQueue;
- private static Deque actQueue;
-
- public static void initiate() {
- highQueue = new ArrayDeque();
- lowQueue = new ArrayDeque();
- actQueue = new ArrayDeque();
- }
- public static String run() {
- String sequence = "";
- main: while(!highQueue.isEmpty() || !lowQueue.isEmpty() || !actQueue.isEmpty()) {
- while(!highQueue.isEmpty()) {
- System.out.println("\n\n");
- System.out.println(" AT HIGH QUEUE ");
- Node toRunNext = highQueue.poll();
- System.out.println(toRunNext);
- System.out.println("\n\n");
- toRunNext.processReports();
- sequence += 'H';
- }
- while(!lowQueue.isEmpty()) {
- System.out.println("in");
- Node toRunNext = lowQueue.poll();
- toRunNext.processRequests();
- sequence += 'L';
- if(!highQueue.isEmpty())
- continue main;
- }
- while(!actQueue.isEmpty()) {
- System.out.println("AT ACT QUEUE");
- ActNode toRunNext = actQueue.removeLast();
- System.out.println(toRunNext + " agenda: " + toRunNext.getAgenda());
- System.out.println("\n\n");
- toRunNext.processIntends();
- sequence += 'A';
- if(!highQueue.isEmpty() || !lowQueue.isEmpty()) {
- continue main;
- }
- }
- }
- return sequence;
- }
-
- public static void addToHighQueue(Node node) {
- highQueue.add(node);
- }
-
- public static void addToLowQueue(Node node) {
- lowQueue.add(node);
- }
-
- public static void addToActStack(ActNode node) {
- actQueue.addLast(node);
- }
+ private static Queue highQueue;
+ private static Queue lowQueue;
+ private static Deque actQueue;
+ private static Hashtable forwardAssertedNodes;
-}
+ public static void initiate() {
+ highQueue = new ArrayDeque();
+ lowQueue = new ArrayDeque();
+ actQueue = new ArrayDeque();
+ forwardAssertedNodes = new Hashtable();
+ }
+
+ public static String run() {
+ String sequence = "";
+ main: while (!highQueue.isEmpty() || !lowQueue.isEmpty() || !actQueue.isEmpty()) {
+ while (!highQueue.isEmpty()) {
+ System.out.println("\n\n");
+ System.out.println(" AT HIGH QUEUE ");
+ Node toRunNext = highQueue.poll();
+ System.out.println(toRunNext);
+ System.out.println("\n\n");
+ toRunNext.processReports();
+ sequence += 'H';
+ }
+ while (!lowQueue.isEmpty()) {
+ System.out.println("in");
+ Node toRunNext = lowQueue.poll();
+ toRunNext.processRequests();
+ sequence += 'L';
+ if (!highQueue.isEmpty())
+ continue main;
+ }
+ while (!actQueue.isEmpty()) {
+ System.out.println("AT ACT QUEUE");
+ ActNode toRunNext = actQueue.removeLast();
+ System.out.println(toRunNext + " agenda: " + toRunNext.getAgenda());
+ System.out.println("\n\n");
+ toRunNext.processIntends();
+ sequence += 'A';
+ if (!highQueue.isEmpty() || !lowQueue.isEmpty()) {
+ continue main;
+ }
+ }
+ }
+ return sequence;
+ }
+
+ public static void addToHighQueue(Node node) {
+ highQueue.add(node);
+ }
+
+ public static void addToLowQueue(Node node) {
+ lowQueue.add(node);
+ }
+
+ public static void addToActStack(ActNode node) {
+ actQueue.addLast(node);
+ }
+
+ /***
+ * Method used to keep track of asserted nodes with a specific certain report as
+ * its hash in the hashtable forwardAssertedNodes instance
+ *
+ * @param report
+ * @param node
+ */
+ public static void addNodeAssertionThroughFReport(Report report, PropositionNode node) {
+ forwardAssertedNodes.put(report, node);
+ }
+
+ /***
+ * Method checks if the given node was asserted (added in the
+ * forwardAssertedNodes instance) with a forward report
+ *
+ * @param node
+ * @return
+ */
+ public static boolean isNodeAssertedThroughForwardInf(PropositionNode node) {
+ if(forwardAssertedNodes != null)
+ return forwardAssertedNodes.containsValue(node);
+ else
+ return false;
+ }
+}
\ No newline at end of file
diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java
index d7259600..290e9203 100644
--- a/src/sneps/snip/channels/Channel.java
+++ b/src/sneps/snip/channels/Channel.java
@@ -42,7 +42,7 @@ public Channel(Substitutions switchSubstitution,
public boolean addReport(Report report) {
System.out.println("Can pass " + filter.canPass(report));
- if (filter.canPass(report) && contextName == report.getContextName()) {
+ if (filter.canPass(report)) {
System.out.println("\n\nThe Switch data:\n" + switch_);
switch_.switchReport(report);
reportsBuffer.addReport(report);
@@ -80,4 +80,9 @@ public void setValve(boolean valve) {
public void clearReportsBuffer() {
reportsBuffer.clear();
}
+
+ public boolean isRequestProcessed() {
+ // TODO Auto-generated method stub
+ return false;
+ }
}
diff --git a/src/sneps/snip/classes/FlagNode.java b/src/sneps/snip/classes/FlagNode.java
index ebdaefd7..989531cc 100644
--- a/src/sneps/snip/classes/FlagNode.java
+++ b/src/sneps/snip/classes/FlagNode.java
@@ -5,7 +5,7 @@
public class FlagNode {
private Node node;
- private PropositionSet supports;
+ private PropositionSet support;
private int flag;
/**
@@ -15,12 +15,12 @@ public class FlagNode {
* node
* @param set
* support
- * @param f
+ * @param f,
* true or false
*/
public FlagNode(Node n, PropositionSet set, int f) {
node = n;
- supports = set;
+ support= set;
flag = f;
}
@@ -38,8 +38,8 @@ public Node getNode() {
*
* @return support
*/
- public PropositionSet getSupports() {
- return supports;
+ public PropositionSet getSupport() {
+ return support;
}
/**
@@ -60,7 +60,12 @@ public int getFlag() {
* @return true or false
*/
public boolean isEqual(FlagNode fn) {
- return fn.node == node && fn.supports == supports && fn.flag == flag;
+ return fn.node == node && fn.support == support && fn.flag == flag;
+ }
+
+ public String toString() {
+ return "Proposiiton: " + node.toString() + " Supports: " + support +
+ " Flag: " + flag;
}
}
diff --git a/src/sneps/snip/classes/PTree.java b/src/sneps/snip/classes/PTree.java
index 078a9e67..0f5921ab 100644
--- a/src/sneps/snip/classes/PTree.java
+++ b/src/sneps/snip/classes/PTree.java
@@ -24,20 +24,19 @@
*
* @ClassDescription A PTree is a binary tree structure. Every AndEntailment rule node stores combinations of antecedent RUIs inside a PTree because of its optimized structure.
* A PTree class follows an algorithm for construction and insertion, having leaf nodes representing RUIs of rule antecedents and root nodes representing combined RUIs of the rule itself.
- *
- * @author Amgad Ashraf
- * @version 3.00 31/5/2018
*/
-public class PTree extends RuisHandler {
+public class PTree implements RuisHandler {
private Hashtable patternVariables;//PatternId, VariableNodes
private Hashtable> variablePatterns;//VariableNode, PatternIds
private VarNodeSet notProccessed;
private HashSet subTrees;
+ /**
+ * Maps every pattern to a subTree.
+ */
private Hashtable subTreesMap;
/**
* Constructor for the PTree
- * @param context
*/
public PTree() {
super();
@@ -52,11 +51,11 @@ public PTree() {
* Builds the PTree by preparing pattern variables set, variable patterns set, pattern sequence and finally constructing the tree bottom up
* @param ants
*/
- public void buildTree(NodeSet ants){
+ public void buildTree(NodeSet ants) {
fillPVandVP(ants);
- Queue patternSequence = getPatternSequence();
-
+ Queue patternSequence = getPatternSequence();
+
constructBottomUp(patternSequence);
patternVariables = new Hashtable();
@@ -68,82 +67,86 @@ public void buildTree(NodeSet ants){
* Prepares both pattern variables set and variable patterns set
* @param ants
*/
- private void fillPVandVP(NodeSet ants) {
- for(Node pattern : ants){
- int id = pattern.getId();
+ public void fillPVandVP(NodeSet ants) {
+ for(Node pattern : ants) {
+ int patId = pattern.getId();
Term term = pattern.getTerm();
- VarNodeSet vars = patternVariables.get(id);
+ VarNodeSet vars = patternVariables.get(patId);
if(vars == null || vars.isEmpty())
vars = new VarNodeSet();
- Set pats = variablePatterns.get(id);
- if(pats == null || pats.isEmpty())
- pats = new HashSet();
- if(term instanceof Variable){
+ if(term instanceof Variable) {
vars.addVarNode((VariableNode) pattern);
notProccessed.addVarNode((VariableNode) pattern);
}
- if(term instanceof Open){
- VarNodeSet freeVars = ((Open)term).getFreeVariables();
+ if(term instanceof Open) {
+ VarNodeSet freeVars = ((Open) term).getFreeVariables();
vars.addAll(freeVars);
notProccessed.addAll(freeVars);
}
- patternVariables.put(id, vars);
- }
-
- Set pats = patternVariables.keySet();
- for(int curPat : pats){
- VarNodeSet vars = patternVariables.get(curPat);
- if(!(vars.isEmpty()) && !(vars == null)){
- for(VariableNode curVar : vars){
- Set pat = variablePatterns.get(curVar);
- if(pat == null){
- pat = new HashSet();
- pat.add(curPat);
- variablePatterns.put(curVar, pat);
- continue;
- }
- if(!pat.contains(curPat)){
- pat.add(curPat);
- variablePatterns.put(curVar, pat);
- }
+
+ patternVariables.put(patId, vars);
+
+ for(VariableNode curVar : vars) {
+ Set pats = variablePatterns.get(curVar);
+ if(pats == null) {
+ pats = new HashSet();
+ pats.add(patId);
+ variablePatterns.put(curVar, pats);
+ continue;
+ }
+
+ if(!pats.contains(patId)) {
+ pats.add(patId);
+ variablePatterns.put(curVar, pats);
}
}
}
}
+
/**
* Prepares pattern sequence into a sequence of PTreeNodes ready for construction
* @return
*/
- private Queue getPatternSequence() {
+ public Queue getPatternSequence() {
LinkedHashSet res = new LinkedHashSet();
Queue treeNodes = new LinkedList();
-
- for(VariableNode currentVar : notProccessed){
- Set vPatternsIds = variablePatterns.get(currentVar);
-
- for(int currentPatId : vPatternsIds)
- if(!res.contains(currentPatId)){
- res.add(currentPatId);
-
- VarNodeSet vs = new VarNodeSet();
- vs.addVarNode(currentVar);
- Set pats = new HashSet();
- pats.add(currentPatId);
-
- treeNodes.add(new PTreeNode(pats, vs));
+ VarNodeSet toBeProcessed = new VarNodeSet();
+
+ while(!notProccessed.isEmpty()) {
+ toBeProcessed.addVarNode(notProccessed.iterator().next());
+ while (!toBeProcessed.isEmpty()) {
+ VariableNode var = toBeProcessed.iterator().next();
+ Set vPatternsIds = variablePatterns.get(var);
+ for(int currentPatId : vPatternsIds) {
+ if(!res.contains(currentPatId)) {
+ res.add(currentPatId);
+ VarNodeSet patVarSet = patternVariables.get(currentPatId);
+ toBeProcessed.addAll(patVarSet);
+ }
}
+
+ toBeProcessed.remove(var);
+ notProccessed.remove(var);
+ }
}
+
+ for (int pat : res) {
+ Set pats = new HashSet();
+ pats.add(pat);
+ treeNodes.add(new PTreeNode(pats, patternVariables.get(pat)));
+ }
+
return treeNodes;
-
}
+
/**
* Uses given ordered PTreeNodes to construct the PTree
* If no two adjacent nodes in the sequence share variables, a PSubTree is handled
* @param treeNodes
*/
- private void constructBottomUp(Queue treeNodes) {
+ public void constructBottomUp(Queue treeNodes) {
PTreeNode head = treeNodes.poll();
if (treeNodes.isEmpty()) {
processSubTree(head);
@@ -167,20 +170,23 @@ private void constructBottomUp(Queue treeNodes) {
head = second;
}
}
+
if (head != null)
newTreeNodes.add(head);
+
if (sharing)
constructBottomUp(newTreeNodes);
else
for(PTreeNode subHead : newTreeNodes)
processSubTree(subHead);
}
+
/**
* Creates a PSubTree and inserts it into subTrees and subTreesMap
* @param subHead
*/
private void processSubTree(PTreeNode subHead) {
- if(subHead != null){
+ if(subHead != null) {
PSubTree subTree = new PSubTree(subHead);
subTrees.add(subTree);
for (int id : subHead.getPats()) {
@@ -194,9 +200,8 @@ private void processSubTree(PTreeNode subHead) {
public RuleUseInfoSet insertRUI(RuleUseInfo rui) {
Stack stack = new Stack();
FlagNodeSet fns = rui.getFlagNodeSet();
- for(FlagNode node : fns){
+ for(FlagNode node : fns) {
int pattern = node.getNode().getId();
-
PSubTree subTree = subTreesMap.get(pattern);
RuleUseInfoSet returned = new RuleUseInfoSet();
if(subTree != null)
@@ -209,8 +214,10 @@ public RuleUseInfoSet insertRUI(RuleUseInfo rui) {
tSet = new RuleUseInfoSet();
stack.push(tSet);
}
+
stack.push(returned);
}
+
return multiply(stack);
}
@@ -237,6 +244,7 @@ private boolean sharingVars(PTreeNode head, PTreeNode second) {
return true;
return false;
}
+
private VarNodeSet getSharedVars(PTreeNode first, PTreeNode second) {
VarNodeSet smaller = null, bigger = null, intersection = new VarNodeSet();
if (first.getVars().size() > second.getVars().size()) {
@@ -249,23 +257,43 @@ private VarNodeSet getSharedVars(PTreeNode first, PTreeNode second) {
for (VariableNode i : smaller)
if (bigger.contains(i))
intersection.addVarNode(i);
+
return intersection;
}
+
private Set union(Set vars1, Set vars2) {
Set union = new HashSet();
- for(int strng : vars1){
- if(vars2.contains(strng))
- union.add(strng);
- }
+ for(int strng : vars1)
+ union.add(strng);
+ for(int strng : vars2)
+ union.add(strng);
return union;
}
+ public VarNodeSet getNotProccessed() {
+ return notProccessed;
+ }
+
+ public void setNotProccessed(VarNodeSet notProccessed) {
+ this.notProccessed = notProccessed;
+ }
+
+ public Hashtable getPatternVariables() {
+ return patternVariables;
+ }
+
+ public Hashtable> getVariablePatterns() {
+ return variablePatterns;
+ }
+
public HashSet getSubTrees() {
return subTrees;
}
+
public void setSubTrees(HashSet subTrees) {
this.subTrees = subTrees;
}
+
public Hashtable getSubTreesMap() {
return subTreesMap;
}
@@ -273,38 +301,63 @@ public Hashtable getSubTreesMap() {
public void setSubTreesMap(Hashtable subTreesMap) {
this.subTreesMap = subTreesMap;
}
- public RuleUseInfoSet getAllRootRuis(){
+
+ public RuleUseInfoSet getAllRootRuis() {
RuleUseInfoSet res = new RuleUseInfoSet();
for(PSubTree subtree : subTrees)
res.addAll(subtree.getRootRUIS());
return res;
}
+
+ @Override
+ public RuleUseInfoSet combineConstantRUI(RuleUseInfo rui) {
+ RuleUseInfoSet res = new RuleUseInfoSet();
+ RuleUseInfoSet ruis = getAllRootRuis();
+ if (ruis != null) {
+ RuleUseInfo combined;
+ for (RuleUseInfo r : ruis) {
+ combined = r.combine(rui);
+ if (combined != null)
+ res.add(combined);
+ }
+ }
+
+ return res;
+ }
+
+ @Override
+ public void clear() {
+ patternVariables = new Hashtable();
+ variablePatterns = new Hashtable>();
+ notProccessed = new VarNodeSet();
+ subTrees = new HashSet();
+ subTreesMap = new Hashtable();
+ }
/**
* @className PSubTree
*
- * @ClassDescription The PSubTree is used to handle the case where antecedent patterns have disjoint variables, by keeping track of multiple PSubTrees for every disjoint variable inside the same PTree.
+ * @ClassDescription The PSubTree is used to handle the case where antecedent
+ * patterns have disjoint variable unions, by keeping track of multiple PSubTrees
+ * for every disjoint variable union inside the same PTree.
*
- * @author Amgad Ashraf
- *
- * @version 3.00 31/5/2018
*/
public class PSubTree {
private PTreeNode root;
- public PSubTree(PTreeNode rot){
- root = rot;
+ public PSubTree(PTreeNode root){
+ this.root = root;
}
public RuleUseInfoSet insert(RuleUseInfo rui) {
FlagNodeSet fns = rui.getFlagNodeSet();
RuleUseInfoSet res = new RuleUseInfoSet();
- for(FlagNode node : fns){
+ for(FlagNode node : fns) {
int pattern = node.getNode().getId();
-
PTreeNode leaf = getLeafPattern(pattern, root);
res = leaf.insertIntoTree(rui, res);
}
+
return res;
}
@@ -331,35 +384,34 @@ public PTreeNode getRoot(){
}
/**
- * @className
- *
- * @ClassDescription The PTreeNode is the lowest level in the PTree, where RUIs are stored and combined.
- *
- * @author Amgad Ashraf
+ * @className PTreeNode
*
- * @version 3.00 31/5/2018
+ * @ClassDescription The PTreeNode is the lowest level in the PTree,
+ * where RUIs are stored and combined.
*/
public class PTreeNode {
private PTreeNode parent, sibling;
private PTreeNode leftChild, rightChild;
- private Hashtable ruisMap;//Substitutions node IDs
+ /**
+ * Maps every set of bindings to a RUISet.
+ */
+ private Hashtable ruisMap;
private Set pats;
private VarNodeSet vars;
private VarNodeSet siblingIntersection;
- public PTreeNode(){
- ruisMap = new Hashtable();
- parent = null; sibling = null;
- leftChild = null; rightChild = null;
- pats = null; vars = null;
+ public PTreeNode() {
+ ruisMap = new Hashtable();
}
- public PTreeNode(Set p, VarNodeSet v){
+
+ public PTreeNode(Set p, VarNodeSet v) {
this();
- pats = p; vars = v;
+ pats = p;
+ vars = v;
}
public RuleUseInfoSet insertIntoTree(RuleUseInfo rui, RuleUseInfoSet ruiSet) {
- Integer[] key = insertRUI(rui);
+ int key = insertRUI(rui);
if (sibling == null) {
ruiSet.add(rui);
return ruiSet;
@@ -373,6 +425,7 @@ public RuleUseInfoSet insertIntoTree(RuleUseInfo rui, RuleUseInfoSet ruiSet) {
continue;
parent.insertIntoTree(combinedRui, ruiSet);
}
+
return ruiSet;
}
@@ -388,58 +441,88 @@ public void insertLeftAndRight(PTreeNode leftNode, PTreeNode rightNode,
rightChild = rightNode;
}
- public Integer[] insertRUI(RuleUseInfo rui) {
+ public int insertRUI(RuleUseInfo rui) {
if (sibling == null) {
- RuleUseInfoSet ruiSet = ruisMap.get(new Integer[]{0});
+ RuleUseInfoSet ruiSet = ruisMap.get(0);
if (ruiSet == null) {
ruiSet = new RuleUseInfoSet();
- ruisMap.put(new Integer[]{0}, ruiSet);
+ ruisMap.put(0, ruiSet);
}
ruiSet.add(rui);
- return new Integer[]{0};
+ return 0;
}
-
- Integer[] vs = new Integer[siblingIntersection.size()];
+
+ // The case when the node is other than the root
+ int[] vs = new int[siblingIntersection.size()];
int index = 0;
- for (VariableNode var : siblingIntersection)
- vs[index++] = rui.getSubstitutions().getBindingByVariable(var).getNode().getId();
+ for (VariableNode var : siblingIntersection) {
+ if(rui.getSubstitutions().getBindingByVariable(var) != null)
+ vs[index++] = rui.getSubstitutions().getBindingByVariable(var).getNode().getId();
+ }
+ int key = getKey(vs);
RuleUseInfoSet ruis = ruisMap.get(vs);
if (ruis == null) {
ruis = new RuleUseInfoSet();
- ruisMap.put(vs, ruis);
+ ruisMap.put(key, ruis);
}
ruis.add(rui);
- return vs;
+ return key;
}
- public RuleUseInfoSet getRUIS(){
+ public RuleUseInfoSet getRUIS() {
RuleUseInfoSet ruiSet = new RuleUseInfoSet();
Collection mappedRuis = ruisMap.values();
for(RuleUseInfoSet singleSet : mappedRuis)
ruiSet.addAll(singleSet);
return ruiSet;
}
+
+ /**
+ * Get the index of a RuleUseInfo in the table by the ids of its
+ * substitutions
+ *
+ * @param x
+ * int[]
+ * @return int
+ */
+ private int getKey(int[] x) {
+ int p = 16777619;
+ int hash = (int) 2166136261L;
+ for (int i = 0; i < x.length; ++i) {
+ hash += (hash ^ x[i]) * p;
+ }
+ hash += hash << 13;
+ hash ^= hash >> 7;
+ hash += hash << 3;
+ hash ^= hash >> 17;
+ hash += hash << 5;
+ return hash;
+ }
+
- public RuleUseInfoSet getRUIS(Integer[] index) {
+ public RuleUseInfoSet getRUIS(int index) {
return ruisMap.get(index);
}
public PTreeNode getLeftChild() {
return leftChild;
}
+
public PTreeNode getRightChild() {
return rightChild;
}
+
public Set getPats() {
return pats;
}
+
public VarNodeSet getVars() {
return vars;
}
+
@Override
public String toString(){
return pats.toString();
}
-
}
}
\ No newline at end of file
diff --git a/src/sneps/snip/classes/RuisHandler.java b/src/sneps/snip/classes/RuisHandler.java
index 8ff3cffa..04ee673d 100644
--- a/src/sneps/snip/classes/RuisHandler.java
+++ b/src/sneps/snip/classes/RuisHandler.java
@@ -1,39 +1,26 @@
package sneps.snip.classes;
-import sneps.network.classes.setClasses.NodeSet;
import sneps.network.classes.setClasses.RuleUseInfoSet;
/**
* @className RuisHandler.java
*
- * @ClassDescription To deal with the large number of RUIs generated as more nodes are built in the network, RuisHandler classes are built to store and combine RUIs.
- * A RuisHandler is stored in a rule Node and a single rule Node can store multiple instances of a single RuisHandler class.
- *
- * @author Amgad Ashraf
- *
- * @version 3.00 31/5/2018
+ * @ClassDescription To deal with the large number of RUIs generated as more nodes are built in the network,
+ * RuisHandler classes are built to store and combine RUIs.
*/
-public abstract class RuisHandler {
- protected String context;
- private NodeSet positiveNodes;
-
- public RuisHandler(){
- positiveNodes = new NodeSet();
- }
- public RuisHandler(String contextID) {
- this();
- this.context = contextID;
- }
-
- public String getContext() {
- return context;
- }
-
- abstract public RuleUseInfoSet insertRUI(RuleUseInfo rui);
- public NodeSet getPositiveNodes() {
- return positiveNodes;
- }
- public void setPositiveNodes(NodeSet positiveNodes) {
- this.positiveNodes = positiveNodes;
- }
+public interface RuisHandler {
+
+ /**
+ * Inserts the given RuleUseInfo into this RuisHandler and returns the
+ * RuleUseInfoSet resulted from combining it with the RuleUseInfos in this
+ * RuisHandler.
+ * @param rui
+ * RuleUseInfo
+ * @return RuleUseInfoSet
+ */
+ public RuleUseInfoSet insertRUI(RuleUseInfo rui);
+
+ public RuleUseInfoSet combineConstantRUI(RuleUseInfo rui);
+
+ public void clear();
}
diff --git a/src/sneps/snip/classes/RuleResponse.java b/src/sneps/snip/classes/RuleResponse.java
new file mode 100644
index 00000000..b5bbcfe2
--- /dev/null
+++ b/src/sneps/snip/classes/RuleResponse.java
@@ -0,0 +1,49 @@
+package sneps.snip.classes;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+
+import sneps.snip.Report;
+import sneps.snip.channels.Channel;
+
+public class RuleResponse {
+
+ private Report report;
+ private Collection consequentChannels;
+
+ public RuleResponse() {
+ consequentChannels = new HashSet();
+ }
+
+ public Report getReport() {
+ return report;
+ }
+
+ public void setReport(Report report) {
+ this.report = report;
+ }
+
+ public Collection getConsequentChannels() {
+ return consequentChannels;
+ }
+
+ public void setConsequentChannels(Set consequentChannels) {
+ this.consequentChannels = consequentChannels;
+ }
+
+ public void addChannel(Channel c) {
+ this.consequentChannels.add(c);
+ }
+
+ public void addAllChannels(Set channels) {
+ for(Channel c : channels) {
+ this.consequentChannels.add(c);
+ }
+ }
+
+ public void clear() {
+ consequentChannels.clear();
+ }
+
+}
diff --git a/src/sneps/snip/classes/RuleUseInfo.java b/src/sneps/snip/classes/RuleUseInfo.java
index 28107b29..79adbb50 100644
--- a/src/sneps/snip/classes/RuleUseInfo.java
+++ b/src/sneps/snip/classes/RuleUseInfo.java
@@ -1,31 +1,35 @@
package sneps.snip.classes;
-import sneps.exceptions.NodeNotFoundInNetworkException;
-import sneps.exceptions.NotAPropositionNodeException;
import sneps.network.classes.setClasses.FlagNodeSet;
-import sneps.network.classes.setClasses.PropositionSet;
+import sneps.snip.InferenceTypes;
import sneps.snip.matching.Substitutions;
/**
- * @className RuleUseInfo.java
+ * @ClassDescription The RuleUseInfo is a data structure used to save instances of
+ * antecedents of rule nodes.
*
- * @ClassDescription The RuleUseInfo is a data structure used to save instances of antecedents of rule nodes.
- *
- * @author Amgad Ashraf
- *
- * @version 3.00 31/5/2018
*/
public class RuleUseInfo {
private Substitutions sub;
private int pos;
private int neg;
private FlagNodeSet fns;
+
+ /**
+ * Type of Report this RUI is produced from.
+ */
+ private InferenceTypes type;
+
+ public RuleUseInfo() {
+
+ }
- public RuleUseInfo(Substitutions s, int p, int n, FlagNodeSet f) {
+ public RuleUseInfo(Substitutions s, int p, int n, FlagNodeSet f, InferenceTypes t) {
sub = s;
pos = p;
neg = n;
fns = f;
+ type = t;
}
/**
@@ -53,10 +57,6 @@ public int getNegCount() {
*/
public FlagNodeSet getNegSubs() {
FlagNodeSet res = new FlagNodeSet();
- // for (int i = 0; i < fns.cardinality(); i++) {
- // if (fns.getFlagNode(i).getFlag() == 2)
- // res.putIn(fns.getFlagNode(i));
- // }
for (FlagNode fn : fns) {
if (fn.getFlag() == 2)
res.insert(fn);
@@ -71,10 +71,6 @@ public FlagNodeSet getNegSubs() {
*/
public FlagNodeSet getPosSubs() {
FlagNodeSet res = new FlagNodeSet();
- // for (int i = 0; i < fns.cardinality(); i++) {
- // if (fns.getFlagNode(i).getFlag() == 1)
- // res.putIn(fns.getFlagNode(i));
- // }
for (FlagNode fn : fns) {
if (fn.getFlag() == 1)
res.insert(fn);
@@ -90,6 +86,19 @@ public FlagNodeSet getPosSubs() {
public FlagNodeSet getFlagNodeSet() {
return fns;
}
+
+ /**
+ * Return the substitutions list
+ *
+ * @return Substitutions
+ */
+ public Substitutions getSubstitutions() {
+ return sub;
+ }
+
+ public InferenceTypes getType() {
+ return type;
+ }
/**
* Check if this and r have no binding conflicts
@@ -99,39 +108,29 @@ public FlagNodeSet getFlagNodeSet() {
* @return true or false
*/
public boolean isVarsCompatible(RuleUseInfo r) {
- return sub.isCompatible(r.sub);
+ return sub.isCompatible(r.getSubstitutions());
}
/**
- * Check if this and r are joint
+ * Check if this flagged node set and r's flagged node set are joint
*
* @param r
* rule use info
* @return true or false
*/
public boolean isJoint(RuleUseInfo r) {
- // for (int i = 0; i < fns.cardinality(); i++) {
- // for (int j = 0; j < r.getFlagNodeSet().cardinality(); j++) {
- // if (fns.getFlagNode(i)
- // .getNode()
- // .getIdentifier()
- // .equals(r.getFlagNodeSet().getFlagNode(j).getNode()
- // .getIdentifier()))
- // return true;
- // }
- // }
for (FlagNode fn1 : fns) {
for (FlagNode fn2 : r.getFlagNodeSet()) {
- System.out.println("---->> " + fn1.getNode() + " " + fn1.getNode());
if (fn1.getNode() == fn2.getNode())
return true;
}
}
+
return false;
}
/**
- * Check if this and r are disjoint
+ * Check if this flagged node set and r's flagged node set are disjoint
*
* @param r
* rule use info
@@ -149,38 +148,25 @@ public boolean isDisjoint(RuleUseInfo r) {
* @return RuleUseInfo
*/
public RuleUseInfo combine(RuleUseInfo rui) {
- //System.out.println(this.isDisjoint(rui) + " " + this.isVarsCompatible(rui));
if (this.isDisjoint(rui) && this.isVarsCompatible(rui)) {
- return new RuleUseInfo(this.getSubstitutions().union(rui.getSubstitutions()), this.pos
- + rui.pos, this.neg + rui.neg, this.fns.union(rui.fns));
+ InferenceTypes resultingType;
+ if(this.getType().equals(InferenceTypes.FORWARD) ||
+ rui.getType().equals(InferenceTypes.FORWARD))
+ resultingType = InferenceTypes.FORWARD;
+ else
+ resultingType = InferenceTypes.BACKWARD;
+
+ return new RuleUseInfo(this.getSubstitutions().union(rui.getSubstitutions()),
+ this.pos + rui.getPosCount(), this.neg + rui.getNegCount(),
+ this.fns.union(rui.getFlagNodeSet()), resultingType);
}
+
return null;
}
-
- public PropositionSet getSupports() {
- if (fns.isNew())
- return new PropositionSet();
- if (fns.cardinality() == 1)
- return fns.iterator().next().getSupports();
-
- PropositionSet res = new PropositionSet();
- for(FlagNode fn : fns){
- try {
- res = res.union(fn.getSupports());
- } catch (NotAPropositionNodeException
- | NodeNotFoundInNetworkException e) {
- }
- }
- return res;
- }
- /**
- * Return the substitutions list
- *
- * @return Substitutions
- */
- public Substitutions getSubstitutions() {
- return sub;
+ public String toString() {
+ return "Sub: " + sub.toString() + " Pos: " + pos + " Neg: " + neg +
+ " Fns: " + fns.toString() + "Type: " + type;
}
-}
+}
\ No newline at end of file
diff --git a/src/sneps/snip/classes/SIndex.java b/src/sneps/snip/classes/SIndex.java
index 1a14805f..5b968ef2 100644
--- a/src/sneps/snip/classes/SIndex.java
+++ b/src/sneps/snip/classes/SIndex.java
@@ -1,111 +1,104 @@
package sneps.snip.classes;
+import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Set;
import sneps.network.VariableNode;
import sneps.network.classes.setClasses.NodeSet;
import sneps.network.classes.setClasses.RuleUseInfoSet;
-import sneps.network.classes.setClasses.VarNodeSet;
-import sneps.snip.classes.PTree;
-import sneps.snip.classes.RuisHandler;
-import sneps.snip.matching.Substitutions;
-public class SIndex extends RuisHandler {
-
-
- private byte ruiType;
- public static final byte RUIS = 0, SINGLETONRUIS = 1, PTREE = 2;
- private VarNodeSet sharedVars;
+public class SIndex implements RuisHandler {
+
+ /**
+ * A Hashtable used to map different substitutions to different RuisHandlers.
+ * ArrayList represents the ids of the bound values of the substitutions
+ * for the shared variables.
+ */
+ public Hashtable, RuisHandler> map;
+ private byte ruiHandlerType;
+ public static final byte RUIS = 0, SINGLETON = 1, PTREE = 2;
+ private Set sharedVars;
private NodeSet nodesWithVars;
/**
- *
* @param context
- * context Name
- * @param SharedVars
- * set
- * @param ruisType
- * byte
+ * Context name.
+ * @param ruiHandlerType
+ * The type of RuisHandler used by a rule to be mapped to in this SIndex.
+ * @param sharedVars
+ * Set of shared variables whose bindings are used to hash on in this SIndex.
+ * @param nodesWithVars
*/
+ public SIndex(byte ruiHandlerType, Set sharedVars,
+ NodeSet nodesWithVars) {
+ map = new Hashtable, RuisHandler>();
+ this.ruiHandlerType = ruiHandlerType;
+ this.sharedVars = sharedVars;
+ this.nodesWithVars = nodesWithVars;
+ }
- public SIndex(String context, VarNodeSet SharedVars, byte ruisType) {
- super(context);
- this.sharedVars=SharedVars;
- this.ruiType=ruisType;
+ public SIndex(byte ruiHandlerType, Set sharedVars) {
+ map = new Hashtable, RuisHandler>();
+ this.ruiHandlerType = ruiHandlerType;
+ this.sharedVars = sharedVars;
}
/**
- * Insert the rule use info in the map based on the substitution.
- * If this rule use info is null from the map, a new one is created based on the type
- * and if not, it will be replaced by combining this rui and the existing one
+ * Inserts the RuleUseInfo in the map based on the bound values for the
+ * substitutions. If the RuisHandler based on the given index is null in the map,
+ * a new one is created according to the ruiHandlerType. If not, the RUI will be
+ * inserted to the corresponding RuisHandler according to the implementation of
+ * its insert method.
*
* @param rui
- * Rule Use Info
- *
- *
- *
+ * RuleUseInfo
*/
-
public RuleUseInfoSet insertRUI(RuleUseInfo rui) {
-
- int[] vars = new int[sharedVars.size()];
- int index = 0;
- for (VariableNode varId : sharedVars) {
- vars[index] = sharedVars.getVarNode(index).getId();
- index++;
+ ArrayList boundValues = new ArrayList();
+ int boundValueID;
+ for(VariableNode var : sharedVars) {
+ if(rui.getSubstitutions().getBindingByVariable(var) != null) {
+ boundValueID = rui.getSubstitutions().getBindingByVariable(var).getNode().getId();
+ boundValues.add(boundValueID);
+ }
}
- int x = getIndex(vars);
-
-
- RuisHandler trui= SIndexHelper.map.get(x);
- if (trui == null) {
- trui = getNewRUIS();
- SIndexHelper.map.put(x, trui);
-
+ if(!boundValues.isEmpty()) {
+ RuisHandler trui = map.get(boundValues);
+ if (trui == null) {
+ trui = getNewRUIType();
+ map.put(boundValues, trui);
+ }
+
+ RuleUseInfoSet res = trui.insertRUI(rui);
+ return res;
}
- RuleUseInfoSet res = trui.insertRUI(rui);
- return res;
-
- }
-
- private int getIndex(int[] x) {
- int p = 16777619;
- int hash = (int) 2166136261L;
- for (int i = 0; i < x.length; ++i) {
- hash += (hash ^ x[i]) * p;
- }
- hash += hash << 13;
- hash ^= hash >> 7;
- hash += hash << 3;
- hash ^= hash >> 17;
- hash += hash << 5;
- return hash;
+ return null;
}
-
/**
- * create a new rule use info based on its type
+ * Creates a new RuisHandler based on the type of SIndex needed.
*
*/
-
- private RuisHandler getNewRUIS() {
+ private RuisHandler getNewRUIType() {
RuisHandler tempRui = null;
- switch (ruiType) {
+ switch (ruiHandlerType) {
+ case SINGLETON:
+ tempRui = new RuleUseInfoSet(true);
+ break;
case PTREE:
tempRui = new PTree();
((PTree) tempRui).buildTree(nodesWithVars);
break;
- case SINGLETONRUIS:
- tempRui = new RuleUseInfoSet(getContext() , true);
- break;
case RUIS:
- tempRui = new RuleUseInfoSet(getContext() , false);
+ tempRui = new RuleUseInfoSet(false);
+ break;
default:
break;
}
+
return tempRui;
}
@@ -116,9 +109,29 @@ private RuisHandler getNewRUIS() {
* @return int
*/
- /*public int getSize() {
+ public int getSize() {
return map.size();
- }*/
+ }
+
+ public byte getRuiHandlerType() {
+ return ruiHandlerType;
+ }
+
+ public void clear() {
+ map.clear();
+ }
+
+ public RuleUseInfoSet combineConstantRUI(RuleUseInfo rui) {
+ RuleUseInfoSet res = new RuleUseInfoSet();
+ Set> keys = map.keySet();
+ for(ArrayList key : keys) {
+ RuisHandler handler = map.get(key);
+ RuleUseInfoSet temp = handler.combineConstantRUI(rui);
+ res.addAll(temp);
+ }
+
+ return res;
+ }
}
\ No newline at end of file
diff --git a/src/sneps/snip/classes/SIndexHelper.java b/src/sneps/snip/classes/SIndexHelper.java
deleted file mode 100644
index 10ba3d5e..00000000
--- a/src/sneps/snip/classes/SIndexHelper.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package sneps.snip.classes;
-
-import java.util.Hashtable;
-
-public class SIndexHelper {
-
- public static Hashtable map = new Hashtable();
-
-
- public static int getSize() {
- return map.size();
- }
-
-}
diff --git a/src/sneps/snip/matching/LinearSubstitutions.java b/src/sneps/snip/matching/LinearSubstitutions.java
index 3f20fee8..2b1a0a0a 100644
--- a/src/sneps/snip/matching/LinearSubstitutions.java
+++ b/src/sneps/snip/matching/LinearSubstitutions.java
@@ -461,6 +461,10 @@ public void update(Binding mb , Node mn)
}
}
}
+
+ public int size() {
+ return sub.size();
+ }
/*public int termID(int variableID) {
diff --git a/src/sneps/snip/matching/Substitutions.java b/src/sneps/snip/matching/Substitutions.java
index f6218186..268f39b5 100644
--- a/src/sneps/snip/matching/Substitutions.java
+++ b/src/sneps/snip/matching/Substitutions.java
@@ -35,6 +35,7 @@ public interface Substitutions {
public void unionIn (Substitutions s);
public void update(Binding mb , Node mn);
public Node value(VariableNode n);
+ public int size();
}
diff --git a/src/sneps/snip/rules/AndEntailment.java b/src/sneps/snip/rules/AndEntailment.java
index eaeb5d3c..b0fa0fbc 100644
--- a/src/sneps/snip/rules/AndEntailment.java
+++ b/src/sneps/snip/rules/AndEntailment.java
@@ -1,26 +1,33 @@
package sneps.snip.rules;
+import java.util.ArrayList;
+import java.util.Set;
+
+import sneps.exceptions.DuplicatePropositionException;
import sneps.exceptions.NodeNotFoundInNetworkException;
import sneps.exceptions.NotAPropositionNodeException;
+
import sneps.network.Node;
import sneps.network.RuleNode;
import sneps.network.VariableNode;
-import sneps.network.classes.Semantic;
import sneps.network.classes.setClasses.FlagNodeSet;
import sneps.network.classes.setClasses.NodeSet;
import sneps.network.classes.setClasses.PropositionSet;
import sneps.network.classes.setClasses.RuleUseInfoSet;
import sneps.network.classes.setClasses.VarNodeSet;
+import sneps.network.classes.term.Closed;
+import sneps.network.classes.term.Molecular;
import sneps.network.classes.term.Open;
-import sneps.network.classes.term.Term;
+import sneps.snip.InferenceTypes;
import sneps.snip.Report;
+import sneps.snip.Runner;
+import sneps.snip.channels.Channel;
import sneps.snip.classes.FlagNode;
import sneps.snip.classes.PTree;
import sneps.snip.classes.RuisHandler;
+import sneps.snip.classes.RuleResponse;
import sneps.snip.classes.RuleUseInfo;
-import sneps.snip.matching.Binding;
-import sneps.snip.matching.LinearSubstitutions;
-import sneps.snip.matching.Substitutions;
+import sneps.snip.classes.SIndex;
/**
* @className AndEntailment.java
@@ -28,188 +35,200 @@
* @ClassDescription The AndEntailment is an inference rule that asserts the conjunction of all the nodes in its antecedent position to imply the conjunction of all the nodes in its consequent position.
* When the rule node receives a request from a node in its consequent position, it sends requests to all its nodes in its antecedent position.
* Generally, when a rule node has enough reports, it creates a reply report and broadcasts it to all consequent nodes.
- * In the case of the AndEntailment rule, the reply report is created and sent when all antecedent nodes sent their respective reports.
+ * In the case of the AndEntailment rule, the reply report is created and sent when all antecedent nodes send their respective reports.
*
- * @author Amgad Ashraf
- * @version 3.00 31/5/2018
*/
public class AndEntailment extends RuleNode {
private static final long serialVersionUID = -8545987005610860977L;
- /**
- * Constructor for the AndEntailment rule node
- * @param syn
- */
- public AndEntailment(Term syn) {
+ public AndEntailment(Molecular syn) {
super(syn);
- }
- /**
- * Constructor for the AndEntailment rule node
- * @param sym
- * @param syn
- */
- public AndEntailment(Semantic sym, Term syn) {
- super(sym, syn);
+ antecedents = getDownAntNodeSet();
+ processNodes(antecedents);
+ consequents = getDownConsqNodeSet();
}
/**
- * Creates the first RuleUseInfo from a given Report and stores it(if positive)
- * Also checks if current number of positive Reports satisfy rule
+ * Creates the first RuleUseInfo from a given Report and stores it (if positive).
+ * Also checks if current number of positive Reports satisfies the rule.
* @param report
* @param signature
*/
@Override
- public void applyRuleHandler(Report report, Node signature) {
- String contxt = report.getContextName();
- if (report.isPositive()) {
- PropositionSet propSet = report.getSupports();
- FlagNodeSet fns = new FlagNodeSet();
- fns.insert(new FlagNode(signature, propSet, 1));
- RuleUseInfo rui = new RuleUseInfo(report.getSubstitutions(),
- 1, 0, fns);
- addNotSentRui(rui, contxt, signature);
+ public ArrayList applyRuleHandler(Report report, Node signature) {
+ if(report.isNegative())
+ return null;
+
+ ArrayList responseList = new ArrayList();
+ ArrayList response = new ArrayList();
+
+ PropositionSet propSet = report.getSupport();
+ FlagNodeSet fns = new FlagNodeSet();
+ fns.insert(new FlagNode(signature, propSet, 1));
+ RuleUseInfo rui = new RuleUseInfo(report.getSubstitutions(), 1, 0, fns,
+ report.getInferenceType());
+
+ if(antNodesWithoutVars.contains(signature)) {
+ addConstantRui(rui);
+ if (constantRUI.getPosCount() != antNodesWithoutVars.size())
+ return null;
+
+ if(ruisHandler == null) {
+ response = applyRuleOnRui(constantRUI);
+ if(response != null)
+ responseList.addAll(response);
+ }
+
+ RuleUseInfoSet ruis = ruisHandler.combineConstantRUI(constantRUI);
+ for (RuleUseInfo tRui : ruis) {
+ response = applyRuleOnRui(tRui);
+ if(response != null)
+ responseList.addAll(response);
+ }
}
- if (contextRuisSet.getByContext(contxt).getPositiveNodes().size() >= getAntSize())
- sendSavedRUIs(report.getContextName());
+ else {
+ if (ruisHandler == null)
+ ruisHandler = addRuiHandler();
+ RuleUseInfoSet res = ruisHandler.insertRUI(rui);
+ if (res == null)
+ res = new RuleUseInfoSet();
+ for (RuleUseInfo tRui : res) {
+ if (tRui.getPosCount() != antNodesWithVars.size())
+ return null;
+
+ if(constantRUI == null) {
+ response = applyRuleOnRui(tRui);
+ if(response != null)
+ responseList.addAll(response);
+ }
+ else {
+ RuleUseInfo combined;
+ combined = tRui.combine(constantRUI);
+ if (combined != null) {
+ response = applyRuleOnRui(combined);
+ if(response != null)
+ responseList.addAll(response);
+ }
+ }
+ }
+ }
+
+ if(responseList.isEmpty())
+ return null;
+
+ return responseList;
}
/**
* Creates a Report from a given RuleUseInfo to be broadcasted to outgoing channels
- * Also checks report supports and modifies accordingly
- * @param Rui
- * @param contextID
*/
@Override
- protected void applyRuleOnRui(RuleUseInfo Rui, String contextID) {
- if (Rui.getPosCount() >= getAntSize()){
- Substitutions sub = Rui.getSubstitutions();
- FlagNodeSet justification = new FlagNodeSet();
- justification.addAll(Rui.getFlagNodeSet());
- PropositionSet supports = new PropositionSet();
-
- for(FlagNode fn : justification){
- try {
- supports = supports.union(fn.getSupports());
- } catch (NotAPropositionNodeException
- | NodeNotFoundInNetworkException e) {}
+ protected ArrayList applyRuleOnRui(RuleUseInfo rui) {
+ if (rui.getPosCount() < getAntSize())
+ return null;
+
+ ArrayList responseList = new ArrayList();
+ RuleResponse response = new RuleResponse();
+ Report reply;
+
+ PropositionSet replySupport = new PropositionSet();
+ PropositionSet ruleSupport = new PropositionSet();
+ for(FlagNode fn : rui.getFlagNodeSet())
+ try {
+ replySupport = replySupport.union(fn.getSupport());
+ } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) {
+ e.printStackTrace();
}
-
+
+ if(this.getTerm() instanceof Closed) {
try {
- supports = supports.union(Rui.getSupports());
- } catch (NotAPropositionNodeException
- | NodeNotFoundInNetworkException e) {}
-
- if(this.getTerm() instanceof Open){
- //knownInstances check this.free vars - > bound
- VarNodeSet freeVars = ((Open)this.getTerm()).getFreeVariables();
- Substitutions ruiSub = Rui.getSubstitutions();
- boolean allBound = true;
-
- for(Report report : knownInstances){
- //Bound to same thing(if bound)
- for(VariableNode var : freeVars){
- if(!report.getSubstitutions().isBound(var)){
- allBound = false;
- break;
- }
+ ruleSupport = ruleSupport.add(this.getId());
+ replySupport = replySupport.union(ruleSupport);
+ } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException |
+ DuplicatePropositionException e) {
+ }
+
+ if(Runner.isNodeAssertedThroughForwardInf(this))
+ reply = new Report(rui.getSubstitutions(), replySupport, true,
+ InferenceTypes.FORWARD);
+ else
+ reply = new Report(rui.getSubstitutions(), replySupport, true,
+ rui.getType());
+
+ reportsToBeSent.add(reply);
+ response.setReport(reply);
+ Set forwardChannels = getOutgoingChannelsForReport(reply);
+ response.addAllChannels(forwardChannels);
+ responseList.add(response);
+ }
+ else if(this.getTerm() instanceof Open) {
+ // knownInstances contain instances found for the rule node itself
+ if(knownInstances.isEmpty())
+ return null;
+ VarNodeSet freeVars = ((Open) this.getTerm()).getFreeVariables();
+ boolean allBound;
+ Report ruiReport = new Report(rui.getSubstitutions(), replySupport,
+ true, rui.getType());
+ for(Report r : knownInstances) {
+ // Only positive reports should be considered
+ if(r.getSign() == false)
+ continue;
+
+ allBound = true;
+ // Check that each free variable in this rule node is bound in the
+ // current report
+ for(VariableNode var : freeVars) {
+ if(!r.getSubstitutions().isBound(var)) {
+ allBound = false;
+ break;
}
- if(allBound){//if yes
- Substitutions instanceSub = report.getSubstitutions();
-
- for(int i = 0; i < ruiSub.cardinality(); i++){
- Binding ruiBind = ruiSub.getBinding(i);//if rui also bound
- Binding instanceBind = instanceSub.
- getBindingByVariable(ruiBind.getVariable());
- if( !((instanceBind != null) &&
- (instanceBind.isEqual(ruiBind))) ){
- allBound = false;
- break;
- }
- }
- if(allBound){
- //combine known with rui
- Substitutions newSub = new LinearSubstitutions();
- newSub.insert(instanceSub);
- newSub.insert(ruiSub);
-
- //add to new support and send
- Report reply = new Report(newSub, supports, true, contextID);
- sendReportToConsequents(reply);
- return;
- }
+ }
+
+ // All free variables of this rule node are bound in the current report
+ if(allBound) {
+ reply = ruiReport.combine(r);
+ if(reply != null) {
+ response.clear();
+ response.setReport(reply);
+ Set forwardChannels = getOutgoingChannelsForReport(reply);
+ response.addAllChannels(forwardChannels);
+ responseList.add(response);
}
}
}
-
- Report reply = new Report(sub, supports, true, contextID);
- sendReportToConsequents(reply);
}
+
+ if(responseList.isEmpty())
+ return null;
+
+ return responseList;
}
-
+
/**
- * Creates an appropriate PTree as a RuisHandler, builds it and inserts it into ContextRuisSet by Context
- * @param context
- * @return
+ * Naming convention used to retrieve Nodes in Down Antecedent position is "&ant";
+ * "&" for AndEntailment, "ant" for Antecedent
+ * @return NodeSet
*/
@Override
- public RuisHandler createRuisHandler(String context) {
- PTree tree = new PTree();
- NodeSet ants = antNodesWithoutVars;
- ants.addAll(antNodesWithVars);
- tree.buildTree(ants);
- this.addContextRUIS(context, tree);
- return tree;
+ public NodeSet getDownAntNodeSet() {
+ return this.getDownNodeSet("&ant");
}
-
- /**
- * Inserts given RuleUseInfo into the appropriate PTree and updates the corresponding PTree
- * @param rui
- * @param contxt
- * @param signature
- */
- public void addNotSentRui(RuleUseInfo rui, String contxt, Node signature){
- PTree tree = (PTree) contextRuisSet.getByContext(contxt);
- if (tree == null)
- tree = (PTree) createRuisHandler(contxt);
- tree.insertRUI(rui);
- if(!tree.getPositiveNodes().contains(signature))
- tree.getPositiveNodes().addNode(signature);
- contextRuisSet.addHandlerSet(contxt, tree);
+
+ @Override
+ public NodeSet getDownConsqNodeSet() {
+ return this.getDownNodeSet("&consq");
}
- /**
- * Prepares the appropriate PTree and all its root RuleUseInfo for broadcasting
- * @param contextID
- */
- private void sendSavedRUIs(String contextID) {
- RuleUseInfo addedConstant = getConstantRUI(contextID);
- if (addedConstant == null && antNodesWithoutVars.size() != 0)
- return;
- if( (addedConstant != null) &&(antNodesWithoutVars.size() != addedConstant.getPosCount()))
- return;
-
- RuleUseInfoSet ruis = ((PTree)contextRuisSet.getByContext(contextID)).getAllRootRuis();
- if (ruis == null) {
- applyRuleOnRui(addedConstant, contextID);
- return;
- }
-
- RuleUseInfo combined;
- for (RuleUseInfo info : ruis) {
- combined = info.combine(addedConstant);
- if (combined != null)
- applyRuleOnRui(combined, contextID);
- }
+ @Override
+ protected RuisHandler createRuisHandler() {
+ PTree tree = new PTree();
+ tree.buildTree(antNodesWithVars);
+ return tree;
}
- /**
- * Naming convention used to retrieve Nodes in Down Antecedent position is "&ant";
- * "&" for AndEntailment, "ant" for Antecedent
- * @return
- */
@Override
- public NodeSet getDownAntNodeSet() {
- return this.getDownNodeSet("&ant");//ants for & name convention
+ protected byte getSIndexType() {
+ return SIndex.PTREE;
}
}
diff --git a/src/sneps/snip/rules/AndOrEntailment.java b/src/sneps/snip/rules/AndOrEntailment.java
index c9ff1fd7..c0e218cc 100644
--- a/src/sneps/snip/rules/AndOrEntailment.java
+++ b/src/sneps/snip/rules/AndOrEntailment.java
@@ -1,255 +1,157 @@
package sneps.snip.rules;
-import java.util.HashSet;
+import java.util.ArrayList;
import java.util.Set;
+import sneps.exceptions.DuplicatePropositionException;
import sneps.exceptions.NodeNotFoundInNetworkException;
import sneps.exceptions.NotAPropositionNodeException;
-import sneps.network.Node;
-import sneps.network.PropositionNode;
import sneps.network.RuleNode;
import sneps.network.VariableNode;
-import sneps.network.classes.Semantic;
-import sneps.network.classes.setClasses.FlagNodeSet;
import sneps.network.classes.setClasses.NodeSet;
import sneps.network.classes.setClasses.PropositionSet;
+import sneps.network.classes.setClasses.RuleUseInfoSet;
import sneps.network.classes.setClasses.VarNodeSet;
+import sneps.network.classes.term.Closed;
+import sneps.network.classes.term.Molecular;
import sneps.network.classes.term.Open;
-import sneps.network.classes.term.Term;
-import sneps.snebr.Context;
-import sneps.snebr.Controller;
-import sneps.snebr.Support;
+import sneps.snip.InferenceTypes;
import sneps.snip.Report;
+import sneps.snip.Runner;
import sneps.snip.channels.Channel;
import sneps.snip.classes.RuleUseInfo;
import sneps.snip.classes.SIndex;
-import sneps.snip.matching.Binding;
-import sneps.snip.matching.LinearSubstitutions;
-import sneps.snip.matching.Substitutions;
import sneps.snip.classes.FlagNode;
import sneps.snip.classes.RuisHandler;
+import sneps.snip.classes.RuleResponse;
public class AndOrEntailment extends RuleNode {
- boolean sign = false;
- private int min, max, args;
- private int received=0;
- private static int pos=0;
- private static int neg=0;
-
- public int getAndOrMin() {
- return min;
- }
-
- public int getAndOrMax() {
- return max;
- }
-
- public int getAndOrArgs() {
- return args;
- }
-
- public void setAndOrMin(int min) {
- this.min = min;
- }
-
- public void setAndOrMax(int max) {
- this.max = max;
- }
-
- public void setAndOrArgs(int args) {
- this.args = args;
- }
-
- /**
- * Constructor for the AndOr Entailment
- * @param syn
- */
-
- public AndOrEntailment(Term syn) {
- super(syn);
- }
-
- /**
- * Constructor for the AndOr Entailment
- * @param sym
- * @param syn
- */
-
- public AndOrEntailment(Semantic sym, Term syn) {
- super(sym, syn);
- }
-
- /**
- * When a report is received, it checks whether it is true or false
- * Then the positive or negative will be updated accordingly
- * When there is enough args received to create a RUI, for the rule to check,
- * A RUI will be created and apply the rule on this RUI
- */
- public void applyRuleHandler(Report report, Node signature) {
- String contextID = report.getContextName();
- RuleUseInfo rui;
- if (report.isPositive()) {
- pos++;
- } else {
- neg++;
- }
-
- int rem = args-(pos+neg);
- if(remrem) {
- PropositionSet propSet = report.getSupports();
- FlagNodeSet fns = new FlagNodeSet();
- fns.insert(new FlagNode(signature, propSet, 1));
- rui = new RuleUseInfo(report.getSubstitutions(),
- pos, neg, fns);
- applyRuleOnRui(rui, contextID);
- }
-
-
-
- if(pos+neg==args) {
- PropositionSet propSet = report.getSupports();
- FlagNodeSet fns = new FlagNodeSet();
- fns.insert(new FlagNode(signature, propSet, 1));
- rui = new RuleUseInfo(report.getSubstitutions(),
- pos, neg, fns);
- applyRuleOnRui(rui, contextID);
- }
- }
+ private static final long serialVersionUID = 1L;
+ private int min;
+ private int max;
- /**
- * Checks the condition for firing the rule.
- * If the conditions are true, the sign is set to true
- * Then a new report is created with the sign that was set.
- * The report is broadcasted to the ants.
- */
- protected void applyRuleOnRui(RuleUseInfo tRui, String contextID) {
-
- if(tRui.getPosCount()>=min&&tRui.getPosCount()<=max) {
- sign=true;
- }else if(tRui.getPosCount()>max||tRui.getPosCount()rem) {
- sign=false;
- }
-
+ public AndOrEntailment(Molecular syn) {
+ super(syn);
+ /*NodeSet minNode = getDownNodeSet("min");
+ min = Integer.parseInt(minNode.getNode(0).getIdentifier());
+ NodeSet maxNode = getDownNodeSet("max");
+ max = Integer.parseInt(maxNode.getNode(0).getIdentifier());*/
+ antecedents = getDownAntNodeSet();
+ processNodes(antecedents);
+ }
+
+ @Override
+ protected ArrayList applyRuleOnRui(RuleUseInfo rui) {
+ boolean reportSign = false;
+ if (rui.getNegCount() == getAntSize() - min)
+ reportSign = true;
+ else if (rui.getPosCount() != max)
+ return null;
- Set nodesSentReports = new HashSet();
- for (FlagNode fn : tRui.getFlagNodeSet()) {
- nodesSentReports.add(fn.getNode().getId());
- }
-
-
-
+ consequents = antecedents.difference(rui.getFlagNodeSet().getAllNodes());
+ ArrayList responseList = new ArrayList();
+ RuleResponse response = new RuleResponse();
+ Report reply;
+ PropositionSet replySupport = new PropositionSet();
+ PropositionSet ruleSupport = new PropositionSet();
+ for(FlagNode fn : rui.getFlagNodeSet())
+ try {
+ replySupport = replySupport.union(fn.getSupport());
+ } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) {
+ }
- Substitutions sub = tRui.getSubstitutions();
- FlagNodeSet justification = new FlagNodeSet();
- justification.addAll(tRui.getFlagNodeSet());
- PropositionSet supports = new PropositionSet();
-
- for(FlagNode fn : justification){
+ if(this.getTerm() instanceof Closed) {
try {
- supports = supports.union(fn.getSupports());
- } catch (NotAPropositionNodeException
- | NodeNotFoundInNetworkException e) {}
+ ruleSupport = ruleSupport.add(this.getId());
+ replySupport = replySupport.union(ruleSupport);
+ } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException |
+ DuplicatePropositionException e) {
+ }
+
+ if(Runner.isNodeAssertedThroughForwardInf(this))
+ reply = new Report(rui.getSubstitutions(), replySupport, reportSign,
+ InferenceTypes.FORWARD);
+ else
+ reply = new Report(rui.getSubstitutions(), replySupport, reportSign,
+ rui.getType());
+
+ reportsToBeSent.add(reply);
+ response.setReport(reply);
+ Set forwardChannels = getOutgoingChannelsForReport(reply);
+ response.addAllChannels(forwardChannels);
+ responseList.add(response);
}
-
- try {
- supports = supports.union(tRui.getSupports());
- } catch (NotAPropositionNodeException
- | NodeNotFoundInNetworkException e) {}
-
- if(this.getTerm() instanceof Open){
- //knownInstances check this.free vars - > bound
- VarNodeSet freeVars = ((Open)this.getTerm()).getFreeVariables();
- Substitutions ruiSub = tRui.getSubstitutions();
- boolean allBound = true;
-
- for(Report report : knownInstances){
- //Bound to same thing(if bound)
- for(VariableNode var : freeVars){
- if(!report.getSubstitutions().isBound(var)){
+ else if(this.getTerm() instanceof Open) {
+ // knownInstances contain instances found for the rule node itself
+ if(knownInstances.isEmpty())
+ return null;
+ VarNodeSet freeVars = ((Open) this.getTerm()).getFreeVariables();
+ boolean allBound;
+ Report ruiReport = new Report(rui.getSubstitutions(), replySupport,
+ reportSign, rui.getType());
+ for(Report r : knownInstances) {
+ // Only positive reports should be considered
+ if(r.getSign() == false)
+ continue;
+
+ allBound = true;
+ // Check that each free variable in this rule node is bound in the
+ // current report
+ for(VariableNode var : freeVars) {
+ if(!r.getSubstitutions().isBound(var)) {
allBound = false;
break;
}
}
- if(allBound){//if yes
- Substitutions instanceSub = report.getSubstitutions();
-
- for(int i = 0; i < ruiSub.cardinality(); i++){
- Binding ruiBind = ruiSub.getBinding(i);//if rui also bound
- Binding instanceBind = instanceSub.
- getBindingByVariable(ruiBind.getVariable());
- if( !((instanceBind != null) &&
- (instanceBind.isEqual(ruiBind))) ){
- allBound = false;
- break;
- }
- }
- if(allBound){
- //combine known with rui
- Substitutions newSub = new LinearSubstitutions();
- newSub.insert(instanceSub);
- newSub.insert(ruiSub);
-
+
+ // All free variables of this rule node are bound in the current report
+ if(allBound) {
+ reply = ruiReport.combine(r);
+ if(reply != null) {
+ response.clear();
+ response.setReport(reply);
+ Set forwardChannels = getOutgoingChannelsForReport(reply);
+ response.addAllChannels(forwardChannels);
+ responseList.add(response);
}
}
}
}
-
- Report forwardReport = new Report(sub, supports, sign, contextID);
-
- for (Channel outChannel : outgoingChannels) {
- if(!nodesSentReports.contains(outChannel.getRequester().getId()))
- outChannel.addReport(forwardReport);
- }
+ if(responseList.isEmpty())
+ return null;
+ return responseList;
}
-
+ @Override
public NodeSet getDownAntNodeSet() {
- return this.getDownNodeSet("Xant");
+ return getDownNodeSet("arg");
}
- /**
- * Create the SIndex within the context
- * @param ContextName
- */
- protected RuisHandler createRuisHandler(String contextName) {
- SIndex index = new SIndex(contextName, getSharedVarsNodes(antNodesWithVars), (byte) 0);
- return this.addContextRUIS(contextName, index);
+ @Override
+ public NodeSet getDownConsqNodeSet() {
+ return null;
}
- /**
- * Getters of positive, negative, sign
- * used in testing
- */
- public static int getPos() {
- return pos;
+ @Override
+ protected RuisHandler createRuisHandler() {
+ return new RuleUseInfoSet(false);
}
- public static int getNeg() {
- return neg;
+ @Override
+ protected byte getSIndexType() {
+ return SIndex.RUIS;
}
-
- public boolean isSign() {
- return sign;
+
+ public void setMin(int min) {
+ this.min = min;
}
-
- /**
- * Clear all the values
- * Used in testing
- */
- public void clrAll() {
- min=0;
- max=0;
- pos=0;
- neg=0;
+
+ public void setMax(int max) {
+ this.max = max;
}
-}
+}
\ No newline at end of file
diff --git a/src/sneps/snip/rules/DoIfNode.java b/src/sneps/snip/rules/DoIfNode.java
index f416b3dd..1f8563e5 100644
--- a/src/sneps/snip/rules/DoIfNode.java
+++ b/src/sneps/snip/rules/DoIfNode.java
@@ -1,38 +1,56 @@
package sneps.snip.rules;
+import java.util.ArrayList;
+import java.util.Set;
+
import sneps.network.RuleNode;
-import sneps.network.classes.Semantic;
import sneps.network.classes.setClasses.NodeSet;
-import sneps.network.classes.term.Term;
+import sneps.network.classes.term.Molecular;
+import sneps.snip.Report;
+import sneps.snip.channels.Channel;
import sneps.snip.classes.RuisHandler;
+import sneps.snip.classes.RuleResponse;
import sneps.snip.classes.RuleUseInfo;
public class DoIfNode extends RuleNode {
private static final long serialVersionUID = -262476672166406490L;
- public DoIfNode(Term syn) {
+ public DoIfNode(Molecular syn) {
super(syn);
}
- public DoIfNode(Semantic sem, Term syn) {
- super(sem, syn);
+ @Override
+ public NodeSet getDownAntNodeSet() {
+ // TODO Auto-generated method stub
+ return null;
}
+ @Override
+ protected byte getSIndexType() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
@Override
- protected void applyRuleOnRui(RuleUseInfo tRui, String contextID) {
+ protected ArrayList applyRuleOnRui(RuleUseInfo tRui) {
// TODO Auto-generated method stub
-
+ return null;
}
@Override
- public NodeSet getDownAntNodeSet() {
+ public NodeSet getDownConsqNodeSet() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ protected RuisHandler createRuisHandler() {
// TODO Auto-generated method stub
return null;
}
@Override
- protected RuisHandler createRuisHandler(String contextName) {
+ protected Set getOutgoingChannelsForReport(Report r) {
// TODO Auto-generated method stub
return null;
}
diff --git a/src/sneps/snip/rules/NumericalEntailment.java b/src/sneps/snip/rules/NumericalEntailment.java
index 71fda669..91ae37bf 100644
--- a/src/sneps/snip/rules/NumericalEntailment.java
+++ b/src/sneps/snip/rules/NumericalEntailment.java
@@ -1,206 +1,239 @@
package sneps.snip.rules;
+import java.util.ArrayList;
+
+import java.util.Set;
+
+import sneps.exceptions.DuplicatePropositionException;
import sneps.exceptions.NodeNotFoundInNetworkException;
import sneps.exceptions.NotAPropositionNodeException;
import sneps.network.Node;
import sneps.network.RuleNode;
import sneps.network.VariableNode;
-import sneps.network.classes.Semantic;
import sneps.network.classes.setClasses.FlagNodeSet;
import sneps.network.classes.setClasses.NodeSet;
import sneps.network.classes.setClasses.PropositionSet;
import sneps.network.classes.setClasses.RuleUseInfoSet;
import sneps.network.classes.setClasses.VarNodeSet;
+import sneps.network.classes.term.Closed;
+import sneps.network.classes.term.Molecular;
import sneps.network.classes.term.Open;
-import sneps.network.classes.term.Term;
+import sneps.snip.InferenceTypes;
import sneps.snip.Report;
+import sneps.snip.Runner;
+import sneps.snip.channels.Channel;
import sneps.snip.classes.FlagNode;
-import sneps.snip.classes.PTree;
import sneps.snip.classes.RuisHandler;
+import sneps.snip.classes.RuleResponse;
import sneps.snip.classes.RuleUseInfo;
import sneps.snip.classes.SIndex;
-import sneps.snip.matching.Binding;
-import sneps.snip.matching.LinearSubstitutions;
-import sneps.snip.matching.Substitutions;
+
/**
* @className NumericalEntailment.java
*
* @ClassDescription The Numerical-Entailment is a rule node that asserts the conjunction of at least i nodes in its antecedent position to imply the conjunction of all the nodes in its consequent position.
* When the rule node receives a request from a node in its consequent position, it sends requests to all its nodes in antecedent positions.
- * Generally, when a rule node has enough reports, it creates a reply report and broadcasts it to all requesting consequent nodes.
- * In the case of the Numerical-Entailment rule, the reply report is created and sent when a minimum of i antecedent nodes sent their respective positive reports.
- *
- * @author Amgad Ashraf
- * @version 3.00 31/5/2018
+ * Generally, when a rule node has enough reports, it creates a reply report and broadcasts it to all consequent nodes.
+ * In the case of the Numerical-Entailment rule, the reply report is created and sent when a minimum of i antecedent nodes send their respective positive reports.
*/
public class NumericalEntailment extends RuleNode {
private static final long serialVersionUID = 3546852401118194013L;
+
private int i;
-
- public NumericalEntailment(Term syn) {
+
+ public NumericalEntailment(Molecular syn) {
super(syn);
- }
- public NumericalEntailment(Semantic sym, Term syn) {
- super(sym, syn);
+ // Initializing i
+ NodeSet max = getDownNodeSet("i");
+ if(max != null)
+ i = Integer.parseInt(max.getNode(0).getIdentifier());
+
+ // Initializing the antecedents
+ antecedents = getDownAntNodeSet();
+ processNodes(antecedents);
+
+ // Initializing the consequents
+ consequents = getDownConsqNodeSet();
}
/**
- * Creates the first RuleUseInfo from a given Report and stores it(if positive)
- * Also checks if current number of positive Reports satisfy rule
+ * Creates the first RuleUseInfo from a given Report and stores it (if positive),
+ * also checks if current number of positive Reports satisfies the rule.
* @param report
* @param signature
*/
@Override
- public void applyRuleHandler(Report report, Node signature) {
- String contxt = report.getContextName();
- if (report.isPositive()) {
- PropositionSet propSet = report.getSupports();
- FlagNodeSet fns = new FlagNodeSet();
- fns.insert(new FlagNode(signature, propSet, 1));
- RuleUseInfo rui = new RuleUseInfo(report.getSubstitutions(),
- 1, 0, fns);
- addNotSentRui(rui, contxt, signature);
+ public ArrayList applyRuleHandler(Report report, Node signature) {
+ if(report.isNegative())
+ return null;
+
+ ArrayList responseList = new ArrayList();
+ ArrayList response = new ArrayList();
+
+ PropositionSet propSet = report.getSupport();
+ FlagNodeSet fns = new FlagNodeSet();
+ fns.insert(new FlagNode(signature, propSet, 1));
+ RuleUseInfo rui = new RuleUseInfo(report.getSubstitutions(), 1, 0, fns,
+ report.getInferenceType());
+
+ if(antNodesWithoutVars.contains(signature)) {
+ addConstantRui(rui);
+ if (ruisHandler == null) {
+ response = applyRuleOnRui(constantRUI);
+ if(response != null)
+ responseList.addAll(response);
+ }
+ else {
+ RuleUseInfoSet combined = ruisHandler.combineConstantRUI(constantRUI);
+ for (RuleUseInfo tRui : combined) {
+ response = applyRuleOnRui(tRui);
+ if(response != null)
+ responseList.addAll(response);
+ }
+ }
+ }
+ else {
+ // Inserting the RuleUseInfo into the RuleNode's RuisHandler:
+ // SIndex in case there are shared variables between all the antecedents, or
+ // RUISet in case there are no shared variables
+ if(ruisHandler == null)
+ ruisHandler = addRuiHandler();
+
+ // The RUI created for the given report is inserted to the RuisHandler
+ RuleUseInfoSet res = ruisHandler.insertRUI(rui);
+
+ if(constantRUI != null) {
+ RuleUseInfo combined;
+ for (RuleUseInfo tRui : res) {
+ combined = tRui.combine(constantRUI);
+ if(combined != null) {
+ response = applyRuleOnRui(combined);
+ if(response != null)
+ responseList.addAll(response);
+ }
+ }
+ }
+ else {
+ for (RuleUseInfo tRui : res) {
+ response = applyRuleOnRui(tRui);
+ if(response != null)
+ responseList.addAll(response);
+ }
+ }
}
- int curPos = contextRuisSet.getByContext(contxt).getPositiveNodes().size();
- int n = antNodesWithoutVars.size()+antNodesWithVars.size();
- if ((curPos >= i) && ((curPos < n-i+1) || (curPos < n-1) ) )
- sendSavedRUIs(report.getContextName());
+
+ if(responseList.isEmpty())
+ return null;
+
+ return responseList;
}
- /**
- * Creates a Report from a given RuleUseInfo to be broadcasted to outgoing channels
- * @param rui
- * @param contextID
- */
- @Override
- protected void applyRuleOnRui(RuleUseInfo Rui, String contextID) {
- if (Rui.getPosCount() >= i){
- Substitutions sub = Rui.getSubstitutions();
- FlagNodeSet justification = new FlagNodeSet();
- justification.addAll(Rui.getFlagNodeSet());
- PropositionSet supports = new PropositionSet();
-
- for(FlagNode fn : justification){
- try {
- supports = supports.union(fn.getSupports());
- } catch (NotAPropositionNodeException
- | NodeNotFoundInNetworkException e) {}
+ protected ArrayList applyRuleOnRui(RuleUseInfo rui) {
+ if(rui.getPosCount() < i)
+ return null;
+
+ ArrayList responseList = new ArrayList();
+ RuleResponse response = new RuleResponse();
+ Report reply;
+
+ PropositionSet replySupport = new PropositionSet();
+ PropositionSet ruleSupport = new PropositionSet();
+ for(FlagNode fn : rui.getFlagNodeSet())
+ try {
+ replySupport = replySupport.union(fn.getSupport());
+ } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) {
+ e.printStackTrace();
}
-
+
+ if(this.getTerm() instanceof Closed) {
try {
- supports = supports.union(Rui.getSupports());
- } catch (NotAPropositionNodeException
- | NodeNotFoundInNetworkException e) {}
-
- if(this.getTerm() instanceof Open){
- //knownInstances check this.free vars - > bound
- VarNodeSet freeVars = ((Open)this.getTerm()).getFreeVariables();
- Substitutions ruiSub = Rui.getSubstitutions();
- boolean allBound = true;
-
- for(Report report : knownInstances){
- //Bound to same thing(if bound)
- for(VariableNode var : freeVars){
- if(!report.getSubstitutions().isBound(var)){
- allBound = false;
- break;
- }
+ ruleSupport = ruleSupport.add(this.getId());
+ replySupport = replySupport.union(ruleSupport);
+ } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException |
+ DuplicatePropositionException e) {
+ }
+
+ if(Runner.isNodeAssertedThroughForwardInf(this))
+ reply = new Report(rui.getSubstitutions(), replySupport, true,
+ InferenceTypes.FORWARD);
+ else
+ reply = new Report(rui.getSubstitutions(), replySupport, true,
+ rui.getType());
+
+ reportsToBeSent.add(reply);
+ response.setReport(reply);
+ Set forwardChannels = getOutgoingChannelsForReport(reply);
+ response.addAllChannels(forwardChannels);
+ responseList.add(response);
+ }
+ else if(this.getTerm() instanceof Open) {
+ // knownInstances contain instances found for the rule node itself
+ if(knownInstances.isEmpty())
+ return null;
+ VarNodeSet freeVars = ((Open) this.getTerm()).getFreeVariables();
+ boolean allBound;
+ Report ruiReport = new Report(rui.getSubstitutions(), replySupport,
+ true, rui.getType());
+ for(Report r : knownInstances) {
+ // Only positive reports should be considered
+ if(r.getSign() == false)
+ continue;
+
+ allBound = true;
+ // Check that each free variable in this rule node is bound in the
+ // current report
+ for(VariableNode var : freeVars) {
+ if(!r.getSubstitutions().isBound(var)) {
+ allBound = false;
+ break;
}
- if(allBound){//if yes
- Substitutions instanceSub = report.getSubstitutions();
-
- for(int i = 0; i < ruiSub.cardinality(); i++){
- Binding ruiBind = ruiSub.getBinding(i);//if rui also bound
- Binding instanceBind = instanceSub.
- getBindingByVariable(ruiBind.getVariable());
- if( !((instanceBind != null) &&
- (instanceBind.isEqual(ruiBind))) ){
- allBound = false;
- break;
- }
- }
- if(allBound){
- //combine known with rui
- Substitutions newSub = new LinearSubstitutions();
- newSub.insert(instanceSub);
- newSub.insert(ruiSub);
-
- //add to new support and send
- Report reply = new Report(newSub, supports, true, contextID);
- sendReportToConsequents(reply);
- return;
- }
+ }
+
+ // All free variables of this rule node are bound in the current report
+ if(allBound) {
+ reply = ruiReport.combine(r);
+ if(reply != null) {
+ response.clear();
+ response.setReport(reply);
+ Set forwardChannels = getOutgoingChannelsForReport(reply);
+ response.addAllChannels(forwardChannels);
+ responseList.add(response);
}
}
}
-
- Report reply = new Report(sub, supports, true, contextID);
- sendReportToConsequents(reply);
}
+
+ if(responseList.isEmpty())
+ return null;
+
+ return responseList;
}
-
+
/**
- * Inserts given RuleUseInfo into the appropriate SIndex and updates the corresponding SIndex
- * @param rui
- * @param contxt
- * @param signature
+ * Naming convention used to retrieve Nodes in Down Antecedent position is "iant"
+ * "i" for NumericalEntailment, "ant" for Antecedent
+ * @return
*/
- public void addNotSentRui(RuleUseInfo rui, String contxt, Node signature){
- SIndex set = (SIndex) contextRuisSet.getByContext(contxt);
- if (set == null)
- set = new SIndex(contxt, getSharedVarsNodes(antNodesWithVars), (byte) 0);
- set.insertRUI(rui);
- if(!set.getPositiveNodes().contains(signature))
- set.getPositiveNodes().addNode(signature);
- contextRuisSet.addHandlerSet(contxt, set);
+ @Override
+ public NodeSet getDownAntNodeSet(){
+ return this.getDownNodeSet("iant");
}
- /**
- * Prepares the appropriate SIndex and all its root RuleUseInfo for broadcasting
- * @param contextID
- */
- private void sendSavedRUIs(String contextID) {
- RuleUseInfo addedConstant = getConstantRUI(contextID);
- if (addedConstant == null && antNodesWithoutVars.size() != 0)
- return;
-
- if (antNodesWithoutVars.size() != addedConstant.getPosCount())
- return;
-
- RuleUseInfoSet ruis = ((PTree)contextRuisSet.getByContext(contextID)).getAllRootRuis();
- if (ruis == null) {
- applyRuleOnRui(addedConstant, contextID);
- return;
- }
-
- RuleUseInfo combined;
- for (RuleUseInfo info : ruis) {
- combined = info.combine(addedConstant);
- if (combined != null)
- applyRuleOnRui(combined, contextID);
- }
+
+ @Override
+ public NodeSet getDownConsqNodeSet() {
+ return this.getDownNodeSet("iconsq");
}
- /**
- * Creates an appropriate SIndex as a RuisHandler and inserts it into ContextRuisSet by Context
- * @param contextName
- * @return
- */
@Override
- public RuisHandler createRuisHandler(String contextName) {
- SIndex index = new SIndex(contextName, getSharedVarsNodes(antNodesWithVars), (byte) 0);
- return this.addContextRUIS(contextName, index);
+ protected RuisHandler createRuisHandler() {
+ return new RuleUseInfoSet(false);
}
- /**
- * Naming convention used to retrieve Nodes in Down Antecedent position is "iant";
- * "i" for NumericalEntailment, "ant" for Antecedent
- * @return
- */
@Override
- public NodeSet getDownAntNodeSet(){
- return this.getDownNodeSet("iant");
+ protected byte getSIndexType() {
+ return SIndex.RUIS;
}
-
+
/**
* Getter for i
* @return
@@ -208,11 +241,13 @@ public NodeSet getDownAntNodeSet(){
public int getI() {
return i;
}
+
/**
* Setter for i
* @param newI
*/
- public void setI(int newI){
+ public void setI(int newI) {
i = newI;
}
+
}
diff --git a/src/sneps/snip/rules/OrEntailment.java b/src/sneps/snip/rules/OrEntailment.java
index aa2a93c8..19a9b9a0 100644
--- a/src/sneps/snip/rules/OrEntailment.java
+++ b/src/sneps/snip/rules/OrEntailment.java
@@ -1,92 +1,133 @@
package sneps.snip.rules;
-import java.util.HashSet;
+import java.util.ArrayList;
import java.util.Set;
+import sneps.exceptions.DuplicatePropositionException;
import sneps.exceptions.NodeNotFoundInNetworkException;
import sneps.exceptions.NotAPropositionNodeException;
import sneps.network.Node;
import sneps.network.RuleNode;
-import sneps.network.classes.Semantic;
-import sneps.network.PropositionNode;
-import sneps.network.classes.setClasses.FlagNodeSet;
+import sneps.network.VariableNode;
import sneps.network.classes.setClasses.NodeSet;
import sneps.network.classes.setClasses.PropositionSet;
-import sneps.network.classes.term.Term;
-import sneps.snebr.Support;
+import sneps.network.classes.setClasses.VarNodeSet;
+import sneps.network.classes.term.Closed;
+import sneps.network.classes.term.Molecular;
+import sneps.network.classes.term.Open;
+import sneps.snip.InferenceTypes;
import sneps.snip.Report;
+import sneps.snip.Runner;
import sneps.snip.channels.Channel;
-import sneps.snip.classes.FlagNode;
import sneps.snip.classes.RuisHandler;
+import sneps.snip.classes.RuleResponse;
import sneps.snip.classes.RuleUseInfo;
public class OrEntailment extends RuleNode {
-
- boolean sign = false;
- private int ant,cq;
+ private static final long serialVersionUID = 1L;
-
- /**
- *Constructor for the Or Entailment
- * @param syn
- */
- public OrEntailment(Term syn) {
+ public OrEntailment(Molecular syn) {
super(syn);
- }
-
-
- /**
- * Constructor for the Or Entailment
- * @param sym
- * @param syn
- */
- public OrEntailment(Semantic sym, Term syn) {
- super(sym, syn);
+ antecedents = getDownAntNodeSet();
+ consequents = getDownConsqNodeSet();
}
- /**
- * Checks if the report received is true
- * If yes, the report is sent to the ants with the true report
- */
- public void applyRuleHandler(Report report, Node node) {
+ public ArrayList applyRuleHandler(Report report, Node signature) {
+ if (report.isNegative())
+ return null;
- if(report.isPositive()) {
-
- sign = true;
-
- PropositionSet propSet = report.getSupports();
- FlagNodeSet fns = new FlagNodeSet();
- fns.insert(new FlagNode(node, propSet, 1));
-
- Report reply = new Report(report.getSubstitutions(), propSet, sign, report.getContextName());
+ ArrayList responseList = new ArrayList();
+ RuleResponse response = new RuleResponse();
+ Report reply;
+
+ PropositionSet replySupport = report.getSupport();
+ PropositionSet ruleSupport = new PropositionSet();
+
+ if(this.getTerm() instanceof Closed) {
+ try {
+ ruleSupport = ruleSupport.add(this.getId());
+ replySupport = replySupport.union(ruleSupport);
+ } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException |
+ DuplicatePropositionException e) {
+ }
- for (Channel outChannel : outgoingChannels)
- outChannel.addReport(reply);
+ if(Runner.isNodeAssertedThroughForwardInf(this))
+ reply = new Report(report.getSubstitutions(), replySupport,
+ true, InferenceTypes.FORWARD);
+ else
+ reply = new Report(report.getSubstitutions(), replySupport,
+ true, report.getInferenceType());
+ reportsToBeSent.add(reply);
+ response.setReport(reply);
+ Set forwardChannels = getOutgoingChannelsForReport(reply);
+ response.addAllChannels(forwardChannels);
+ responseList.add(response);
+ }
+ else if(this.getTerm() instanceof Open) {
+ // knownInstances contain instances found for the rule node itself
+ if(knownInstances.isEmpty())
+ return null;
+ VarNodeSet freeVars = ((Open) this.getTerm()).getFreeVariables();
+ boolean allBound;
+ for(Report r : knownInstances) {
+ // Only positive reports for this rule node should be considered
+ if(r.getSign() == false)
+ continue;
+
+ allBound = true;
+ // Check that each free variable in this rule node is bound in the
+ // current report
+ for(VariableNode var : freeVars) {
+ if(!r.getSubstitutions().isBound(var)) {
+ allBound = false;
+ break;
+ }
+ }
+
+ // All free variables of this rule node are bound in the current report
+ if(allBound) {
+ reply = report.combine(r);
+ if(reply != null) {
+ response.clear();
+ response.setReport(reply);
+ Set forwardChannels = getOutgoingChannelsForReport(reply);
+ response.addAllChannels(forwardChannels);
+ responseList.add(response);
+ }
+ }
+ }
}
-}
-
-
+ if(responseList.isEmpty())
+ return null;
+
+ return responseList;
+ }
+ @Override
+ protected ArrayList applyRuleOnRui(RuleUseInfo tRui) {
+ return null;
+ }
+
@Override
public NodeSet getDownAntNodeSet() {
return this.getDownNodeSet("Vant");
}
-
+
@Override
- protected void applyRuleOnRui(RuleUseInfo tRui, String contextID) {
-
+ public NodeSet getDownConsqNodeSet() {
+ return this.getDownNodeSet("Vconsq");
}
@Override
- protected RuisHandler createRuisHandler(String contextName) {
- // TODO Auto-generated method stub
+ protected RuisHandler createRuisHandler() {
return null;
}
-
- public boolean getReply() {
- return sign;
+
+ @Override
+ protected byte getSIndexType() {
+ return 0;
}
}
diff --git a/src/sneps/snip/rules/ThreshEntailment.java b/src/sneps/snip/rules/ThreshEntailment.java
index e9f6304c..7d86f8c2 100644
--- a/src/sneps/snip/rules/ThreshEntailment.java
+++ b/src/sneps/snip/rules/ThreshEntailment.java
@@ -1,258 +1,160 @@
package sneps.snip.rules;
-import java.util.HashSet;
+import java.util.ArrayList;
import java.util.Set;
+import sneps.exceptions.DuplicatePropositionException;
import sneps.exceptions.NodeNotFoundInNetworkException;
import sneps.exceptions.NotAPropositionNodeException;
-import sneps.network.Node;
-import sneps.network.PropositionNode;
import sneps.network.RuleNode;
import sneps.network.VariableNode;
-import sneps.network.classes.Semantic;
-import sneps.network.PropositionNode;
-import sneps.network.classes.setClasses.FlagNodeSet;
import sneps.network.classes.setClasses.NodeSet;
import sneps.network.classes.setClasses.PropositionSet;
+import sneps.network.classes.setClasses.RuleUseInfoSet;
import sneps.network.classes.setClasses.VarNodeSet;
+import sneps.network.classes.term.Closed;
+import sneps.network.classes.term.Molecular;
import sneps.network.classes.term.Open;
-import sneps.network.classes.term.Term;
-import sneps.snebr.Context;
-import sneps.snebr.Controller;
-import sneps.snebr.Support;
+import sneps.snip.InferenceTypes;
import sneps.snip.Report;
+import sneps.snip.Runner;
import sneps.snip.channels.Channel;
import sneps.snip.classes.RuleUseInfo;
import sneps.snip.classes.SIndex;
-import sneps.snip.matching.Binding;
-import sneps.snip.matching.LinearSubstitutions;
-import sneps.snip.matching.Substitutions;
import sneps.snip.classes.FlagNode;
import sneps.snip.classes.RuisHandler;
+import sneps.snip.classes.RuleResponse;
public class ThreshEntailment extends RuleNode {
-
- private static boolean sign = false;
+ private static final long serialVersionUID = 1L;
- private int min, max, args;
- private int pos=0;
- private int neg=0;
- public int getThreshMin() {
- return min;
- }
-
- public int getThreshMax() {
- return max;
- }
-
- public int getThreshArgs() {
- return args;
- }
+ private int min;
+ private int max;
- public void setThreshMin(int min) {
- this.min = min;
- }
-
- public void setThreshMax(int max) {
- this.max = max;
- }
-
- public void setThreshArgs(int args) {
- this.args = args;
- }
-
-
- /**
- * Constructor for the Thresh Entailment
- * @param syn
- */
- public ThreshEntailment(Term syn) {
+ public ThreshEntailment(Molecular syn) {
super(syn);
+ /*NodeSet minNode = getDownNodeSet("min");
+ min = Integer.parseInt(minNode.getNode(0).getIdentifier());
+ NodeSet maxNode = getDownNodeSet("max");
+ max = Integer.parseInt(maxNode.getNode(0).getIdentifier());*/
+ antecedents = getDownAntNodeSet();
+ processNodes(antecedents);
}
- /**
- * Constructor for the Thresh Entailment
- * @param sym
- * @param syn
- */
- public ThreshEntailment(Semantic sym, Term syn) {
- super(sym, syn);
- }
-
-
- /**
- * When a report is received, it checks whether it is true or false
- * Then the positive or negative will be updated accordingly
- * When there is enough args received to create a RUI, for the rule to check,
- * A RUI will be created and apply the rule on this RUI
- */
-
- public void applyRuleHandler(Report report, Node signature) {
-
- String contextID = report.getContextName();
- RuleUseInfo rui;
+ @Override
+ protected ArrayList applyRuleOnRui(RuleUseInfo rui) {
+ boolean reportSign = false;
+ if (rui.getPosCount() == min
+ && rui.getNegCount() == getAntSize() - max - 1)
+ reportSign = true;
+ else if (rui.getPosCount() != min - 1
+ || rui.getNegCount() != getAntSize() - max)
+ return null;
- if(report.isPositive()) {
- pos++;
- }
- if(report.isNegative()) {
- neg++;
- }
+ consequents = antecedents.difference(rui.getFlagNodeSet().getAllNodes());
+ ArrayList responseList = new ArrayList();
+ RuleResponse response = new RuleResponse();
+ Report reply;
- int rem = args-(pos+neg);
- if(pos>min && posrem) {
-
- PropositionSet propSet = report.getSupports();
- FlagNodeSet fns = new FlagNodeSet();
- fns.insert(new FlagNode(signature, propSet, 1));
- rui = new RuleUseInfo(report.getSubstitutions(),
- pos, neg, fns);
- applyRuleOnRui(rui, contextID);
-
- }
+ PropositionSet replySupport = new PropositionSet();
+ PropositionSet ruleSupport = new PropositionSet();
+ for(FlagNode fn : rui.getFlagNodeSet())
+ try {
+ replySupport = replySupport.union(fn.getSupport());
+ } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) {
+ e.printStackTrace();
+ }
- if(neg+pos==args) {
+ if(this.getTerm() instanceof Closed) {
+ try {
+ ruleSupport = ruleSupport.add(this.getId());
+ replySupport = replySupport.union(ruleSupport);
+ } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException |
+ DuplicatePropositionException e) {
+ }
- PropositionSet propSet = report.getSupports();
- FlagNodeSet fns = new FlagNodeSet();
- fns.insert(new FlagNode(signature, propSet, 1));
- rui = new RuleUseInfo(report.getSubstitutions(),
- pos, neg, fns);
- applyRuleOnRui(rui, contextID);
+ if(Runner.isNodeAssertedThroughForwardInf(this))
+ reply = new Report(rui.getSubstitutions(), replySupport, reportSign,
+ InferenceTypes.FORWARD);
+ else
+ reply = new Report(rui.getSubstitutions(), replySupport, reportSign,
+ rui.getType());
+ reportsToBeSent.add(reply);
+ response.setReport(reply);
+ Set forwardChannels = getOutgoingChannelsForReport(reply);
+ response.addAllChannels(forwardChannels);
+ responseList.add(response);
}
-
- }
-
-
-
-
- /**
- * Checks the condition for firing the rule.
- * If the conditions are true, the sign is set to true
- * Then a new report is created with the sign that was set.
- * The report is broadcasted to the ants.
- */
- protected void applyRuleOnRui(RuleUseInfo tRui, String contextID) {
-
- if (tRui.getPosCount() < min || tRui.getPosCount()>max)
- sign = true;
- else if (tRui.getPosCount()>= min && tRui.getPosCount() <= max)
- sign = false;
-
- int rem = args-(tRui.getPosCount()+tRui.getNegCount());
- if(tRui.getPosCount()>min && tRui.getPosCount()rem) {
- sign=false;
- }
-
- Set nodesSentReports = new HashSet();
- for (FlagNode fn : tRui.getFlagNodeSet()) {
- nodesSentReports.add(fn.getNode().getId());
- }
-
-
- Substitutions sub = tRui.getSubstitutions();
- FlagNodeSet justification = new FlagNodeSet();
- justification.addAll(tRui.getFlagNodeSet());
- PropositionSet supports = new PropositionSet();
-
- for(FlagNode fn : justification){
- try {
- supports = supports.union(fn.getSupports());
- } catch (NotAPropositionNodeException
- | NodeNotFoundInNetworkException e) {}
- }
-
- try {
- supports = supports.union(tRui.getSupports());
- } catch (NotAPropositionNodeException
- | NodeNotFoundInNetworkException e) {}
-
- if(this.getTerm() instanceof Open){
- //knownInstances check this.free vars - > bound
- VarNodeSet freeVars = ((Open)this.getTerm()).getFreeVariables();
- Substitutions ruiSub = tRui.getSubstitutions();
- boolean allBound = true;
-
- for(Report report : knownInstances){
- //Bound to same thing(if bound)
- for(VariableNode var : freeVars){
- if(!report.getSubstitutions().isBound(var)){
+ else if(this.getTerm() instanceof Open) {
+ // knownInstances contain instances found for the rule node itself
+ if(knownInstances.isEmpty())
+ return null;
+ VarNodeSet freeVars = ((Open) this.getTerm()).getFreeVariables();
+ boolean allBound;
+ Report ruiReport = new Report(rui.getSubstitutions(), replySupport,
+ reportSign, rui.getType());
+ for(Report r : knownInstances) {
+ // Only positive reports should be considered
+ if(r.getSign() == false)
+ continue;
+
+ allBound = true;
+ // Check that each free variable in this rule node is bound in the
+ // current report
+ for(VariableNode var : freeVars) {
+ if(!r.getSubstitutions().isBound(var)) {
allBound = false;
break;
}
}
- if(allBound){//if yes
- Substitutions instanceSub = report.getSubstitutions();
-
- for(int i = 0; i < ruiSub.cardinality(); i++){
- Binding ruiBind = ruiSub.getBinding(i);//if rui also bound
- Binding instanceBind = instanceSub.
- getBindingByVariable(ruiBind.getVariable());
- if( !((instanceBind != null) &&
- (instanceBind.isEqual(ruiBind))) ){
- allBound = false;
- break;
- }
- }
- if(allBound){
- //combine known with rui
- Substitutions newSub = new LinearSubstitutions();
- newSub.insert(instanceSub);
- newSub.insert(ruiSub);
-
+
+ // All free variables of this rule node are bound in the current report
+ if(allBound) {
+ reply = ruiReport.combine(r);
+ if(reply != null) {
+ response.clear();
+ response.setReport(reply);
+ Set forwardChannels = getOutgoingChannelsForReport(reply);
+ response.addAllChannels(forwardChannels);
+ responseList.add(response);
}
}
}
}
+ if(responseList.isEmpty())
+ return null;
- Report forwardReport = new Report(sub, supports, sign, contextID);
-
- for (Channel outChannel : outgoingChannels) {
- if(!nodesSentReports.contains(outChannel.getRequester().getId()))
- outChannel.addReport(forwardReport);
- }
-
- }
-
- /**
- * Create the SIndex within the context
- * @param ContextName
- */
- protected RuisHandler createRuisHandler(String contextName) {
- SIndex index = new SIndex(contextName, getSharedVarsNodes(antNodesWithVars), (byte) 0);
- return this.addContextRUIS(contextName, index);
+ return responseList;
}
-
@Override
public NodeSet getDownAntNodeSet() {
- return this.getDownNodeSet("Tant");
+ return getDownNodeSet("arg");
}
-
- public boolean getSign() {
- return sign;
+
+ @Override
+ public NodeSet getDownConsqNodeSet() {
+ return null;
}
-
- public int getPos() {
- return pos;
+ @Override
+ protected RuisHandler createRuisHandler() {
+ return new RuleUseInfoSet(false);
+ }
+
+ @Override
+ protected byte getSIndexType() {
+ return SIndex.RUIS;
}
- public int getNeg() {
- return neg;
+ public void setMin(int min) {
+ this.min = min;
}
- /**
- * Clears all the variables.
- * Used in testing
- */
- public void clrAll() {
- min=0;
- max=0;
- pos=0;
- neg=0;
-
+ public void setMax(int max) {
+ this.max = max;
}
+
}
diff --git a/src/sneps/snip/rules/WhenDoNode.java b/src/sneps/snip/rules/WhenDoNode.java
index b7d94dd9..d20da483 100644
--- a/src/sneps/snip/rules/WhenDoNode.java
+++ b/src/sneps/snip/rules/WhenDoNode.java
@@ -1,38 +1,56 @@
package sneps.snip.rules;
+import java.util.ArrayList;
+import java.util.Set;
+
import sneps.network.RuleNode;
-import sneps.network.classes.Semantic;
import sneps.network.classes.setClasses.NodeSet;
-import sneps.network.classes.term.Term;
+import sneps.network.classes.term.Molecular;
+import sneps.snip.Report;
+import sneps.snip.channels.Channel;
import sneps.snip.classes.RuisHandler;
+import sneps.snip.classes.RuleResponse;
import sneps.snip.classes.RuleUseInfo;
public class WhenDoNode extends RuleNode {
private static final long serialVersionUID = 2515697705889848498L;
-
- public WhenDoNode(Semantic sem, Term syn) {
- super(sem, syn);
- }
- public WhenDoNode(Term syn) {
+ public WhenDoNode(Molecular syn) {
super(syn);
}
-
@Override
- protected void applyRuleOnRui(RuleUseInfo tRui, String contextID) {
+ public NodeSet getDownAntNodeSet() {
// TODO Auto-generated method stub
-
+ return null;
}
@Override
- public NodeSet getDownAntNodeSet() {
+ protected byte getSIndexType() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ protected ArrayList applyRuleOnRui(RuleUseInfo tRui) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public NodeSet getDownConsqNodeSet() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ protected RuisHandler createRuisHandler() {
// TODO Auto-generated method stub
return null;
}
@Override
- protected RuisHandler createRuisHandler(String contextName) {
+ protected Set getOutgoingChannelsForReport(Report r) {
// TODO Auto-generated method stub
return null;
}
diff --git a/tests/AndEntailmentTests.java b/tests/AndEntailmentTests.java
index b0a289ec..5f9eee38 100644
--- a/tests/AndEntailmentTests.java
+++ b/tests/AndEntailmentTests.java
@@ -16,6 +16,7 @@
import sneps.exceptions.NotAPropositionNodeException;
import sneps.network.Network;
import sneps.network.Node;
+import sneps.network.PropositionNode;
import sneps.network.VariableNode;
import sneps.network.cables.DownCable;
import sneps.network.cables.DownCableSet;
@@ -23,6 +24,8 @@
import sneps.network.classes.Relation;
import sneps.network.classes.Semantic;
import sneps.network.classes.Wire;
+import sneps.network.classes.term.Base;
+import sneps.network.classes.term.Closed;
import sneps.network.classes.term.Open;
import sneps.network.classes.term.Variable;
import sneps.network.classes.setClasses.FlagNodeSet;
@@ -30,27 +33,26 @@
import sneps.network.classes.setClasses.PropositionSet;
import sneps.snebr.Context;
import sneps.snebr.Controller;
+import sneps.snip.InferenceTypes;
import sneps.snip.Report;
import sneps.snip.classes.FlagNode;
import sneps.snip.classes.PTree;
-import sneps.snip.classes.RuisHandler;
-import sneps.snip.classes.RuleUseInfo;
import sneps.snip.matching.Binding;
import sneps.snip.matching.LinearSubstitutions;
import sneps.snip.rules.AndEntailment;
-public class AndEntailmentTests extends TestCase{
+public class AndEntailmentTests extends TestCase {
private static Context context;
private static String contextName = "TempContext";
private static AndEntailment and;
- private static Node fido, var, dog, barks;
+ private static Node fido, var1, var2, dog, barks;
+ private static Node man, woman, married, husband, john, mary, steve, sue;
private static Node prop1, prop2, prop3, prop4;
- private static RuleUseInfo rui;
- private static Report report;
+ private static Report report, report1, report2, report3, report4, report5;
@Before
- public void setUp(){
+ public void setUp() {
try {
context = Controller.createContext(contextName);
} catch (DuplicateContextNameException e1) {
@@ -58,13 +60,12 @@ public void setUp(){
}
LinearSubstitutions sub = new LinearSubstitutions();
- FlagNodeSet fns = new FlagNodeSet();
- FlagNode fn;
PropositionSet support = new PropositionSet();
ArrayList wires = new ArrayList();
LinkedList dc = new LinkedList();
LinkedList rels = new LinkedList();
NodeSet nodeSet = new NodeSet();
+ NodeSet nodeSett = new NodeSet();
Relation memberRel = Network.defineRelation("Member", "NodeSet");
Relation classRel = Network.defineRelation("Class", "NodeSet");
Relation doesRel = Network.defineRelation("Does", "NodeSet");
@@ -73,211 +74,226 @@ public void setUp(){
rels.add(memberRel); rels.add(classRel);
CaseFrame caseFrameMC = Network.defineCaseFrame("MemberClass", rels);
rels.clear(); rels.add(classRel); rels.add(doesRel);
- CaseFrame caseFrameCD = Network.defineCaseFrame("ClassDoes", rels);
- rels.clear(); rels.add(memberRel); rels.add(doesRel);
- CaseFrame caseFrameMD = Network.defineCaseFrame("MemberDoes", rels);
rels.clear(); rels.add(antsRel); rels.add(consRel);
CaseFrame caseFrameAC = Network.defineCaseFrame("AntsCons", rels);
- Wire wire1 = null, wire2 = null, wire3 = null, wire4 = null;
+ Wire wire1 = null, wire2 = null, wire3 = null, wire4 = null, wire5 = null;
+ Wire wire6 = null, wire7 = null, wire8 = null, wire9 = null, wire10 = null;
rels.clear();
-//-------------------------------------- fido, dog, barks, X ---------------------------------------------//
+//----------------------- SETTING UP NODES --------------------------------//
try {
- var = Network.buildVariableNode("X");
- fido = Network.buildBaseNode("Fido", new Semantic("Base"));
- dog = Network.buildBaseNode("Dog", new Semantic("Proposition"));//MolecularNode(wires, caseFrame);
- barks = Network.buildBaseNode("Barks", new Semantic("Proposition"));//MolecularNode(wires, caseFrame);
- wire1 = new Wire(memberRel, fido);
- wire2 = new Wire(classRel, dog);
- wire3 = new Wire(doesRel, barks);
- wire4 = new Wire(memberRel, var);
+ var1 = Network.buildVariableNode("X");
+ var2 = Network.buildVariableNode("Y");
+
+ man = Network.buildBaseNode("Man", new Semantic("Class"));
+ woman = Network.buildBaseNode("Woman", new Semantic("Class"));
+ married = Network.buildBaseNode("Married", new Semantic("Class"));
+ husband = Network.buildBaseNode("Husband", new Semantic("Class"));
+ john = Network.buildBaseNode("John", new Semantic("Class"));
+ mary = Network.buildBaseNode("Mary", new Semantic("Class"));
+ steve = Network.buildBaseNode("Steve", new Semantic("Class"));
+ sue = Network.buildBaseNode("Sue", new Semantic("Class"));
+ wire5 = new Wire(memberRel, var1);
+ wire6 = new Wire(memberRel, var2);
+ wire7 = new Wire(classRel, man);
+ wire8 = new Wire(classRel, woman);
+ wire9 = new Wire(classRel, married);
+ wire10 = new Wire(classRel, husband);
} catch (IllegalIdentifierException | NotAPropositionNodeException
| NodeNotFoundInNetworkException e1) {
assertNotNull(e1.getMessage(), e1);
- var = new VariableNode(new Variable("X"));
+ var1 = new VariableNode(new Variable("X"));
+ var2 = new VariableNode(new Variable("Y"));
+ man = new Node(new Base("Man"));
+ woman = new Node(new Base("Woman"));
+ married = new Node(new Base("Married"));
+ husband = new Node(new Base("Husband"));
+ john = new Node(new Base("John"));
+ mary = new Node(new Base("Mary"));
+ steve = new Node(new Base("Steve"));
+ sue = new Node(new Base("Sue"));
}
-//------------------------------------- prop1, prop2, prop3, prop4 ----------------------------------------------//
+//---------------------- PROPOSITION NODES SETUP -------------------------------//
try {
- wires.clear(); wires.add(wire1); wires.add(wire2);
+ wires.clear(); wires.add(wire5); wires.add(wire7);
prop1 = Network.buildMolecularNode(wires, caseFrameMC);
- wires.clear(); wires.add(wire2); wires.add(wire3);
- prop2 = Network.buildMolecularNode(wires, caseFrameCD);
+ wires.clear(); wires.add(wire6); wires.add(wire8);
+ prop2 = Network.buildMolecularNode(wires, caseFrameMC);
- wires.clear(); wires.add(wire4); wires.add(wire2);
+ wires.clear(); wires.add(wire5); wires.add(wire6); wires.add(wire9);
prop3 = Network.buildMolecularNode(wires, caseFrameMC);
-
- wires.clear(); wires.add(wire1); wires.add(wire3);
- prop4 = Network.buildMolecularNode(wires, caseFrameMD);
+
+ wires.clear(); wires.add(wire5); wires.add(wire6); wires.add(wire10);
+ prop4 = Network.buildMolecularNode(wires, caseFrameMC);
} catch (CannotBuildNodeException | EquivalentNodeException
| NotAPropositionNodeException | NodeNotFoundInNetworkException e1) {
assertNotNull(e1.getMessage(), e1);
LinkedList dcList = new LinkedList