From 17cd6753111a81818401a952c2bfeadfb8886a6f Mon Sep 17 00:00:00 2001 From: Youssef Date: Thu, 28 Mar 2019 23:17:44 +0200 Subject: [PATCH 01/22] initial revision for deduce method --- src/sneps/gui/FXController.java | 6 +- src/sneps/network/Network.java | 5 + src/sneps/network/Node.java | 51 +- src/sneps/network/PropositionNode.java | 152 +-- src/sneps/network/RuleNode.java | 67 +- .../classes/setClasses/PropositionSet.java | 11 + src/sneps/snebr/Support.java | 4 + src/sneps/snip/Filter.java | 5 +- src/sneps/snip/Pair.java | 2 +- src/sneps/snip/Report.java | 3 +- src/sneps/snip/Runner.java | 2 +- src/sneps/snip/Switch.java | 12 +- src/sneps/snip/channels/Channel.java | 34 +- src/sneps/snip/channels/MatchChannel.java | 6 +- .../channels/RuleToConsequentChannel.java | 4 +- .../snip/matching/LinearSubstitutions.java | 911 +++++++++--------- src/sneps/snip/matching/Substitutions.java | 83 +- tests/NetworkTestN.java | 52 +- 18 files changed, 736 insertions(+), 674 deletions(-) diff --git a/src/sneps/gui/FXController.java b/src/sneps/gui/FXController.java index 5d48737f..eb6c3728 100644 --- a/src/sneps/gui/FXController.java +++ b/src/sneps/gui/FXController.java @@ -3665,10 +3665,10 @@ public void deduce() { try { n = (PropositionNode) Network.getNode(identifier); } catch (NodeNotFoundInNetworkException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + System.out.println(e); + n = Network.buildTemporaryNode(identifier); } - n.deduce(n); + n.deduce(); ReportSet rs = n.getKnownInstances(); for(Report r : rs) { res = res + r.toString() + "\n"; diff --git a/src/sneps/network/Network.java b/src/sneps/network/Network.java index bc054588..23368a59 100644 --- a/src/sneps/network/Network.java +++ b/src/sneps/network/Network.java @@ -2145,4 +2145,9 @@ public static void clearNetwork() { userDefinedVarSuffix.clear(); } + public static PropositionNode buildTemporaryNode(String identifier) { + // TODO build temporary node for the deduce method + return null; + } + } diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java index 06a7a505..6a6d48b5 100644 --- a/src/sneps/network/Node.java +++ b/src/sneps/network/Node.java @@ -1,6 +1,8 @@ package sneps.network; import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; import sneps.network.cables.UpCable; import sneps.network.cables.UpCableSet; @@ -9,7 +11,10 @@ import sneps.network.classes.term.Term; import sneps.network.classes.setClasses.NodeSet; import sneps.snebr.Context; +import sneps.snip.Pair; +import sneps.snip.Runner; import sneps.snip.channels.Channel; +import sneps.snip.channels.ChannelTypes; import sneps.snip.matching.Substitutions; public class Node implements Serializable { @@ -25,7 +30,7 @@ public Node() { public Node(Term trm) { term = trm; id = count++; - if(this.getTerm() instanceof Molecular) { + if (this.getTerm() instanceof Molecular) { this.updateUpCables(); } } @@ -39,7 +44,7 @@ public Node(Semantic sem, Term trm) { semanticType = sem; term = trm; id = count++; - if(this.getTerm() instanceof Molecular) { + if (this.getTerm() instanceof Molecular) { this.updateUpCables(); } } @@ -127,8 +132,7 @@ public String toString() { * This method overrides the default equals method inherited from the Object * class. * - * @param obj - * an Object that is to be compared to the current node to check + * @param obj an Object that is to be compared to the current node to check * whether they are equal. * * @return true if the given object is an instance of the Node class and has the @@ -144,7 +148,7 @@ public boolean equals(Object obj) { } public void receiveRequest(Channel newChannel) { - // TODO Auto-generated method stub + // TODO Auto-generated method stub - install channel } @@ -207,19 +211,32 @@ Context fake() { return null; } - public void deduce(Node node) { - /* - * Runner.initiate(); NodeSet dominatingRules = getDominatingRules(); - * sendRequests(dominatingRules, channel.getFilter().getSubstitution(), - * channel.getContextID(), ChannelTypes.RuleCons); // - * System.out.println("#$#$#$#$# 1"); try { List matchesReturned = - * Matcher.Match(this); if(matchesReturned != null) { ArrayList matches = - * new ArrayList(); for(Object[] match : matchesReturned) { Pair newPair = - * new Pair((Substitutions)match[1], (Substitutions)match[2], (Node)match[0]); - * matches.add(newPair); } sendRequests(matches, channel.getContextID(), - * ChannelTypes.MATCHED); } } catch (Exception e) { e.printStackTrace(); } - * Runner.run(); // what to return here ? + public void deduce() { + Runner.initiate(); + Node toBeDeduced = this; + /** + * Retrieving all Dominating rules for Node and sending requests to each. */ + NodeSet dominatingRules = getDominatingRules(); + sendRequests(dominatingRules, channel.getFilter().getSubstitution(), channel.getContextID(), + ChannelTypes.RuleCons); + try { + /** + * Retrieving all matching nodes for Node and sending requests to each. + */ + List matchesReturned = Matcher.Match(toBeDeduced); + if (matchesReturned != null) { + ArrayList matches = new ArrayList(); + for (Object[] match : matchesReturned) { + Pair newPair = new Pair((Substitutions) match[1], (Substitutions) match[2], (Node) match[0]); + matches.add(newPair); + } + sendRequests(matches, channel.getContextID(), ChannelTypes.MATCHED); + } + } catch (Exception e) { + e.printStackTrace(); + } + Runner.run(); // what to return here ? } public void setTerm(Term term) { diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 38aeceb6..27d92548 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -2,6 +2,7 @@ import java.io.Serializable; import java.util.ArrayList; +import java.util.HashSet; import sneps.exceptions.CannotInsertJustificationSupportException; import sneps.exceptions.CustomException; @@ -17,7 +18,11 @@ import sneps.network.classes.term.Term; import java.util.Hashtable; +import java.util.List; +import java.util.Set; +import sneps.snebr.Context; +import sneps.snebr.Controller; import sneps.snebr.Support; import sneps.snip.Pair; import sneps.snip.Report; @@ -30,9 +35,9 @@ import sneps.snip.matching.LinearSubstitutions; import sneps.snip.matching.Substitutions; -public class PropositionNode extends Node implements Serializable{ +public class PropositionNode extends Node implements Serializable { private Support basicSupport; - + protected ChannelSet outgoingChannels; protected ChannelSet incomingChannels; protected ReportSet knownInstances; @@ -51,9 +56,8 @@ public PropositionNode(Term trm) { knownInstances = new ReportSet(); setTerm(trm); } - - public void processSingleChannelReports(Channel currentChannel) { + public void processSingleReportsChannel(Channel currentChannel) { ReportSet reports = currentChannel.getReportsBuffer(); for (Report currentReport : reports) { Report alteredReport = new Report(currentReport.getSubstitutions(), currentReport.getSupports(), @@ -70,46 +74,39 @@ public void processSingleChannelReports(Channel currentChannel) { public void processReports() { for (Channel inChannel : incomingChannels) - processSingleChannelReports(inChannel); - } - - public void broadcastReport(Report report) { - for (Channel outChannel : outgoingChannels) { - if (outChannel.addReport(report)) { - // System.out.println("SENDING REPORT " + this); - } - } + processSingleReportsChannel(inChannel); } - public boolean sendReport(Report report, Channel channel) { - if (channel.addReport(report)) { - // System.out.println("SENDING REPORT " + this); - return true; - } - return false; - } - - public void processSingleRequest(Channel currentChannel) { - //TODO check correctness + /*** + * Request handling in Non-Rule proposition nodes. + * + * @param currentChannel + */ + public void processSingleRequestsChannel(Channel currentChannel) { + // TODO check correctness /* PropositionSet propSet = new PropositionSet(); + // TODO addProposition with input a Node propSet.addProposition((PropositionNode) this); - Context desiredContext = SNeBR.getContextByID(currentChannel.getContextID()); + Context desiredContext = Controller.getContextID(currentChannel.getContextID()); + // TODO assertedInContext if (propSet.assertedInContext(desiredContext)) { // TODO change the subs to hashsubs + // #Sends an instance of this report# // System.out.println("#$#$#$#$# -1 " + desiredContext.getId()); Set support = new HashSet(); + // TODO Blank Support constructor with input a Node support.add(new Support((PropositionNode) this)); Report reply = new Report(new LinearSubstitutions(), support, true, currentChannel.getContextID()); - knownInstances.add(reply); + knownInstances.addReport(reply); broadcastReport(reply); } else { + // #Sends any previously known instances# boolean sentAtLeastOne = false; for (Report currentReport : knownInstances) { sentAtLeastOne = sendReport(currentReport, currentChannel); } - // TODO Akram: passed the filter subs to isWhQuest, is that correct - // ? + // TODO Akram: passed the filter subs to isWhQuest, is that correct? // System.out.println("#$#$#$#$# 0"); if (!sentAtLeastOne || isWhQuestion(currentChannel.getFilter().getSubstitution())) { if (!alreadyWorking(currentChannel)) { @@ -120,10 +117,11 @@ public void processSingleRequest(Channel currentChannel) { if (!(currentChannel instanceof MatchChannel)) { try { List matchesReturned = Matcher.Match(this); - if(matchesReturned != null) { + if (matchesReturned != null) { ArrayList matches = new ArrayList(); - for(Object[] match : matchesReturned) { - Pair newPair = new Pair((Substitutions)match[1], (Substitutions)match[2], (Node)match[0]); + for (Object[] match : matchesReturned) { + Pair newPair = new Pair((Substitutions) match[1], (Substitutions) match[2], + (Node) match[0]); matches.add(newPair); } sendRequests(matches, currentChannel.getContextID(), ChannelTypes.MATCHED); @@ -135,12 +133,46 @@ public void processSingleRequest(Channel currentChannel) { } } } -*/ + */ } public void processRequests() { for (Channel outChannel : outgoingChannels) - processSingleRequest(outChannel); + processSingleRequestsChannel(outChannel); + } + + /*** + * Requests received added to the low priority queue to be served accordingly + * through the runner. + */ + public void receiveRequest(Channel channel) { + outgoingChannels.addChannel(channel); + Runner.addToLowQueue(this); + } + + /*** + * Reports received added to the high priority queue to be served accordingly through + * the runner. + */ + public void receiveReports(Channel channel) { + outgoingChannels.addChannel(channel); + Runner.addToHighQueue(this); + } + + public void broadcastReport(Report report) { + for (Channel outChannel : outgoingChannels) { + if (outChannel.addReport(report)) { + // System.out.println("SENDING REPORT " + this); + } + } + } + + public boolean sendReport(Report report, Channel channel) { + if (channel.addReport(report)) { + // System.out.println("SENDING REPORT " + this); + return true; + } + return false; } public void sendRequests(ArrayList list, String conetxtID, ChannelTypes channelType) { @@ -179,74 +211,80 @@ public void sendRequests(NodeSet ns, Substitutions filterSubs, String contextID, } } - public void receiveRequest(Channel channel) { - outgoingChannels.addChannel(channel); - Runner.addToLowQueue(this); - } - - public void receiveReports(Channel channel) { - //TODO - } - public boolean alreadyWorking(Channel channel) { return false; } - - 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() { return knownInstances; } + public void setKnownInstances(ReportSet knownInstances) { this.knownInstances = knownInstances; } + public Hashtable getAssumptionBasedSupport() { return basicSupport.getAssumptionBasedSupport(); - + } - public Hashtable getJustificationSupport() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + + public Hashtable getJustificationSupport() + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { return basicSupport.getJustificationSupport(); } - public void addJustificationBasedSupport(PropositionSet propSet) throws NodeNotFoundInPropSetException, NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException, CannotInsertJustificationSupportException{ + + public void addJustificationBasedSupport(PropositionSet propSet) + throws NodeNotFoundInPropSetException, NotAPropositionNodeException, NodeNotFoundInNetworkException, + DuplicatePropositionException, CannotInsertJustificationSupportException { basicSupport.addJustificationBasedSupport(propSet); } - public void removeNodeFromSupports(PropositionNode propNode) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + + public void removeNodeFromSupports(PropositionNode propNode) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { basicSupport.removeNodeFromSupports(propNode); - + } - public void addParentNode(int id) throws DuplicatePropositionException, NotAPropositionNodeException, NodeNotFoundInNetworkException { - basicSupport.addParentNode(id); - + + public void addParentNode(int id) + throws DuplicatePropositionException, NotAPropositionNodeException, NodeNotFoundInNetworkException { + basicSupport.addParentNode(id); + } - + public ArrayList getParentSupports() { return basicSupport.getParentSupports(); } - - + public boolean HasChildren() { return basicSupport.HasChildren(); } - - public ArrayList>> getMySupportsTree() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + + public ArrayList>> getMySupportsTree() + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { return basicSupport.getMySupportsTree(); } @@ -254,7 +292,7 @@ public boolean reStructureJustifications() throws NotAPropositionNodeException, return basicSupport.reStructureJustifications(); } - public void setHyp(boolean isHyp) throws NotAPropositionNodeException, NodeNotFoundInNetworkException{ + public void setHyp(boolean isHyp) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { basicSupport.setHyp(isHyp); } } \ No newline at end of file diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index f93fb1db..d05faebc 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -26,7 +26,7 @@ import sneps.snip.classes.RuleUseInfo; import sneps.snip.classes.SIndex; -public abstract class RuleNode extends PropositionNode implements Serializable{ +public abstract class RuleNode extends PropositionNode implements Serializable { /** * a NodeSet containing all the pattern antecedents attached to this Node @@ -34,26 +34,25 @@ public abstract class RuleNode extends PropositionNode implements Serializable{ protected NodeSet antNodesWithVars; /** - * a NodeSet containing all the non pattern antecedents attached to this - * Node + * a NodeSet containing all the non pattern antecedents attached to this Node */ protected NodeSet antNodesWithoutVars; /** - * an integer set containing all the ids of the pattern antecedents attached - * to this Node + * an integer set containing all the ids of the pattern antecedents attached to + * this Node */ protected Set antNodesWithVarsIDs; /** - * an integer set containing all the ids of the non pattern antecedents - * attached to this Node + * an integer set containing all the ids of the non pattern antecedents attached + * to this Node */ protected Set antNodesWithoutVarsIDs; /** - * set to true if all the antecedents with Variables share the same - * variables, false otherwise. + * set to true if all the antecedents with Variables share the same variables, + * false otherwise. */ protected boolean shareVars; @@ -61,15 +60,14 @@ public abstract class RuleNode extends PropositionNode implements Serializable{ * Set of ids of the variables shared by all patterns */ protected Set sharedVars; - protected ContextRuisSet contextRuisSet; private Hashtable contextConstantRUI; - - public RuleNode(){} - + public RuleNode() { + } + public RuleNode(Term syn) { super(syn); antNodesWithoutVars = new NodeSet(); @@ -88,8 +86,8 @@ protected void processNodes(NodeSet antNodes) { for (Node n : antNodesWithoutVars) { antNodesWithoutVarsIDs.add(n.getId()); } - //this.antNodesWithoutVars.size(); - //this.antNodesWithVars.size(); + // this.antNodesWithoutVars.size(); + // this.antNodesWithVars.size(); this.shareVars = this.allShareVars(antNodesWithVars); sharedVars = getSharedVarsInts(antNodesWithVars); } @@ -125,7 +123,6 @@ public void applyRuleHandler(Report report, Node signature) { abstract protected void sendRui(RuleUseInfo tRui, String contextID); - public void clear() { contextRuisSet.clear(); contextConstantRUI.clear(); @@ -147,16 +144,14 @@ public boolean allShareVars(NodeSet nodes) { } public Set getSharedVarsNodes(NodeSet nodes) { - /*if (nodes.isEmpty()) - return new HashSet(); - VariableNode n = (VariableNode) nodes.getNode(0); - Set res = ImmutableSet.copyOf(n.getFreeVariables()); - for (int i = 1; i < nodes.size(); i++) { - n = (VariableNode) nodes.getNode(i); - Set temp = ImmutableSet.copyOf(n.getFreeVariables()); - res = Sets.intersection(res, temp); - } - return res;*/ + /* + * if (nodes.isEmpty()) return new HashSet(); VariableNode n = + * (VariableNode) nodes.getNode(0); Set res = + * ImmutableSet.copyOf(n.getFreeVariables()); for (int i = 1; i < nodes.size(); + * i++) { n = (VariableNode) nodes.getNode(i); Set temp = + * ImmutableSet.copyOf(n.getFreeVariables()); res = Sets.intersection(res, + * temp); } return res; + */ return null; } @@ -169,7 +164,7 @@ public Set getSharedVarsInts(NodeSet nodes) { } public NodeSet getDownNodeSet(String name) { - return ((Molecular)term).getDownCableSet().getDownCable(name).getNodeSet(); + return ((Molecular) term).getDownCableSet().getDownCable(name).getNodeSet(); } public abstract NodeSet getDownAntNodeSet(); @@ -227,7 +222,6 @@ public void splitToNodesWithVarsAndWithout(NodeSet allNodes, NodeSet withVars, N } } - public RuleUseInfo addConstantRuiToContext(int context, RuleUseInfo rui) { RuleUseInfo tRui = contextConstantRUI.get(context); if (tRui != null) @@ -249,7 +243,7 @@ public RuleUseInfo getConstantRui(Context con) { public RuleUseInfo getConstantRUI(int context) { return contextConstantRUI.get(context); } - + public static boolean isConstantNode(Node n) { return !(n instanceof VariableNode) || n instanceof RuleNode || ((VariableNode) n).getFreeVariables().isEmpty(); } @@ -258,9 +252,10 @@ public static boolean isConstantNode(Node n) { public void processRequests() { for (Channel currentChannel : outgoingChannels) { if (currentChannel instanceof RuleToConsequentChannel) { - VariableSet variablesList = ((Open)this.term).getFreeVariables(); + VariableSet variablesList = ((Open) this.term).getFreeVariables(); if (variablesList.isEmpty()) { - //Proposition semanticType = (Proposition) this.getSemantic();TODO change according to snebr + // Proposition semanticType = (Proposition) this.getSemantic();TODO change + // according to snebr if (this.semanticType.isAsserted(Controller.getContextByName(currentChannel.getContextName()))) { NodeSet antecedentNodeSet = this.getDownAntNodeSet(); NodeSet toBeSentTo = new NodeSet(); @@ -277,18 +272,14 @@ public void processRequests() { sendRequests(toBeSentTo, currentChannel.getFilter().getSubstitution(), currentChannel.getContextName(), ChannelTypes.RuleAnt); } - } else if (true) - - { + } else if (true) { // TODO Akram: there are free variables but each is bound - } else if (true) - - { + } else if (true) { // TODO Akram: there are free variable } } else { - super.processSingleRequest(currentChannel); + super.processSingleRequestsChannel(currentChannel); } } } diff --git a/src/sneps/network/classes/setClasses/PropositionSet.java b/src/sneps/network/classes/setClasses/PropositionSet.java index f9d9ac02..c959dbcd 100644 --- a/src/sneps/network/classes/setClasses/PropositionSet.java +++ b/src/sneps/network/classes/setClasses/PropositionSet.java @@ -7,6 +7,7 @@ import sneps.exceptions.NotAPropositionNodeException; import sneps.network.Network; import sneps.network.PropositionNode; +import sneps.snebr.Context; import java.io.Serializable; import java.util.Arrays; @@ -292,5 +293,15 @@ public PropositionSet add(int prop) throws DuplicatePropositionException, NotAPr } + public void addProposition(PropositionNode propositionNode) { + // TODO Auto-generated method stub + + } + + public boolean assertedInContext(Context desiredContext) { + // TODO Auto-generated method stub + return false; + } + } \ No newline at end of file diff --git a/src/sneps/snebr/Support.java b/src/sneps/snebr/Support.java index 9a63c382..6cbe5e18 100644 --- a/src/sneps/snebr/Support.java +++ b/src/sneps/snebr/Support.java @@ -52,6 +52,10 @@ public Support(int id) throws NotAPropositionNodeException, NodeNotFoundInNetwor hasChildren = false; } + public Support(PropositionNode propositionNode) { + // TODO Auto-generated constructor stub + } + /** * toString method. retrieving the assumptions and justification supports in a string. */ diff --git a/src/sneps/snip/Filter.java b/src/sneps/snip/Filter.java index 30cfb21e..02c2e9bf 100644 --- a/src/sneps/snip/Filter.java +++ b/src/sneps/snip/Filter.java @@ -22,7 +22,7 @@ public Substitutions getSubstitution() { @Override public boolean equals(Object filter) { Filter typeCastedObject = (Filter) filter; - if(typeCastedObject == null) + if (typeCastedObject == null) return false; return this.substitution.isEqual(typeCastedObject.getSubstitution()); } @@ -30,7 +30,8 @@ public boolean equals(Object filter) { public boolean canPass(Report report) { for (int i = 0; i < this.substitution.cardinality(); i++) { Binding currentFilterBinding = substitution.getBinding(i); - Binding currentReportBinding = report.getSubstitutions().getBindingByVariable(currentFilterBinding.getVariable()); + Binding currentReportBinding = report.getSubstitutions() + .getBindingByVariable(currentFilterBinding.getVariable()); System.out.println("Bindings " + currentFilterBinding + " " + report.getSubstitutions()); if (currentReportBinding != null && currentFilterBinding.getNode() != currentReportBinding.getNode()) return false; diff --git a/src/sneps/snip/Pair.java b/src/sneps/snip/Pair.java index f5885618..700da05c 100644 --- a/src/sneps/snip/Pair.java +++ b/src/sneps/snip/Pair.java @@ -3,7 +3,6 @@ import sneps.network.Node; import sneps.snip.matching.Substitutions; - public class Pair { Node node; Substitutions filterSubs, switchSubs; @@ -17,6 +16,7 @@ public Pair(Substitutions filterSubs, Substitutions switchSubs, Node node) { public Node getNode() { return node; } + public Substitutions getFilter() { return filterSubs; } diff --git a/src/sneps/snip/Report.java b/src/sneps/snip/Report.java index f116aba7..41124609 100644 --- a/src/sneps/snip/Report.java +++ b/src/sneps/snip/Report.java @@ -46,7 +46,8 @@ public boolean isNegative() { } public String toString() { - return "ContextID : " + contextName + "\nSign: " + sign + "\nSubstitution: " + substitution + "\nSupport: " + supports; + return "ContextID : " + contextName + "\nSign: " + sign + "\nSubstitution: " + substitution + "\nSupport: " + + supports; } public String getContextName() { diff --git a/src/sneps/snip/Runner.java b/src/sneps/snip/Runner.java index a5d97de5..6bc1a199 100644 --- a/src/sneps/snip/Runner.java +++ b/src/sneps/snip/Runner.java @@ -61,7 +61,7 @@ public static void addToHighQueue(Node node) { public static void addToLowQueue(Node node) { lowQueue.add(node); } - + public static void addToActStack(ActNode node) { actQueue.addLast(node); } diff --git a/src/sneps/snip/Switch.java b/src/sneps/snip/Switch.java index 175f4c8f..368bbe16 100644 --- a/src/sneps/snip/Switch.java +++ b/src/sneps/snip/Switch.java @@ -1,6 +1,5 @@ package sneps.snip; - import sneps.network.VariableNode; import sneps.snip.matching.Binding; import sneps.snip.matching.LinearSubstitutions; @@ -19,26 +18,23 @@ public Switch(Substitutions substitution) { public void switchReport(Report r) { for (int i = 0; i < this.substitution.cardinality(); i++) { - - Binding b = r.getSubstitutions().getBindingByVariable( - this.substitution.getBinding(i).getVariable()); + Binding b = r.getSubstitutions().getBindingByVariable(this.substitution.getBinding(i).getVariable()); System.out.println(this.substitution.getBinding(i).getVariable()); System.out.println("i: " + i + " binding: " + b); if (b != null) { - b.setVariable( (VariableNode) this.substitution.getBinding(i).getNode()); - }else { + b.setVariable((VariableNode) this.substitution.getBinding(i).getNode()); + } else { System.out.println("there u go " + this.substitution.getBinding(i)); r.getSubstitutions().putIn(this.substitution.getBinding(i)); System.out.println("size now " + r.getSubstitutions().cardinality()); } - } System.out.println(r.getSubstitutions().isNew()); System.out.println("Done Switching:\n" + r.getSubstitutions()); // {a/X, b/Y}, {X/W, Y/Z, K/C} => {a/W, b/Z, K/C} // r.getSubstitutions().unionIn(s); } - + public String toString() { return substitution.toString(); } diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index d7259600..0292bb3b 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -11,7 +11,7 @@ public abstract class Channel { private Filter filter; - private Switch switch_; + private Switch switcher; private String contextName; private Node requester; private Node reporter; @@ -20,16 +20,14 @@ public abstract class Channel { public Channel() { filter = new Filter(); - switch_ = new Switch(); + switcher = new Switch(); reportsBuffer = new ReportSet(); } - public Channel(Substitutions switchSubstitution, - Substitutions filterSubstitutions, - String contextID, Node requester, - Node reporter, boolean v) { + public Channel(Substitutions switcherSubstitution, Substitutions filterSubstitutions, String contextID, + Node requester, Node reporter, boolean v) { this.filter = new Filter(filterSubstitutions); - this.switch_ = new Switch(switchSubstitution); + this.switcher = new Switch(switcherSubstitution); this.contextName = contextID; this.requester = requester; this.reporter = reporter; @@ -38,13 +36,12 @@ public Channel(Substitutions switchSubstitution, reportsBuffer = new ReportSet(); } - - public boolean addReport(Report report) { - System.out.println("Can pass " + filter.canPass(report)); - if (filter.canPass(report) && contextName == report.getContextName()) { - System.out.println("\n\nThe Switch data:\n" + switch_); - switch_.switchReport(report); + boolean passTest = filter.canPass(report); + System.out.println("Can pass " + passTest); + if (passTest && contextName.equals(report.getContextName())) { + System.out.println("\n\nThe switcher data:\n" + switcher); + switcher.switchReport(report); reportsBuffer.addReport(report); Runner.addToHighQueue(requester); return true; @@ -52,31 +49,38 @@ public boolean addReport(Report report) { return false; } - public String getContextName() { return contextName; } + public boolean isValveOpen() { return valve; } + public Filter getFilter() { return filter; } + public Switch getSwitch() { - return switch_; + return switcher; } + public Node getRequester() { return requester; } + public Node getReporter() { return reporter; } + public ReportSet getReportsBuffer() { return reportsBuffer; } + public void setValve(boolean valve) { this.valve = valve; } + public void clearReportsBuffer() { reportsBuffer.clear(); } diff --git a/src/sneps/snip/channels/MatchChannel.java b/src/sneps/snip/channels/MatchChannel.java index d30d71e3..3a4658d4 100644 --- a/src/sneps/snip/channels/MatchChannel.java +++ b/src/sneps/snip/channels/MatchChannel.java @@ -4,11 +4,13 @@ import sneps.snip.matching.Substitutions; public class MatchChannel extends Channel { - + public MatchChannel() { super(); } - public MatchChannel(Substitutions switchSubstitution, Substitutions filterSubstitutions, String contextID, Node requester, Node reporter, boolean v) { + + public MatchChannel(Substitutions switchSubstitution, Substitutions filterSubstitutions, String contextID, + Node requester, Node reporter, boolean v) { super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v); } diff --git a/src/sneps/snip/channels/RuleToConsequentChannel.java b/src/sneps/snip/channels/RuleToConsequentChannel.java index 27286ce8..f3bf0fed 100644 --- a/src/sneps/snip/channels/RuleToConsequentChannel.java +++ b/src/sneps/snip/channels/RuleToConsequentChannel.java @@ -5,8 +5,8 @@ public class RuleToConsequentChannel extends Channel { - public RuleToConsequentChannel(Substitutions switchSubstitution, Substitutions filterSubstitutions, String contextID, - Node requester, Node reporter, boolean v) { + public RuleToConsequentChannel(Substitutions switchSubstitution, Substitutions filterSubstitutions, + String contextID, Node requester, Node reporter, boolean v) { super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v); } diff --git a/src/sneps/snip/matching/LinearSubstitutions.java b/src/sneps/snip/matching/LinearSubstitutions.java index 6c625a90..bd44c912 100644 --- a/src/sneps/snip/matching/LinearSubstitutions.java +++ b/src/sneps/snip/matching/LinearSubstitutions.java @@ -7,481 +7,446 @@ public class LinearSubstitutions implements Substitutions { private Vector sub; - /** - *Creates new empty substitutions list - */ - - public LinearSubstitutions() - { - sub=new Vector(); - } - - /** - *Check if the substitutions list new or not (empty) - *@return true if new false otherwise - */ - public boolean isNew() - { - return sub.isEmpty(); - } - - /** - *Insert a new binding in the list of substitutions - *@param mb Binding - */ - public void putIn(Binding mb) - { - sub.add(mb); - } - - /** - * Check if mb is compatible with this substitutions list - * @param mb Binding - * @return true or false - */ - public boolean isCompatible(Binding mb) - { - LinearSubstitutions test =new LinearSubstitutions(); - test.sub.add(mb); - return this.isCompatible(test); - } - - /** - *Update the value of a binding with the new node - *@param mb the binding - *@param mn the new node - */ - public void update(Binding mb , Node mn) - { - for(int i=0;i(); - } - - /** - * Insert s in this substitutions list - * @param s - */ - public void insert(Substitutions s) - { LinearSubstitutions sl=(LinearSubstitutions) s; - for(int i=0;i(); + } + + /** + * Check if the substitutions list new or not (empty) + * + * @return true if new false otherwise + */ + public boolean isNew() { + return sub.isEmpty(); + } + + /** + * Insert a new binding in the list of substitutions + * + * @param mb Binding + */ + public void putIn(Binding mb) { + sub.add(mb); + } + + /** + * Check if mb is compatible with this substitutions list + * + * @param mb Binding + * @return true or false + */ + public boolean isCompatible(Binding mb) { + LinearSubstitutions test = new LinearSubstitutions(); + test.sub.add(mb); + return this.isCompatible(test); + } + + /** + * Update the value of a binding with the new node + * + * @param mb the binding + * @param mn the new node + */ + public void update(Binding mb, Node mn) { + for (int i = 0; i < sub.size(); i++) { + if (mb.isEqual(sub.get(i))) { + sub.get(i).setNode(mn); + } + } + } + + /** + * Check if the variable node is bound in this substitution list or not. + * + * @param mv the variable node + * @return true if the mv is bound false otherwise + */ + public boolean isBound(VariableNode mv) { + for (int i = 0; i < sub.size(); i++) { + if (sub.get(i).getVariable() == mv) { + return true; + } + } + return false; + } + + /** + * Check if the node is a value in this substitution list or not. + * + * @param mn the node + * @return true if the mn is a value false otherwise + */ + public boolean isValue(Node mn) { + for (int i = 0; i < sub.size(); i++) { + if (sub.get(i).getNode() == mn) { + return true; + } + } + return false; + } + + /** + * Returns the variable node of the node in the substitutions list if node is + * not in the substitutions list return null + * + * @param mn is the node + * @return VariableNode or null + */ + public VariableNode srcNode(Node mn) { + for (int i = 0; i < sub.size(); i++) { + if (sub.get(i).getNode() == mn) { + return sub.get(i).getVariable(); + } + } + return null; + } + + /** + * Returns the binding witch have mv as its variable node or null if mv is not + * in the substitutions list + * + * @param mv mvar + * @return Binding or null + */ + public Binding getBindingByVariable(VariableNode mv) { + for (int i = 0; i < sub.size(); i++) { + if (sub.get(i).getVariable() == mv) { + return sub.get(i); + } + } + return null; + } + + /** + * Returns the binding witch have mn as its node or null if mn is not in the + * substitutions list + * + * @param mn node + * @return binding or null + */ + public Binding getBindingByNode(Node mn) { + for (int i = 0; i < sub.size(); i++) { + if (sub.get(i).getNode() == mn) { + return sub.get(i); + } + } + return null; + } + + /** + * Check if the binding mb is in the substitutions list or not + * + * @param mb the binding + * @return true if mb exists in substitutions list false otherwise + */ + public boolean isMember(Binding mb) { + for (int i = 0; i < sub.size(); i++) { + if (mb.isEqual(sub.get(i))) { + return true; + } + } + return false; + } + + /** + * Check if substitutions list s is a subset of this substitutions list + * + * @param s substitutions list + * @return true if s is a subset of this false otherwise + */ + public boolean isSubSet(Substitutions s) { + LinearSubstitutions sl = (LinearSubstitutions) s; + if (this.sub.size() < sl.sub.size()) + return false; + for (int i = 0; i < sl.sub.size(); i++) { + boolean found = false; + for (int j = 0; j < this.sub.size() && !found; j++) { + if (sl.sub.get(i).isEqual(this.sub.get(j))) + found = true; + } + if (!found) + return false; + } + return true; + } + + /** + * Check if substitutions list s is a equal to this substitutions list + * + * @param s substitutions list + * @return true if s is a equal to this false otherwise + */ + public boolean isEqual(Substitutions s) { + LinearSubstitutions sl = (LinearSubstitutions) s; + if (this.sub.size() == sl.sub.size()) { + for (int i = 0; i < sl.sub.size(); i++) { + boolean found = false; + for (int j = 0; j < this.sub.size() && !found; j++) { + if (sl.sub.get(i).isEqual(this.sub.get(j))) + found = true; + } + if (!found) + return false; + } + return true; + } + return false; + } + + /** + * Union the substitution list s with this substitution list in a new + * substitutions list + * + * @param s substitutions list + * @return substitutions + */ + public Substitutions union(Substitutions s) { + LinearSubstitutions res = new LinearSubstitutions(); + LinearSubstitutions sl = (LinearSubstitutions) s; + for (int i = 0; i < this.sub.size(); i++) { + if (!res.isMember(this.sub.get(i))) { + res.putIn(this.sub.get(i)); + } + } + for (int i = 0; i < sl.sub.size(); i++) { + if (!res.isMember(sl.sub.get(i))) { + res.putIn(sl.sub.get(i)); + } + } + return res; + } + + /** + * Union the substitution list s with this substitution list in this + * + * @param s substitutions list + */ + public void unionIn(Substitutions s) { + LinearSubstitutions sl = (LinearSubstitutions) s; + for (int i = 0; i < sl.sub.size(); i++) { + if (!this.isMember(sl.sub.get(i))) { + this.putIn(sl.sub.get(i).clone()); + } + } + } + + /** + * returns a substitutions list consisting of only those bindings whose variable + * node are in ns + * + * @param ns array of variable node nodes + * @return substitutions list + */ + public Substitutions restrict(VariableNode[] ns) { + LinearSubstitutions s = new LinearSubstitutions(); + for (int i = 0; i < ns.length; i++) { + Binding x = getBindingByVariable(ns[i]); + if (x != null) + s.putIn(x); } + return s; + } + + /** + * If mv is an variable node which is bound, then returns the node to which mv + * is bound otherwise it returns null + * + * @param mv variable node + * @return node or null + */ + public Node term(VariableNode mv) { + for (int i = 0; i < sub.size(); i++) { + if (sub.get(i).getVariable() == mv) { + return sub.get(i).getNode(); + } + } + return null; + } + + /** + * Returns the number of bindings in the substitution list + * + * @return number of bindings + */ + public int cardinality() { + return sub.size(); + } + + /** + * Returns the first Binding in the substitutions list + * + * @return Binding + */ + public Binding choose() { + return sub.get(0); + } - @Override - public void insertOrUpdate(Binding mb) { - if(isBound(mb.getVariable())) - update(getBindingByVariable(mb.getVariable()), mb.getNode()); - else putIn(mb); - + /** + * Return a substitutions list with all the bindings in the substitutions list + * except the first binding + * + * @return Substitutions + */ + public Substitutions others() { + LinearSubstitutions s1 = new LinearSubstitutions(); + for (int i = 1; i < this.sub.size(); i++) { + s1.sub.add(this.sub.get(i)); } + return s1; + } + + /** + * If the node n is bound to another node return the one bounding it otherwise + * return the node it self + * + * @param n node + * @return node + */ + public Node value(VariableNode n) { + Binding b = getBindingByVariable(n); + if (b == null) + return n; + return b.getNode(); + } + + /** + * Returns a new substitutions list with the binding of this added to them the + * Binding m + * + * @param m Binding + * @return Substitutions + */ + public Substitutions insert(Binding m) { + LinearSubstitutions s1 = new LinearSubstitutions(); + s1.putIn(m); + for (int i = 0; i < this.sub.size(); i++) { + s1.sub.add(this.sub.get(i)); + } + return s1; + } + + /** + * Check if the substitutions list s is compatible to this or not two lists are + * compatible if ever variable node in both are bound to the same node and ever + * node in both are bound to the same variable node + * + * @param s substitutions list + * @return true or false + */ + public boolean isCompatible(Substitutions s) { + LinearSubstitutions sl = (LinearSubstitutions) s; + for (int i = 0; i < this.sub.size(); i++) { + for (int j = 0; j < sl.sub.size(); j++) { + if (sl.sub.get(j).getVariable() == this.sub.get(i).getVariable()) { + if (sl.sub.get(j).getNode() != this.sub.get(i).getNode()) + return false; + } else if (sl.sub.get(j).getNode() == this.sub.get(i).getNode()) + if (sl.sub.get(j).getVariable() != this.sub.get(i).getVariable()) + return false; + } + } + return true; + } + + /** + * Return the Binding number x in the substitutions list + * + * @param x binding number + * @return Binding + */ + public Binding getBinding(int x) { + return sub.get(x); + } + + /** + * Split the substitutions list into two parts. The first one is that bindings + * with a base node as its node, and the second one is the rest of the + * substitutions list + * + * @return + */ + public Substitutions[] split() { + LinearSubstitutions[] res = new LinearSubstitutions[2]; + res[0] = new LinearSubstitutions(); + res[1] = new LinearSubstitutions(); + for (int i = 0; i < sub.size(); i++) { + Binding x = sub.get(i); + Node n = x.getNode(); + String name = n.getClass().getName(); + if (sub(name, "sneps.BaseNode")) + res[0].putIn(x); + else + res[1].putIn(x); + } + return res; + } + + /** + * Clear all Bindings from the substitutions list + */ + public void clear() { + sub = new Vector(); + } + + /** + * Insert s in this substitutions list + * + * @param s + */ + public void insert(Substitutions s) { + LinearSubstitutions sl = (LinearSubstitutions) s; + for (int i = 0; i < sl.cardinality(); i++) { + Binding b = sl.sub.get(i); + if (!isMember(b)) + putIn(b); + } + } + + /** + * String checking. + * + * @param x String + * @param y String + * @return true or false + */ + public boolean sub(String x, String y) { + for (int i = 0; i < y.length(); i++) { + if (y.charAt(i) != x.charAt(i)) + return false; + } + return true; + } + + /** + * Print the substitutions list + */ + public String toString() { + String res = ""; + for (int i = 0; i < sub.size(); i++) { + res += sub.get(i).getNode().getIdentifier() + " substitutes " + sub.get(i).getVariable().getIdentifier() + + '\n'; + } + return res; + } + + public int termID(int variableID) { + for (int i = 0; i < sub.size(); i++) + if (sub.get(i).getVariable().getId() == variableID) + return sub.get(i).getNode().getId(); + return -1; + } + + @Override + public void insertOrUpdate(Binding mb) { + if (isBound(mb.getVariable())) + update(getBindingByVariable(mb.getVariable()), mb.getNode()); + else + putIn(mb); + + } } \ No newline at end of file diff --git a/src/sneps/snip/matching/Substitutions.java b/src/sneps/snip/matching/Substitutions.java index cdfffd9a..2407024a 100644 --- a/src/sneps/snip/matching/Substitutions.java +++ b/src/sneps/snip/matching/Substitutions.java @@ -4,38 +4,65 @@ import sneps.network.VariableNode; public interface Substitutions { - + public boolean isNew(); + public void putIn(Binding mb); + public boolean isCompatible(Binding mb); - public void update(Binding mb , Node mn); - public boolean isBound(VariableNode mv); - public boolean isValue(Node mn); - public VariableNode srcNode(Node mn); - public Binding getBindingByVariable(VariableNode mv); - public Binding getBindingByNode(Node mn); - public boolean isMember(Binding mb); - public boolean isSubSet(Substitutions s); - public boolean isEqual(Substitutions s); - public Substitutions union (Substitutions s); - public void unionIn (Substitutions s); - public Substitutions restrict(VariableNode [] ns); - public Node term(VariableNode mv); - public int cardinality(); - public Binding choose(); - public Substitutions others(); - public Node value(VariableNode n); - public Substitutions insert(Binding m); - public boolean isCompatible(Substitutions s); - public Binding getBinding(int x); - public Substitutions[] split(); - public void clear(); - public void insert(Substitutions s); - public boolean sub(String x, String y); - public String toString(); - public int termID(int variableID); - public void insertOrUpdate(Binding mb); + public void update(Binding mb, Node mn); + + public boolean isBound(VariableNode mv); + + public boolean isValue(Node mn); + + public VariableNode srcNode(Node mn); + + public Binding getBindingByVariable(VariableNode mv); + + public Binding getBindingByNode(Node mn); + + public boolean isMember(Binding mb); + + public boolean isSubSet(Substitutions s); + + public boolean isEqual(Substitutions s); + + public Substitutions union(Substitutions s); + + public void unionIn(Substitutions s); + + public Substitutions restrict(VariableNode[] ns); + + public Node term(VariableNode mv); + + public int cardinality(); + + public Binding choose(); + + public Substitutions others(); + + public Node value(VariableNode n); + + public Substitutions insert(Binding m); + + public boolean isCompatible(Substitutions s); + + public Binding getBinding(int x); + + public Substitutions[] split(); + + public void clear(); + + public void insert(Substitutions s); + + public boolean sub(String x, String y); + + public String toString(); + + public int termID(int variableID); + public void insertOrUpdate(Binding mb); } diff --git a/tests/NetworkTestN.java b/tests/NetworkTestN.java index d0699e79..6bafc65b 100644 --- a/tests/NetworkTestN.java +++ b/tests/NetworkTestN.java @@ -1,6 +1,5 @@ package tests; - import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -24,30 +23,31 @@ import java.util.LinkedList; public class NetworkTestN { - Semantic semantic; - final static String semanticType = "Proposition"; - - - @Before - public void setUp() throws CustomException{ - semantic = new Semantic(semanticType); - } - - @Test - public void buildBaseNode() throws NotAPropositionNodeException, NodeNotFoundInNetworkException, IllegalIdentifierException{ - Network.buildBaseNode("n0", semantic); - Node n0 = Network.getNode("n0"); - //Hashtable propositionNodes = Network.getPropositionNodes(); - assertTrue(Network.getNodeById(0) instanceof PropositionNode); - assertEquals(n0, Network.getNodeById(0)); - assertTrue(n0.getTerm() instanceof Base); - - - } - - @After - public void removeNodes() throws NodeCannotBeRemovedException, NodeNotFoundInNetworkException, NodeNotFoundInPropSetException, NotAPropositionNodeException { - Network.removeNode(Network.getNode("n0")); - } + Semantic semantic; + final static String semanticType = "Proposition"; + + @Before + public void setUp() throws CustomException { + semantic = new Semantic(semanticType); + } + + @Test + public void buildBaseNode() + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, IllegalIdentifierException { + Network.buildBaseNode("n0", semantic); + Node n0 = Network.getNode("n0"); + // Hashtable propositionNodes = + // Network.getPropositionNodes(); + assertTrue(Network.getNodeById(0) instanceof PropositionNode); + assertEquals(n0, Network.getNodeById(0)); + assertTrue(n0.getTerm() instanceof Base); + + } + + @After + public void removeNodes() throws NodeCannotBeRemovedException, NodeNotFoundInNetworkException, + NodeNotFoundInPropSetException, NotAPropositionNodeException { + Network.removeNode(Network.getNode("n0")); + } } \ No newline at end of file From be5d8dea131647f89b284ab49671ed64fe997e36 Mon Sep 17 00:00:00 2001 From: Youssef Date: Fri, 29 Mar 2019 14:09:32 +0200 Subject: [PATCH 02/22] migrate deduce method to class PropositionNode --- src/sneps/network/Node.java | 33 +++++--------------------- src/sneps/network/PropositionNode.java | 29 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 27 deletions(-) diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java index 6a6d48b5..af7af3b6 100644 --- a/src/sneps/network/Node.java +++ b/src/sneps/network/Node.java @@ -11,10 +11,15 @@ import sneps.network.classes.term.Term; import sneps.network.classes.setClasses.NodeSet; import sneps.snebr.Context; +import sneps.snebr.Controller; import sneps.snip.Pair; import sneps.snip.Runner; +import sneps.snip.channels.AntecedentToRuleChannel; import sneps.snip.channels.Channel; import sneps.snip.channels.ChannelTypes; +import sneps.snip.channels.MatchChannel; +import sneps.snip.channels.RuleToConsequentChannel; +import sneps.snip.matching.LinearSubstitutions; import sneps.snip.matching.Substitutions; public class Node implements Serializable { @@ -210,34 +215,8 @@ public boolean isWhQuestion(Substitutions sub) { Context fake() { return null; } + - public void deduce() { - Runner.initiate(); - Node toBeDeduced = this; - /** - * Retrieving all Dominating rules for Node and sending requests to each. - */ - NodeSet dominatingRules = getDominatingRules(); - sendRequests(dominatingRules, channel.getFilter().getSubstitution(), channel.getContextID(), - ChannelTypes.RuleCons); - try { - /** - * Retrieving all matching nodes for Node and sending requests to each. - */ - List matchesReturned = Matcher.Match(toBeDeduced); - if (matchesReturned != null) { - ArrayList matches = new ArrayList(); - for (Object[] match : matchesReturned) { - Pair newPair = new Pair((Substitutions) match[1], (Substitutions) match[2], (Node) match[0]); - matches.add(newPair); - } - sendRequests(matches, channel.getContextID(), ChannelTypes.MATCHED); - } - } catch (Exception e) { - e.printStackTrace(); - } - Runner.run(); // what to return here ? - } public void setTerm(Term term) { this.term = term; diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 27d92548..7b3ed14d 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -211,6 +211,35 @@ public void sendRequests(NodeSet ns, Substitutions filterSubs, String contextID, } } + public void deduce() { + Runner.initiate(); + PropositionNode toBeDeduced = this; + String currentContextName = Controller.getCurrentContextName(); + /** + * Retrieving all Dominating rules for Node and sending requests to each. + */ + NodeSet dominatingRules = getDominatingRules(); + toBeDeduced.sendRequests(dominatingRules, new LinearSubstitutions(), currentContextName, + ChannelTypes.RuleCons); + try { + /** + * Retrieving all matching nodes for Node and sending requests to each. + */ + List matchesReturned = Matcher.match(toBeDeduced); + if (matchesReturned != null) { + ArrayList matches = new ArrayList(); + for (Object[] match : matchesReturned) { + Pair newPair = new Pair((Substitutions) match[1], (Substitutions) match[2], (Node) match[0]); + matches.add(newPair); + } + toBeDeduced.sendRequests(matches, currentContextName, ChannelTypes.MATCHED); + } + } catch (Exception e) { + e.printStackTrace(); + } + Runner.run(); // what to return here ? + } + public boolean alreadyWorking(Channel channel) { return false; } From ca158652b92495ed06af33e66aed9affea7382f7 Mon Sep 17 00:00:00 2001 From: Youssef Date: Fri, 5 Apr 2019 22:17:59 +0200 Subject: [PATCH 03/22] initialized two matching classes and declared some functions to adapt with latest processSingleRequestsChannel --- src/sneps/network/Node.java | 26 +- src/sneps/network/PropositionNode.java | 261 ++++---- src/sneps/network/RuleNode.java | 84 ++- .../network/classes/setClasses/NodeSet.java | 15 +- .../classes/setClasses/PropositionSet.java | 569 +++++++++--------- .../classes/setClasses/VariableSet.java | 17 +- src/sneps/snip/Filter.java | 16 +- src/sneps/snip/channels/Channel.java | 18 + src/sneps/snip/matching/Match.java | 49 ++ src/sneps/snip/matching/Matcher.java | 14 + 10 files changed, 610 insertions(+), 459 deletions(-) create mode 100644 src/sneps/snip/matching/Match.java create mode 100644 src/sneps/snip/matching/Matcher.java diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java index af7af3b6..5846a7da 100644 --- a/src/sneps/network/Node.java +++ b/src/sneps/network/Node.java @@ -2,6 +2,7 @@ import java.io.Serializable; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; import sneps.network.cables.UpCable; @@ -9,7 +10,9 @@ import sneps.network.classes.Semantic; import sneps.network.classes.term.Molecular; import sneps.network.classes.term.Term; +import sneps.network.classes.term.Variable; import sneps.network.classes.setClasses.NodeSet; +import sneps.network.classes.setClasses.VariableSet; import sneps.snebr.Context; import sneps.snebr.Controller; import sneps.snip.Pair; @@ -197,26 +200,21 @@ public NodeSet getDominatingRules() { } public boolean isWhQuestion(Substitutions sub) { - /* - * if (!this.getIdentifier().equalsIgnoreCase("patternnode")) return false; - * - * PatternNode node = (PatternNode) this; LinkedList variables = - * node.getFreeVariables(); - * - * for (int i = 0; i < variables.size(); i++) { Node termNode = - * sub.term(variables.get(i)); if (termNode == null || - * (!termNode.getIdentifier().equalsIgnoreCase("basenode"))) return true; - * - * } - */ +// if (!this.getIdentifier().equalsIgnoreCase("patternnode")) +// return false; +// VariableNode node = (VariableNode) this; +// VariableSet variables = node.getFreeVariables(); +// for (Variable currentVariable: variables) { +// Node termNode = sub.term(currentVariable); +// if (termNode == null || (!termNode.getIdentifier().equalsIgnoreCase("basenode"))) +// return true; +// } return false; } Context fake() { return null; } - - public void setTerm(Term term) { this.term = term; diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 7b3ed14d..beb4baf7 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -33,6 +33,8 @@ import sneps.snip.channels.MatchChannel; import sneps.snip.channels.RuleToConsequentChannel; import sneps.snip.matching.LinearSubstitutions; +import sneps.snip.matching.Match; +import sneps.snip.matching.Matcher; import sneps.snip.matching.Substitutions; public class PropositionNode extends Node implements Serializable { @@ -57,6 +59,77 @@ public PropositionNode(Term trm) { setTerm(trm); } + /*** + * Adding a report to all outgoing channels + * + * @param report + */ + public void broadcastReport(Report report) { + for (Channel outChannel : outgoingChannels) { + if (outChannel.addReport(report)) { + // System.out.println("SENDING REPORT " + this); + } + } + } + + public boolean sendReport(Report report, Channel channel) { + if (channel.addReport(report)) { + // System.out.println("SENDING REPORT " + this); + return true; + } + return false; + } + + /*** + * Method handling all types of Channels establishment according to different + * channel types passed through the matching. + * + * @param type type of channel being addressed + * @param currentElement source Node/Match element being addressed + * @param switchSubs mapped substitutions from origin node + * @param filterSubs constraints substitutions for a specific request + * @param contextId context name used + * @return the established type based channel + */ + private Channel establishChannel(ChannelTypes type, Object currentElement, Substitutions switchSubs, + Substitutions filterSubs, String contextId) { + boolean matchTypeEstablishing = currentElement instanceof Match; + Node evaluatedReporter = matchTypeEstablishing ? ((Match) currentElement).getNode() : (Node) currentElement; + Substitutions switchLinearSubs = switchSubs == null ? new LinearSubstitutions() : switchSubs; + Channel newChannel; + switch (type) { + case MATCHED: + newChannel = new MatchChannel(switchLinearSubs, filterSubs, contextId, this, evaluatedReporter, true); + break; + case RuleAnt: + newChannel = new AntecedentToRuleChannel(switchLinearSubs, filterSubs, contextId, this, evaluatedReporter, + true); + default: + newChannel = new RuleToConsequentChannel(switchLinearSubs, filterSubs, contextId, this, evaluatedReporter, + true); + } + return newChannel; + + } + + public void sendRequests(List list, String contextId, ChannelTypes channelType) { + for (Match currentMatch : list) { + Substitutions switchSubs = currentMatch.getSwitchSubs(); + Substitutions filterSubs = currentMatch.getFilterSubs(); + Channel newChannel = establishChannel(channelType, currentMatch, switchSubs, filterSubs, contextId); + incomingChannels.addChannel(newChannel); + currentMatch.getNode().receiveRequest(newChannel); + } + } + + public void sendRequests(NodeSet ns, Substitutions filterSubs, String contextID, ChannelTypes channelType) { + for (Node sentTo : ns) { + Channel newChannel = establishChannel(channelType, sentTo, null, filterSubs, contextID); + incomingChannels.addChannel(newChannel); + sentTo.receiveRequest(newChannel); + } + } + public void processSingleReportsChannel(Channel currentChannel) { ReportSet reports = currentChannel.getReportsBuffer(); for (Report currentReport : reports) { @@ -81,64 +154,68 @@ public void processReports() { * Request handling in Non-Rule proposition nodes. * * @param currentChannel + * @throws NodeNotFoundInNetworkException + * @throws NotAPropositionNodeException + * @throws DuplicatePropositionException */ - public void processSingleRequestsChannel(Channel currentChannel) { + public void processSingleRequestsChannel(Channel currentChannel) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { // TODO check correctness - /* + int instanceNodeId = getId(); PropositionSet propSet = new PropositionSet(); - // TODO addProposition with input a Node - propSet.addProposition((PropositionNode) this); - Context desiredContext = Controller.getContextID(currentChannel.getContextID()); - // TODO assertedInContext - if (propSet.assertedInContext(desiredContext)) { + propSet.add(instanceNodeId); + String currentContextName = currentChannel.getContextName(); + Context desiredContext = Controller.getContextByName(currentContextName); + if (assertedInContext(desiredContext)) { // TODO change the subs to hashsubs - // #Sends an instance of this report# - // System.out.println("#$#$#$#$# -1 " + desiredContext.getId()); + /** + * Sends an instance of this report + */ Set support = new HashSet(); - // TODO Blank Support constructor with input a Node - support.add(new Support((PropositionNode) this)); - Report reply = new Report(new LinearSubstitutions(), support, true, currentChannel.getContextID()); + support.add(new Support(instanceNodeId)); + Report reply = new Report(new LinearSubstitutions(), support, true, currentChannel.getContextName()); knownInstances.addReport(reply); broadcastReport(reply); } else { - // #Sends any previously known instances# + /** + * Sends any previously known instances + */ boolean sentAtLeastOne = false; for (Report currentReport : knownInstances) { - sentAtLeastOne = sendReport(currentReport, currentChannel); + sentAtLeastOne |= sendReport(currentReport, currentChannel); } // TODO Akram: passed the filter subs to isWhQuest, is that correct? - // System.out.println("#$#$#$#$# 0"); - if (!sentAtLeastOne || isWhQuestion(currentChannel.getFilter().getSubstitution())) { + if (!sentAtLeastOne || isWhQuestion(currentChannel.getFilter().getSubstitutions())) if (!alreadyWorking(currentChannel)) { - NodeSet dominatingRules = getDominatingRules(); - sendRequests(dominatingRules, currentChannel.getFilter().getSubstitution(), - currentChannel.getContextID(), ChannelTypes.RuleCons); - // System.out.println("#$#$#$#$# 1"); - if (!(currentChannel instanceof MatchChannel)) { - try { - List matchesReturned = Matcher.Match(this); - if (matchesReturned != null) { - ArrayList matches = new ArrayList(); - for (Object[] match : matchesReturned) { - Pair newPair = new Pair((Substitutions) match[1], (Substitutions) match[2], - (Node) match[0]); - matches.add(newPair); - } - sendRequests(matches, currentChannel.getContextID(), ChannelTypes.MATCHED); - } - } catch (Exception e) { - e.printStackTrace(); - } - } + getNodesToSendRequests(ChannelTypes.RuleCons, currentChannel.getContextName(), + currentChannel.getFilter().getSubstitutions()); + if (!(currentChannel instanceof MatchChannel)) + getNodesToSendRequests(ChannelTypes.MATCHED, currentChannel.getContextName(), null); } - } } - */ + } + + /*** + * + * @param desiredContext + * @return whether the PropositionNode is asserted in a desiredContext or not + * @throws NodeNotFoundInNetworkException + * @throws NotAPropositionNodeException + */ + public boolean assertedInContext(Context desiredContext) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + return desiredContext.isAsserted(this); } public void processRequests() { for (Channel outChannel : outgoingChannels) - processSingleRequestsChannel(outChannel); + try { + processSingleRequestsChannel(outChannel); + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { + e.printStackTrace(); + } catch (DuplicatePropositionException e) { + e.printStackTrace(); + } } /*** @@ -151,95 +228,53 @@ public void receiveRequest(Channel channel) { } /*** - * Reports received added to the high priority queue to be served accordingly through - * the runner. + * Reports received added to the high priority queue to be served accordingly + * through the runner. */ public void receiveReports(Channel channel) { outgoingChannels.addChannel(channel); Runner.addToHighQueue(this); } - public void broadcastReport(Report report) { - for (Channel outChannel : outgoingChannels) { - if (outChannel.addReport(report)) { - // System.out.println("SENDING REPORT " + this); - } - } - } - - public boolean sendReport(Report report, Channel channel) { - if (channel.addReport(report)) { - // System.out.println("SENDING REPORT " + this); - return true; - } - return false; - } - - public void sendRequests(ArrayList list, String conetxtID, ChannelTypes channelType) { - for (Pair currentPair : list) { - Substitutions switchSubs = currentPair.getSwitch(); - Substitutions filterSubs = currentPair.getFilter(); - Channel newChannel; - if (channelType == ChannelTypes.MATCHED) { - newChannel = new MatchChannel(switchSubs, filterSubs, conetxtID, this, currentPair.getNode(), true); - } else if (channelType == ChannelTypes.RuleAnt) { - newChannel = new AntecedentToRuleChannel(switchSubs, filterSubs, conetxtID, this, currentPair.getNode(), - true); - } else { - newChannel = new RuleToConsequentChannel(switchSubs, filterSubs, conetxtID, this, currentPair.getNode(), - true); - } - incomingChannels.addChannel(newChannel); - currentPair.getNode().receiveRequest(newChannel); - } - } - - public void sendRequests(NodeSet ns, Substitutions filterSubs, String contextID, ChannelTypes channelType) { - for (Node sentTo : ns) { - Channel newChannel = null; - if (channelType == ChannelTypes.MATCHED) { - newChannel = new MatchChannel(new LinearSubstitutions(), filterSubs, contextID, this, sentTo, true); - } else if (channelType == ChannelTypes.RuleAnt) { - newChannel = new AntecedentToRuleChannel(new LinearSubstitutions(), filterSubs, contextID, this, sentTo, - true); - } else { - newChannel = new RuleToConsequentChannel(new LinearSubstitutions(), filterSubs, contextID, this, sentTo, - true); - } - incomingChannels.addChannel(newChannel); - sentTo.receiveRequest(newChannel); - } - } - public void deduce() { Runner.initiate(); - PropositionNode toBeDeduced = this; String currentContextName = Controller.getCurrentContextName(); - /** - * Retrieving all Dominating rules for Node and sending requests to each. - */ - NodeSet dominatingRules = getDominatingRules(); - toBeDeduced.sendRequests(dominatingRules, new LinearSubstitutions(), currentContextName, - ChannelTypes.RuleCons); + getNodesToSendRequests(ChannelTypes.RuleCons, currentContextName, null); + getNodesToSendRequests(ChannelTypes.MATCHED, currentContextName, null); + Runner.run(); // what to return here ? + } + + /*** + * Method handling all types of Nodes retrieval and sending different type-based + * requests to each Node Type + * + * @param type type of channel being addressed + * @param currentContextName context name used + * @param substitutions channel substitutions applied over the channel + */ + private void getNodesToSendRequests(ChannelTypes type, String currentContextName, Substitutions substitutions) { try { - /** - * Retrieving all matching nodes for Node and sending requests to each. - */ - List matchesReturned = Matcher.match(toBeDeduced); - if (matchesReturned != null) { - ArrayList matches = new ArrayList(); - for (Object[] match : matchesReturned) { - Pair newPair = new Pair((Substitutions) match[1], (Substitutions) match[2], (Node) match[0]); - matches.add(newPair); - } - toBeDeduced.sendRequests(matches, currentContextName, ChannelTypes.MATCHED); + switch (type) { + case MATCHED: + List matchesReturned = Matcher.match(this); + if (matchesReturned != null) + sendRequests(matchesReturned, currentContextName, type); + break; + case RuleCons: + NodeSet dominatingRules = getDominatingRules(); + // TODO Youssef: check if passing a new LinearSubstitutions is correct + Substitutions linearSubs = substitutions == null ? new LinearSubstitutions() : substitutions; + sendRequests(dominatingRules, linearSubs, currentContextName, type); + break; + default: + break; } } catch (Exception e) { e.printStackTrace(); } - Runner.run(); // what to return here ? + } - + public boolean alreadyWorking(Channel channel) { return false; } diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index d05faebc..ffdf9935 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -5,10 +5,14 @@ import java.util.Hashtable; import java.util.Set; +import sneps.exceptions.DuplicatePropositionException; +import sneps.exceptions.NodeNotFoundInNetworkException; +import sneps.exceptions.NotAPropositionNodeException; 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; import sneps.network.classes.setClasses.ReportSet; import sneps.network.classes.setClasses.RuleUseInfoSet; import sneps.network.classes.setClasses.VariableSet; @@ -17,14 +21,17 @@ import sneps.network.classes.term.Term; import sneps.snebr.Context; import sneps.snebr.Controller; +import sneps.snebr.Support; import sneps.snip.Report; import sneps.snip.channels.AntecedentToRuleChannel; import sneps.snip.channels.Channel; import sneps.snip.channels.ChannelTypes; +import sneps.snip.channels.MatchChannel; import sneps.snip.channels.RuleToConsequentChannel; import sneps.snip.classes.FlagNode; import sneps.snip.classes.RuleUseInfo; import sneps.snip.classes.SIndex; +import sneps.snip.matching.LinearSubstitutions; public abstract class RuleNode extends PropositionNode implements Serializable { @@ -250,36 +257,63 @@ public static boolean isConstantNode(Node n) { @Override public void processRequests() { - for (Channel currentChannel : outgoingChannels) { - if (currentChannel instanceof RuleToConsequentChannel) { - VariableSet variablesList = ((Open) this.term).getFreeVariables(); - if (variablesList.isEmpty()) { - // Proposition semanticType = (Proposition) this.getSemantic();TODO change - // according to snebr - if (this.semanticType.isAsserted(Controller.getContextByName(currentChannel.getContextName()))) { - NodeSet antecedentNodeSet = this.getDownAntNodeSet(); - NodeSet toBeSentTo = new NodeSet(); - for (Node currentNode : antecedentNodeSet) { - if (currentNode == currentChannel.getRequester()) { - continue; - } - // TODO Akram: if not yet been requested for this - // instance - if (true) { - toBeSentTo.addNode(currentNode); - } + for (Channel outChannel : outgoingChannels) + try { + processSingleRequestsChannel(outChannel); + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { + e.printStackTrace(); + } catch (DuplicatePropositionException e) { + e.printStackTrace(); + } + } + + /*** + * Request handling in Rule proposition nodes. + * + * @param currentChannel + * @throws NodeNotFoundInNetworkException + * @throws NotAPropositionNodeException + * @throws DuplicatePropositionException + */ + public void processSingleRequestsChannel(Channel currentChannel) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { + if (currentChannel instanceof RuleToConsequentChannel) { + VariableSet variablesList = ((Open) this.term).getFreeVariables(); + if (variablesList.isEmpty()) { + // Proposition semanticType = (Proposition) this.getSemantic(); + // TODO change according to snebr + String currentContextName = currentChannel.getContextName(); + Context currentContext = Controller.getContextByName(currentContextName); + if (assertedInContext(currentContext)) { // this.semanticType.isAsserted(currentContext) + NodeSet antecedentNodeSet = getDownAntNodeSet(); + NodeSet toBeSentTo = new NodeSet(); + for (Node currentNode : antecedentNodeSet) { + if (currentNode == currentChannel.getRequester()) + continue; + + // TODO Akram: if not yet been requested for this + // instance + // TODO Youssef: added requestServing to monitor requests status over each + // channel established + if (!currentChannel.isRequestProcessed()) { + toBeSentTo.addNode(currentNode); } - sendRequests(toBeSentTo, currentChannel.getFilter().getSubstitution(), - currentChannel.getContextName(), ChannelTypes.RuleAnt); } - } else if (true) { - // TODO Akram: there are free variables but each is bound - } else if (true) { - // TODO Akram: there are free variable + sendRequests(toBeSentTo, currentChannel.getFilter().getSubstitutions(), + currentChannel.getContextName(), ChannelTypes.RuleAnt); } - + } else if (variablesList.areVariablesBound()) { + // TODO Akram: there are free variables but each is bound } else { + // TODO Akram: there is a free variable not bound + } + + } else { + try { super.processSingleRequestsChannel(currentChannel); + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException | DuplicatePropositionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } } } diff --git a/src/sneps/network/classes/setClasses/NodeSet.java b/src/sneps/network/classes/setClasses/NodeSet.java index 4634eae3..2da30f39 100644 --- a/src/sneps/network/classes/setClasses/NodeSet.java +++ b/src/sneps/network/classes/setClasses/NodeSet.java @@ -13,14 +13,13 @@ public NodeSet() { nodes = new Vector(); } - public Node getNode(int index) { return this.nodes.get(index); } public void addNode(Node node) { - if (!this.nodes.contains(node)) - this.nodes.add(node); + if (!nodes.contains(node)) + nodes.add(node); } public int size() { @@ -40,11 +39,11 @@ public void removeNode(Node node) { public void clear() { this.nodes.clear(); } - + public boolean isEmpty() { return this.nodes.isEmpty(); } - + public boolean contains(Node node) { return this.nodes.contains(node); } @@ -95,8 +94,8 @@ public Iterator iterator() { } /** - * This method overrides the default toString method inherited from the - * Object class. + * This method overrides the default toString method inherited from the Object + * class. */ @Override public String toString() { @@ -109,5 +108,5 @@ public String toString() { s += "}"; return s; } - + } diff --git a/src/sneps/network/classes/setClasses/PropositionSet.java b/src/sneps/network/classes/setClasses/PropositionSet.java index c959dbcd..42a20c67 100644 --- a/src/sneps/network/classes/setClasses/PropositionSet.java +++ b/src/sneps/network/classes/setClasses/PropositionSet.java @@ -12,296 +12,291 @@ import java.io.Serializable; import java.util.Arrays; -public class PropositionSet implements Serializable{ - @Override - public String toString() { - return "PropositionSet [props=" + Arrays.toString(props) + "]"; - } - - private int[] props; - private String hash = ""; - - /** - * Constructs a new PropositionSet with an empty array of props - */ - public PropositionSet() { - this.props = new int[0]; - } - - /** - * Constructs a new PropositionSet with an array containing a single prop - * - * @param prop proposition to be added to the array of props in this PropositionSet - * @throws NotAPropositionNodeException - * @throws NodeNotFoundInNetworkException - * @throws CustomException - */ - public PropositionSet(int prop) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - if (!(Network.getNodeById(prop) instanceof PropositionNode)) { - throw new NotAPropositionNodeException(); - } - this.props = new int[]{prop}; - hash = prop + ","; - } - - /** - * Constructs a new PropositionSet with an array containing of propositions - * deep cloning of the array occurs here. - * - * @param props the array of props to populate the props attribute with - * @throws NodeNotFoundInNetworkException - */ - public PropositionSet(int[] props) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - for (int i = 0; i < props.length; i++) - if (!(Network.getNodeById(props[i]) instanceof PropositionNode)) - throw new NotAPropositionNodeException(); - - this.props = removeDuplicates(props); - Arrays.sort(this.props); - for (int i = 0; i < this.props.length; i++) { - hash += this.props[i] + ","; - } - } - - - /** - * Returns a new props array having no duplicates - * - * @param props the array of props that duplicates should be removed from if found - * @return a new array of props having no duplicates - */ - public static int[] removeDuplicates(int[] props) { - int current = -1, j = 0; - int[] temp = new int[props.length]; - for (int i = 0; i < props.length; i++) { - if (current == props[i]) - continue; - else { - current = props[i]; - temp[j] = current; - j++; - } - } - return Arrays.copyOfRange(temp, 0, j); - } - - /** - * Method for returning the props of the PropositionSet - * - * @return an int array containing the props - */ - private int[] getProps() { - return props; - } - - /** - * Returns an array of the props in a given PropositionSet - * but insures immutability through deep cloning of the props done by the - * PropositionSet constructor. - * - * @return a new int array of props - * @throws NodeNotFoundInNetworkException - */ - public static int[] getPropsSafely(PropositionSet set) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - return new PropositionSet(set.getProps()).props; - } - - /** - * Checks if a given PropositionSet is equivalent to this. - * It checks for equality by comparing the equivalence of the two props arrays. - * - * @param obj - * @return true if they are equal and false otherwise. - */ - public boolean equals(Object obj) { - PropositionSet propositionSet = (PropositionSet) obj; - int[] inputProps = propositionSet.getProps(); - if (inputProps.length != this.props.length) { - return false; - } else { - for (int i = 0; i < this.props.length; i++) { - if (this.props[i] != inputProps[i]) - return false; - } - } - return true; - } - - /** - * Checks if this PropositionSet is a subset of a passed PropositionSet. - * - * @param propositionSet the set that should be a superset of this PropositionSet - * @return true if this is a subset of propositionSet, false otherwise. - */ - public boolean isSubSet(PropositionSet propositionSet) { - int[] props = propositionSet.getProps(); - int i = 0, j = 0; - while (i < this.props.length && j < props.length) { - if (this.props[i] == props[j]) - i++; - else - j++; - } - return i == this.props.length; - } - - /** - * Performs a union of this PropositionSet and a passed PropositionSet and returns - * a new PropositionSet with the union - * - * @param propSet the PropositionSet to perform union with. - * @return the union of the two PropositionSets - * @throws NodeNotFoundInNetworkException - */ - - public PropositionSet union(PropositionSet propSet) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - int[] props = propSet.getProps(); - int[] props1 = this.getProps(); - int[] props2 = new int[props.length + props1.length]; - - int i = 0, j = 0, k = 0; - - while (i < props.length || j < props1.length) { - - if (i >= props.length) { // length of arg passed - props2[k++] = props1[j++]; - continue; - } else if (j >= props1.length) { - props2[k++] = props[i++]; - continue; - } - - if (props[i] == props1[j]) { - props2[k] = props[i]; - i++; - j++; - } else if (props[i] < props1[j]) { - props2[k] = props[i]; - i++; - } else { - props2[k] = props1[j]; - j++; - } - k++; - } - - int[] output = Arrays.copyOfRange(props2, 0, k); - return new PropositionSet(output); - } - - public boolean isEmpty() { - return props.length == 0; - } - - public PropositionSet clearSet() { - return new PropositionSet(); - } - - public String getHash() { - return hash; - } - - /** - * Returns a new PropositionSet without the proposition passed as an argument. - * - * @param prop the proposition that shouldn't be present in the returned PropositionSet - * @return a new PropositionSet not having prop. - * @throws NodeNotFoundInPropSetException if prop is not found in this PropositionSet - * @throws NodeNotFoundInNetworkException - */ - public PropositionSet remove(int prop) throws NodeNotFoundInPropSetException, NotAPropositionNodeException, NodeNotFoundInNetworkException { - if (this.props.length == 0) - return new PropositionSet(); - - int[] current = this.getProps(); - int[] newSet = new int[current.length - 1]; - int j = 0; - boolean found = false; - if (props[props.length - 1] < prop) - throw new NodeNotFoundInPropSetException("The Node You Are Trying To Remove is Not Found"); - for (int i = 0; i < current.length; i++) { - if (prop < current[i] && !found) - throw new NodeNotFoundInPropSetException("The Node You Are Trying To Remove is Not Found"); - if (!(prop == current[i])) { - newSet[j] = current[i]; - j++; - } else { - found = true; - } - } - return new PropositionSet(newSet); - } - - public PropositionSet removeProps(PropositionSet propSet) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - int[] props = this.getProps(); - int[] props1 = propSet.getProps(); - int[] props2 = new int[props.length]; - - int i = 0, j = 0, k = 0; - - for (; i < props.length; i++) { - - if (j >= props1.length) { - props2[k++] = props[i]; - continue; - } - - if (props[i] == props1[j]) { - j++; - } else { - props2[k] = props[i]; - k++; - } - } - - int[] output = Arrays.copyOfRange(props2, 0, k); - return new PropositionSet(output); - - } - - /** - * Creates a new PropositionSet with a prop if it isn't a duplicate. - * - * @param prop The proposition that is desired to be added. - * @return A new PropositionSet with the added prop. - * @throws DuplicatePropositionException If the prop is a duplicate - * @throws NodeNotFoundInNetworkException - */ - public PropositionSet add(int prop) throws DuplicatePropositionException, NotAPropositionNodeException, NodeNotFoundInNetworkException { - int[] props = this.props; - int[] props2 = new int[props.length + 1]; - int i = 0, j = 0; - boolean inserted = false; - while (i < props.length) { - if (props[i] == prop) - throw new DuplicatePropositionException(); - - if (!inserted && prop < props[i]) { - props2[j++] = prop; - inserted = true; - } else { - props2[j++] = props[i++]; - } - } - - if (!inserted) - props2[j] = prop; - - hash = hash + ","; - - return new PropositionSet(props2); - - } - - public void addProposition(PropositionNode propositionNode) { - // TODO Auto-generated method stub - +public class PropositionSet implements Serializable { + @Override + public String toString() { + return "PropositionSet [props=" + Arrays.toString(props) + "]"; } - public boolean assertedInContext(Context desiredContext) { - // TODO Auto-generated method stub - return false; + private int[] props; + private String hash = ""; + + /** + * Constructs a new PropositionSet with an empty array of props + */ + public PropositionSet() { + this.props = new int[0]; + } + + /** + * Constructs a new PropositionSet with an array containing a single prop + * + * @param prop proposition to be added to the array of props in this + * PropositionSet + * @throws NotAPropositionNodeException + * @throws NodeNotFoundInNetworkException + * @throws CustomException + */ + public PropositionSet(int prop) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + if (!(Network.getNodeById(prop) instanceof PropositionNode)) { + throw new NotAPropositionNodeException(); + } + this.props = new int[] { prop }; + hash = prop + ","; + } + + /** + * Constructs a new PropositionSet with an array containing of propositions deep + * cloning of the array occurs here. + * + * @param props the array of props to populate the props attribute with + * @throws NodeNotFoundInNetworkException + */ + public PropositionSet(int[] props) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + for (int i = 0; i < props.length; i++) + if (!(Network.getNodeById(props[i]) instanceof PropositionNode)) + throw new NotAPropositionNodeException(); + + this.props = removeDuplicates(props); + Arrays.sort(this.props); + for (int i = 0; i < this.props.length; i++) { + hash += this.props[i] + ","; + } + } + + /** + * Returns a new props array having no duplicates + * + * @param props the array of props that duplicates should be removed from if + * found + * @return a new array of props having no duplicates + */ + public static int[] removeDuplicates(int[] props) { + int current = -1, j = 0; + int[] temp = new int[props.length]; + for (int i = 0; i < props.length; i++) { + if (current == props[i]) + continue; + else { + current = props[i]; + temp[j] = current; + j++; + } + } + return Arrays.copyOfRange(temp, 0, j); + } + + /** + * Method for returning the props of the PropositionSet + * + * @return an int array containing the props + */ + private int[] getProps() { + return props; } + /** + * Returns an array of the props in a given PropositionSet but insures + * immutability through deep cloning of the props done by the PropositionSet + * constructor. + * + * @return a new int array of props + * @throws NodeNotFoundInNetworkException + */ + public static int[] getPropsSafely(PropositionSet set) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + return new PropositionSet(set.getProps()).props; + } + + /** + * Checks if a given PropositionSet is equivalent to this. It checks for + * equality by comparing the equivalence of the two props arrays. + * + * @param obj + * @return true if they are equal and false otherwise. + */ + public boolean equals(Object obj) { + PropositionSet propositionSet = (PropositionSet) obj; + int[] inputProps = propositionSet.getProps(); + if (inputProps.length != this.props.length) { + return false; + } else { + for (int i = 0; i < this.props.length; i++) { + if (this.props[i] != inputProps[i]) + return false; + } + } + return true; + } + + /** + * Checks if this PropositionSet is a subset of a passed PropositionSet. + * + * @param propositionSet the set that should be a superset of this + * PropositionSet + * @return true if this is a subset of propositionSet, + * false otherwise. + */ + public boolean isSubSet(PropositionSet propositionSet) { + int[] props = propositionSet.getProps(); + int i = 0, j = 0; + while (i < this.props.length && j < props.length) { + if (this.props[i] == props[j]) + i++; + else + j++; + } + return i == this.props.length; + } + + /** + * Performs a union of this PropositionSet and a passed PropositionSet and + * returns a new PropositionSet with the union + * + * @param propSet the PropositionSet to perform union with. + * @return the union of the two PropositionSets + * @throws NodeNotFoundInNetworkException + */ + + public PropositionSet union(PropositionSet propSet) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + int[] props = propSet.getProps(); + int[] props1 = this.getProps(); + int[] props2 = new int[props.length + props1.length]; + + int i = 0, j = 0, k = 0; + + while (i < props.length || j < props1.length) { + + if (i >= props.length) { // length of arg passed + props2[k++] = props1[j++]; + continue; + } else if (j >= props1.length) { + props2[k++] = props[i++]; + continue; + } + + if (props[i] == props1[j]) { + props2[k] = props[i]; + i++; + j++; + } else if (props[i] < props1[j]) { + props2[k] = props[i]; + i++; + } else { + props2[k] = props1[j]; + j++; + } + k++; + } + + int[] output = Arrays.copyOfRange(props2, 0, k); + return new PropositionSet(output); + } + + public boolean isEmpty() { + return props.length == 0; + } + + public PropositionSet clearSet() { + return new PropositionSet(); + } + + public String getHash() { + return hash; + } + + /** + * Returns a new PropositionSet without the proposition passed as an argument. + * + * @param prop the proposition that shouldn't be present in the returned + * PropositionSet + * @return a new PropositionSet not having prop. + * @throws NodeNotFoundInPropSetException if prop is not found in this + * PropositionSet + * @throws NodeNotFoundInNetworkException + */ + public PropositionSet remove(int prop) + throws NodeNotFoundInPropSetException, NotAPropositionNodeException, NodeNotFoundInNetworkException { + if (this.props.length == 0) + return new PropositionSet(); + + int[] current = this.getProps(); + int[] newSet = new int[current.length - 1]; + int j = 0; + boolean found = false; + if (props[props.length - 1] < prop) + throw new NodeNotFoundInPropSetException("The Node You Are Trying To Remove is Not Found"); + for (int i = 0; i < current.length; i++) { + if (prop < current[i] && !found) + throw new NodeNotFoundInPropSetException("The Node You Are Trying To Remove is Not Found"); + if (!(prop == current[i])) { + newSet[j] = current[i]; + j++; + } else { + found = true; + } + } + return new PropositionSet(newSet); + } + + public PropositionSet removeProps(PropositionSet propSet) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + int[] props = this.getProps(); + int[] props1 = propSet.getProps(); + int[] props2 = new int[props.length]; + + int i = 0, j = 0, k = 0; + + for (; i < props.length; i++) { + + if (j >= props1.length) { + props2[k++] = props[i]; + continue; + } + + if (props[i] == props1[j]) { + j++; + } else { + props2[k] = props[i]; + k++; + } + } + + int[] output = Arrays.copyOfRange(props2, 0, k); + return new PropositionSet(output); + + } + + /** + * Creates a new PropositionSet with a prop if it isn't a duplicate. + * + * @param prop The proposition that is desired to be added. + * @return A new PropositionSet with the added prop. + * @throws DuplicatePropositionException If the prop is a duplicate + * @throws NodeNotFoundInNetworkException + */ + public PropositionSet add(int prop) + throws DuplicatePropositionException, NotAPropositionNodeException, NodeNotFoundInNetworkException { + int[] props = this.props; + int[] props2 = new int[props.length + 1]; + int i = 0, j = 0; + boolean inserted = false; + while (i < props.length) { + if (props[i] == prop) + throw new DuplicatePropositionException(); + if (!inserted && prop < props[i]) { + props2[j++] = prop; + inserted = true; + } else { + props2[j++] = props[i++]; + } + } + if (!inserted) + props2[j] = prop; + hash = hash + ","; + return new PropositionSet(props2); + + } } \ No newline at end of file diff --git a/src/sneps/network/classes/setClasses/VariableSet.java b/src/sneps/network/classes/setClasses/VariableSet.java index 9ee71cf4..21f87e14 100644 --- a/src/sneps/network/classes/setClasses/VariableSet.java +++ b/src/sneps/network/classes/setClasses/VariableSet.java @@ -17,8 +17,8 @@ public VariableSet() { public Iterator iterator() { return variables.iterator(); } - - public Variable getVariable(int index){ + + public Variable getVariable(int index) { return variables.get(index); } @@ -29,16 +29,25 @@ public void addVariable(Variable n) { public void addAll(VariableSet allVariables) { for (int i = 0; i < variables.size(); i++) { this.addVariable(allVariables.getVariable(i)); - } + } } public int size() { return variables.size(); } - public boolean isEmpty() { return variables.isEmpty(); } + /*** + * Method to iterate over all variables in the Vector to check for + * their bound status + * + * @return boolean expressing no none-bound free variables + */ + public boolean areVariablesBound() { + // TODO Youssef + return false; + } } diff --git a/src/sneps/snip/Filter.java b/src/sneps/snip/Filter.java index 02c2e9bf..a5bf26a5 100644 --- a/src/sneps/snip/Filter.java +++ b/src/sneps/snip/Filter.java @@ -5,18 +5,18 @@ import sneps.snip.matching.Substitutions; public class Filter { - private Substitutions substitution; + private Substitutions substitutions; public Filter() { - this.substitution = new LinearSubstitutions(); + this.substitutions = new LinearSubstitutions(); } public Filter(Substitutions substitution) { - this.substitution = substitution; + this.substitutions = substitution; } - public Substitutions getSubstitution() { - return substitution; + public Substitutions getSubstitutions() { + return substitutions; } @Override @@ -24,12 +24,12 @@ public boolean equals(Object filter) { Filter typeCastedObject = (Filter) filter; if (typeCastedObject == null) return false; - return this.substitution.isEqual(typeCastedObject.getSubstitution()); + return this.substitutions.isEqual(typeCastedObject.getSubstitutions()); } public boolean canPass(Report report) { - for (int i = 0; i < this.substitution.cardinality(); i++) { - Binding currentFilterBinding = substitution.getBinding(i); + for (int i = 0; i < this.substitutions.cardinality(); i++) { + Binding currentFilterBinding = substitutions.getBinding(i); Binding currentReportBinding = report.getSubstitutions() .getBindingByVariable(currentFilterBinding.getVariable()); System.out.println("Bindings " + currentFilterBinding + " " + report.getSubstitutions()); diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index 0292bb3b..8a6c5184 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -17,6 +17,8 @@ public abstract class Channel { private Node reporter; private boolean valve; private ReportSet reportsBuffer; + private boolean requestProcessed = false; + private boolean reportProcessed = false; public Channel() { filter = new Filter(); @@ -77,6 +79,22 @@ public ReportSet getReportsBuffer() { return reportsBuffer; } + public boolean isRequestProcessed() { + return requestProcessed; + } + + public void setRequestProcessed(boolean requestProcessed) { + this.requestProcessed = requestProcessed; + } + + public boolean isReportProcessed() { + return reportProcessed; + } + + public void setReportProcessed(boolean reportProcessed) { + this.reportProcessed = reportProcessed; + } + public void setValve(boolean valve) { this.valve = valve; } diff --git a/src/sneps/snip/matching/Match.java b/src/sneps/snip/matching/Match.java new file mode 100644 index 00000000..a8cabc27 --- /dev/null +++ b/src/sneps/snip/matching/Match.java @@ -0,0 +1,49 @@ +package sneps.snip.matching; + +import sneps.network.Node; + +public class Match { + private Substitutions filterSubs; + private Substitutions switchSubs; + private Node node; + private int matchType; + + public Match(Substitutions filterSubs, Substitutions switchSubs, Node n, int type) { + this.filterSubs = filterSubs; + this.switchSubs = switchSubs; + this.node = n; + this.matchType = type; + } + + public Substitutions getFilterSubs() { + return filterSubs; + } + + public void setFilterSubs(Substitutions filterSub) { + this.filterSubs = filterSub; + } + + public Substitutions getSwitchSubs() { + return switchSubs; + } + + public void setSwitchSubs(Substitutions switchSubs) { + this.switchSubs = switchSubs; + } + + public Node getNode() { + return node; + } + + public void setNode(Node node) { + this.node = node; + } + + public int getMatchType() { + return matchType; + } + + public void setMatchType(int matchType) { + this.matchType = matchType; + } +} diff --git a/src/sneps/snip/matching/Matcher.java b/src/sneps/snip/matching/Matcher.java new file mode 100644 index 00000000..060b8316 --- /dev/null +++ b/src/sneps/snip/matching/Matcher.java @@ -0,0 +1,14 @@ +package sneps.snip.matching; + +import java.util.List; + +import sneps.network.PropositionNode; + +public class Matcher { + + public static List match(PropositionNode toBeDeduced) { + // TODO Auto-generated method stub + return null; + } + +} From db76d23b5a7a7ca776ea97cf23245a867cbcc9e4 Mon Sep 17 00:00:00 2001 From: Youssef Date: Sun, 7 Apr 2019 20:29:46 +0200 Subject: [PATCH 04/22] handling different cases for RuleNode processSingleRequestsChannel --- src/sneps/network/Node.java | 20 ++- src/sneps/network/PropositionNode.java | 25 +++- src/sneps/network/RuleNode.java | 46 ++++-- src/sneps/network/classes/Semantic.java | 5 - .../classes/setClasses/ChannelSet.java | 16 ++ .../classes/setClasses/VariableSet.java | 13 +- src/sneps/snip/Switch.java | 28 ++-- src/sneps/snip/channels/Channel.java | 17 +++ src/sneps/snip/matching/Binding.java | 137 +++++++++--------- .../snip/matching/LinearSubstitutions.java | 8 + src/sneps/snip/matching/Match.java | 4 +- src/sneps/snip/matching/Substitutions.java | 2 + 12 files changed, 204 insertions(+), 117 deletions(-) diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java index 5846a7da..cea9f5be 100644 --- a/src/sneps/network/Node.java +++ b/src/sneps/network/Node.java @@ -199,17 +199,29 @@ public NodeSet getDominatingRules() { return ret; } - public boolean isWhQuestion(Substitutions sub) { + public boolean isWhQuestion(Substitutions switchSubs, Substitutions filterSubs) { + // law fih free variable mesh bound le constant pattern heya open +// int switchCardn = switchSubs.cardinality(); +// int filterCardn = filterSubs.cardinality(); +// return switchCardn > 0 && filterCardn < switchCardn; + // if (!this.getIdentifier().equalsIgnoreCase("patternnode")) // return false; // VariableNode node = (VariableNode) this; // VariableSet variables = node.getFreeVariables(); -// for (Variable currentVariable: variables) { -// Node termNode = sub.term(currentVariable); +// for (Variable currentVariable : variables) { +// Node termNode = filterSubs.term(currentVariable); // if (termNode == null || (!termNode.getIdentifier().equalsIgnoreCase("basenode"))) // return true; // } - return false; +// return false; + return !areAllVariablesConstants(switchSubs, filterSubs); + } + + public boolean areAllVariablesConstants(Substitutions switchSubs, Substitutions filterSubs) { + int switchCardn = switchSubs.cardinality(); + int filterCardn = filterSubs.cardinality(); + return switchCardn > 0 && filterCardn == switchCardn; } Context fake() { diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index beb4baf7..3882bd14 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -18,6 +18,7 @@ import sneps.network.classes.term.Term; import java.util.Hashtable; +import java.util.Iterator; import java.util.List; import java.util.Set; @@ -39,7 +40,6 @@ public class PropositionNode extends Node implements Serializable { private Support basicSupport; - protected ChannelSet outgoingChannels; protected ChannelSet incomingChannels; protected ReportSet knownInstances; @@ -185,7 +185,10 @@ public void processSingleRequestsChannel(Channel currentChannel) sentAtLeastOne |= sendReport(currentReport, currentChannel); } // TODO Akram: passed the filter subs to isWhQuest, is that correct? - if (!sentAtLeastOne || isWhQuestion(currentChannel.getFilter().getSubstitutions())) + // TODO Youssef: passed the switch subs to isWhQuest, is that also correct? + Substitutions switchSubs = currentChannel.getSwitch().getSubstitutions(); + Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); + if (!sentAtLeastOne || isWhQuestion(switchSubs, filterSubs)) if (!alreadyWorking(currentChannel)) { getNodesToSendRequests(ChannelTypes.RuleCons, currentChannel.getContextName(), currentChannel.getFilter().getSubstitutions()); @@ -225,6 +228,7 @@ public void processRequests() { public void receiveRequest(Channel channel) { outgoingChannels.addChannel(channel); Runner.addToLowQueue(this); + channel.setRequestProcessed(true); } /*** @@ -275,7 +279,24 @@ private void getNodesToSendRequests(ChannelTypes type, String currentContextName } + /*** + * Method checking if a similar more generic request is being processed and + * awaits a report in order not to re-send the same request + * + * @param channel current channel handling the current request + * @return boolean represents whether a more generic request has been received + */ public boolean alreadyWorking(Channel channel) { + ChannelSet filteredChannelsSet = incomingChannels.getFilteredRequestChannels(true); + Substitutions currentChannelFilterSubs = channel.getFilter().getSubstitutions(); + for (Channel incomingChannel : filteredChannelsSet) { + if (incomingChannel != channel) { + Substitutions processedChannelFilterSubs = incomingChannel.getFilter().getSubstitutions(); + if (processedChannelFilterSubs.isSubSet(currentChannelFilterSubs)) { + return true; + } + } + } return false; } diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index ffdf9935..17f0aa40 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -16,6 +16,7 @@ import sneps.network.classes.setClasses.ReportSet; import sneps.network.classes.setClasses.RuleUseInfoSet; import sneps.network.classes.setClasses.VariableSet; +import sneps.network.classes.term.Closed; import sneps.network.classes.term.Molecular; import sneps.network.classes.term.Open; import sneps.network.classes.term.Term; @@ -32,6 +33,7 @@ import sneps.snip.classes.RuleUseInfo; import sneps.snip.classes.SIndex; import sneps.snip.matching.LinearSubstitutions; +import sneps.snip.matching.Substitutions; public abstract class RuleNode extends PropositionNode implements Serializable { @@ -278,44 +280,56 @@ public void processRequests() { public void processSingleRequestsChannel(Channel currentChannel) throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { if (currentChannel instanceof RuleToConsequentChannel) { + boolean closedTypeTerm = term instanceof Closed; VariableSet variablesList = ((Open) this.term).getFreeVariables(); - if (variablesList.isEmpty()) { - // Proposition semanticType = (Proposition) this.getSemantic(); - // TODO change according to snebr + Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); + Substitutions switchSubs = currentChannel.getSwitch().getSubstitutions(); + // law closed type yb2a awel case, law open type yb2a two other cases, + // areVariablesBound check law el filter fadi wala la2: fadi case 2, la2 case 3 + if (closedTypeTerm) { String currentContextName = currentChannel.getContextName(); Context currentContext = Controller.getContextByName(currentContextName); - if (assertedInContext(currentContext)) { // this.semanticType.isAsserted(currentContext) + if (assertedInContext(currentContext)) { NodeSet antecedentNodeSet = getDownAntNodeSet(); NodeSet toBeSentTo = new NodeSet(); for (Node currentNode : antecedentNodeSet) { if (currentNode == currentChannel.getRequester()) continue; - // TODO Akram: if not yet been requested for this // instance // TODO Youssef: added requestServing to monitor requests status over each // channel established - if (!currentChannel.isRequestProcessed()) { +// Substitutions currentChannelFilterSubs = currentChannel.getFilter().getSubstitutions(); +// currentChannel.processedGeneralizedRequest(currentChannelFilterSubs) + if (!alreadyWorking(currentChannel)) { toBeSentTo.addNode(currentNode); } } sendRequests(toBeSentTo, currentChannel.getFilter().getSubstitutions(), currentChannel.getContextName(), ChannelTypes.RuleAnt); + return; + } + } else if (areAllVariablesConstants(switchSubs, filterSubs)) { + // TODO Akram: there are free variables but each is bound; check filter beta3 el + // channel law empty + if (true) { + return; } - } else if (variablesList.areVariablesBound()) { - // TODO Akram: there are free variables but each is bound + } else { - // TODO Akram: there is a free variable not bound + // TODO Akram: there is a free variable not bound; check filter + if (true) { + return; + } } - } else { - try { - super.processSingleRequestsChannel(currentChannel); - } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException | DuplicatePropositionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } } + try { + super.processSingleRequestsChannel(currentChannel); + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException | DuplicatePropositionException e) { + e.printStackTrace(); + } + } @Override diff --git a/src/sneps/network/classes/Semantic.java b/src/sneps/network/classes/Semantic.java index 3e56d4f9..09ac06e3 100644 --- a/src/sneps/network/classes/Semantic.java +++ b/src/sneps/network/classes/Semantic.java @@ -23,11 +23,6 @@ public String getSemanticType() { return semanticType; } - public boolean isAsserted(Object contextByName) { - // TODO Auto-generated method stub - return false; - } - public static void createDefaultSemantics() { act = SemanticHierarchy.createSemanticType("Act"); proposition = SemanticHierarchy.createSemanticType("Proposition"); diff --git a/src/sneps/network/classes/setClasses/ChannelSet.java b/src/sneps/network/classes/setClasses/ChannelSet.java index 7bcddced..5eaa0fc6 100644 --- a/src/sneps/network/classes/setClasses/ChannelSet.java +++ b/src/sneps/network/classes/setClasses/ChannelSet.java @@ -23,4 +23,20 @@ public void addChannel(Channel newChannel) { channels.add(newChannel); } + /*** + * 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(); + for (Channel channel : processedRequestsChannels) { + if (channel.isRequestProcessed() == processedRequest) + processedRequestsChannels.addChannel(channel); + } + return processedRequestsChannels; + } + } diff --git a/src/sneps/network/classes/setClasses/VariableSet.java b/src/sneps/network/classes/setClasses/VariableSet.java index 21f87e14..ac1c6799 100644 --- a/src/sneps/network/classes/setClasses/VariableSet.java +++ b/src/sneps/network/classes/setClasses/VariableSet.java @@ -5,6 +5,9 @@ import java.util.Vector; import sneps.network.classes.term.Variable; +import sneps.snip.Filter; +import sneps.snip.channels.Channel; +import sneps.snip.matching.Substitutions; public class VariableSet implements Iterable, Serializable { protected Vector variables; @@ -40,14 +43,4 @@ public boolean isEmpty() { return variables.isEmpty(); } - /*** - * Method to iterate over all variables in the Vector to check for - * their bound status - * - * @return boolean expressing no none-bound free variables - */ - public boolean areVariablesBound() { - // TODO Youssef - return false; - } } diff --git a/src/sneps/snip/Switch.java b/src/sneps/snip/Switch.java index 368bbe16..f7ac2e66 100644 --- a/src/sneps/snip/Switch.java +++ b/src/sneps/snip/Switch.java @@ -6,26 +6,34 @@ import sneps.snip.matching.Substitutions; public class Switch { - private Substitutions substitution; + private Substitutions substitutions; public Switch() { - this.substitution = new LinearSubstitutions(); + this.substitutions = new LinearSubstitutions(); + } + + public Substitutions getSubstitutions() { + return substitutions; + } + + public void setSubstitutions(Substitutions substitutions) { + this.substitutions = substitutions; } public Switch(Substitutions substitution) { - this.substitution = substitution; + this.substitutions = substitution; } public void switchReport(Report r) { - for (int i = 0; i < this.substitution.cardinality(); i++) { - Binding b = r.getSubstitutions().getBindingByVariable(this.substitution.getBinding(i).getVariable()); - System.out.println(this.substitution.getBinding(i).getVariable()); + for (int i = 0; i < this.substitutions.cardinality(); i++) { + Binding b = r.getSubstitutions().getBindingByVariable(this.substitutions.getBinding(i).getVariable()); + System.out.println(this.substitutions.getBinding(i).getVariable()); System.out.println("i: " + i + " binding: " + b); if (b != null) { - b.setVariable((VariableNode) this.substitution.getBinding(i).getNode()); + b.setVariable((VariableNode) this.substitutions.getBinding(i).getNode()); } else { - System.out.println("there u go " + this.substitution.getBinding(i)); - r.getSubstitutions().putIn(this.substitution.getBinding(i)); + System.out.println("there u go " + this.substitutions.getBinding(i)); + r.getSubstitutions().putIn(this.substitutions.getBinding(i)); System.out.println("size now " + r.getSubstitutions().cardinality()); } } @@ -36,6 +44,6 @@ public void switchReport(Report r) { } public String toString() { - return substitution.toString(); + return substitutions.toString(); } } diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index 8a6c5184..e48a2c1f 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -1,6 +1,8 @@ package sneps.snip.channels; import sneps.network.Node; +import sneps.network.PropositionNode; +import sneps.network.classes.setClasses.ChannelSet; import sneps.network.classes.setClasses.ReportSet; import sneps.snip.Filter; import sneps.snip.Report; @@ -102,4 +104,19 @@ public void setValve(boolean valve) { public void clearReportsBuffer() { reportsBuffer.clear(); } + + public boolean processedGeneralizedRequest(Substitutions currentChannelFilterSubs) { + ChannelSet filteredChannelsSet = ((PropositionNode) requester).getIncomingChannels() + .getFilteredRequestChannels(true); + for (Channel incomingChannel : filteredChannelsSet) { + if (incomingChannel != this) { + Substitutions processedChannelFilterSubs = incomingChannel.getFilter().getSubstitutions(); + if (processedChannelFilterSubs.isSubSet(currentChannelFilterSubs)) { + return true; + } + } + } + return false; + + } } diff --git a/src/sneps/snip/matching/Binding.java b/src/sneps/snip/matching/Binding.java index c1ceadec..07a89aba 100644 --- a/src/sneps/snip/matching/Binding.java +++ b/src/sneps/snip/matching/Binding.java @@ -3,74 +3,73 @@ import sneps.network.Node; import sneps.network.VariableNode; -public class Binding{ +public class Binding { private Node node; - private VariableNode variable; - - /** - *Creates new binding from variable and node - *@param node - *@param variablear - */ - public Binding(VariableNode variable,Node node) - { - this.node=node; - this.variable=variable; - } - - /** - *returns the variable of the binding - *@return variable - */ - public VariableNode getVariable() - { - return variable; - } - /** - *returns the node of the binding - *@return node - */ - public Node getNode() - { - return node; - } - - /** - *Check if binding is equal to this binding - *@param binding Binding - *@return true if equal false otherwise - */ - public boolean isEqual(Binding binding) - { - if(this.getNode() == binding.getNode() && - this.getVariable() == binding.getVariable()) - return true; - return false; - } - - /** - *Set the value of the variable of the binding with m - *@param m the new variable - */ - public void setVariable(VariableNode m) - { - variable=m; - } - - /** - *Set the value of the node of the binding with m - *@param m the new node - */ - public void setNode(Node m) - { - node=m; - } - - /** - * Create a copy of this binding - */ - public Binding clone() - { - return new Binding(variable,node); - } + private VariableNode variable; + + /** + * Creates new binding from variable and node + * + * @param node + * @param variablear + */ + public Binding(VariableNode variable, Node node) { + this.node = node; + this.variable = variable; + } + + /** + * returns the variable of the binding + * + * @return variable + */ + public VariableNode getVariable() { + return variable; + } + + /** + * returns the node of the binding + * + * @return node + */ + public Node getNode() { + return node; + } + + /** + * Check if binding is equal to this binding + * + * @param binding Binding + * @return true if equal false otherwise + */ + public boolean isEqual(Binding binding) { + if (this.getNode() == binding.getNode() && this.getVariable() == binding.getVariable()) + return true; + return false; + } + + /** + * Set the value of the variable of the binding with m + * + * @param m the new variable + */ + public void setVariable(VariableNode m) { + variable = m; + } + + /** + * Set the value of the node of the binding with m + * + * @param m the new node + */ + public void setNode(Node m) { + node = m; + } + + /** + * Create a copy of this binding + */ + public Binding clone() { + return new Binding(variable, node); + } } diff --git a/src/sneps/snip/matching/LinearSubstitutions.java b/src/sneps/snip/matching/LinearSubstitutions.java index bd44c912..a93f1478 100644 --- a/src/sneps/snip/matching/LinearSubstitutions.java +++ b/src/sneps/snip/matching/LinearSubstitutions.java @@ -449,4 +449,12 @@ public void insertOrUpdate(Binding mb) { } + /*** + * Method to iterate over all variables in the Vector to check for + * their bound status + */ + public boolean areVariablesBound() { + return isNew(); + } + } \ No newline at end of file diff --git a/src/sneps/snip/matching/Match.java b/src/sneps/snip/matching/Match.java index a8cabc27..77b7df4d 100644 --- a/src/sneps/snip/matching/Match.java +++ b/src/sneps/snip/matching/Match.java @@ -3,7 +3,9 @@ import sneps.network.Node; public class Match { - private Substitutions filterSubs; + private Substitutions filterSubs; // whquestion atleastone free not bound + // no filter on match channel + // target (switch el heya variables to variables) <- source (filter el heya variables to constants) private Substitutions switchSubs; private Node node; private int matchType; diff --git a/src/sneps/snip/matching/Substitutions.java b/src/sneps/snip/matching/Substitutions.java index 2407024a..adb59781 100644 --- a/src/sneps/snip/matching/Substitutions.java +++ b/src/sneps/snip/matching/Substitutions.java @@ -65,4 +65,6 @@ public interface Substitutions { public void insertOrUpdate(Binding mb); + public boolean areVariablesBound(); + } From 51ae7a46ce787c33828a62b0f60fbde0bb02e1dd Mon Sep 17 00:00:00 2001 From: Youssef Date: Sat, 13 Apr 2019 19:26:16 +0200 Subject: [PATCH 05/22] migrate alreadyWorking to NodeSet --- src/sneps/network/Node.java | 26 ++-- src/sneps/network/PropositionNode.java | 122 +++++++++--------- src/sneps/network/RuleNode.java | 65 +++++----- .../classes/setClasses/ChannelSet.java | 2 +- .../network/classes/setClasses/NodeSet.java | 31 +++++ src/sneps/snip/InferenceTypes.java | 5 + src/sneps/snip/Report.java | 5 + .../channels/AntecedentToRuleChannel.java | 6 +- src/sneps/snip/channels/Channel.java | 15 ++- src/sneps/snip/channels/MatchChannel.java | 15 ++- .../channels/RuleToConsequentChannel.java | 5 +- src/sneps/snip/rules/OrNode.java | 2 +- 12 files changed, 184 insertions(+), 115 deletions(-) create mode 100644 src/sneps/snip/InferenceTypes.java diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java index cea9f5be..e657d017 100644 --- a/src/sneps/network/Node.java +++ b/src/sneps/network/Node.java @@ -9,6 +9,7 @@ import sneps.network.cables.UpCableSet; import sneps.network.classes.Semantic; 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.network.classes.setClasses.NodeSet; @@ -199,23 +200,14 @@ public NodeSet getDominatingRules() { return ret; } - public boolean isWhQuestion(Substitutions switchSubs, Substitutions filterSubs) { - // law fih free variable mesh bound le constant pattern heya open -// int switchCardn = switchSubs.cardinality(); -// int filterCardn = filterSubs.cardinality(); -// return switchCardn > 0 && filterCardn < switchCardn; - -// if (!this.getIdentifier().equalsIgnoreCase("patternnode")) -// return false; -// VariableNode node = (VariableNode) this; -// VariableSet variables = node.getFreeVariables(); -// for (Variable currentVariable : variables) { -// Node termNode = filterSubs.term(currentVariable); -// if (termNode == null || (!termNode.getIdentifier().equalsIgnoreCase("basenode"))) -// return true; -// } -// return false; - return !areAllVariablesConstants(switchSubs, filterSubs); + public boolean isWhQuestion(Substitutions filterSubs) { + if (!(this instanceof VariableNode)) + return false; + VariableNode node = (VariableNode) this; + VariableSet variables = node.getFreeVariables(); + int variablesCardn = variables.size(); + int filterCardn = filterSubs.cardinality(); + return filterCardn < variablesCardn; } public boolean areAllVariablesConstants(Substitutions switchSubs, Substitutions filterSubs) { diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 3882bd14..48ac13f7 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -25,6 +25,7 @@ import sneps.snebr.Context; import sneps.snebr.Controller; import sneps.snebr.Support; +import sneps.snip.InferenceTypes; import sneps.snip.Pair; import sneps.snip.Report; import sneps.snip.Runner; @@ -66,14 +67,14 @@ public PropositionNode(Term trm) { */ public void broadcastReport(Report report) { for (Channel outChannel : outgoingChannels) { - if (outChannel.addReport(report)) { + if (outChannel.testReportToAdd(report)) { // System.out.println("SENDING REPORT " + this); } } } public boolean sendReport(Report report, Channel channel) { - if (channel.addReport(report)) { + if (channel.testReportToAdd(report)) { // System.out.println("SENDING REPORT " + this); return true; } @@ -89,61 +90,84 @@ public boolean sendReport(Report report, Channel channel) { * @param switchSubs mapped substitutions from origin node * @param filterSubs constraints substitutions for a specific request * @param contextId context name used + * @param inferenceType inference type used for this process * @return the established type based channel */ - private Channel establishChannel(ChannelTypes type, Object currentElement, Substitutions switchSubs, - Substitutions filterSubs, String contextId) { + protected Channel establishChannel(ChannelTypes type, Object currentElement, Substitutions switchSubs, + Substitutions filterSubs, String contextId, InferenceTypes inferenceType, int matchType) { boolean matchTypeEstablishing = currentElement instanceof Match; Node evaluatedReporter = matchTypeEstablishing ? ((Match) currentElement).getNode() : (Node) currentElement; Substitutions switchLinearSubs = switchSubs == null ? new LinearSubstitutions() : switchSubs; Channel newChannel; switch (type) { case MATCHED: - newChannel = new MatchChannel(switchLinearSubs, filterSubs, contextId, this, evaluatedReporter, true); + newChannel = new MatchChannel(switchLinearSubs, filterSubs, contextId, this, evaluatedReporter, true, + inferenceType, matchType); break; case RuleAnt: newChannel = new AntecedentToRuleChannel(switchLinearSubs, filterSubs, contextId, this, evaluatedReporter, - true); + true, inferenceType); default: newChannel = new RuleToConsequentChannel(switchLinearSubs, filterSubs, contextId, this, evaluatedReporter, - true); + true, inferenceType); } return newChannel; } - public void sendRequests(List list, String contextId, ChannelTypes channelType) { + public void sendRequests(List list, String contextId, ChannelTypes channelType, + InferenceTypes inferenceType) { for (Match currentMatch : list) { Substitutions switchSubs = currentMatch.getSwitchSubs(); Substitutions filterSubs = currentMatch.getFilterSubs(); - Channel newChannel = establishChannel(channelType, currentMatch, switchSubs, filterSubs, contextId); + int matchType = currentMatch.getMatchType(); + Channel newChannel = establishChannel(channelType, currentMatch, switchSubs, filterSubs, contextId, + inferenceType, matchType); incomingChannels.addChannel(newChannel); currentMatch.getNode().receiveRequest(newChannel); } } - public void sendRequests(NodeSet ns, Substitutions filterSubs, String contextID, ChannelTypes channelType) { + public void sendRequests(NodeSet ns, Substitutions filterSubs, String contextID, ChannelTypes channelType, + InferenceTypes inferenceType) { for (Node sentTo : ns) { - Channel newChannel = establishChannel(channelType, sentTo, null, filterSubs, contextID); + Channel newChannel = establishChannel(channelType, sentTo, null, filterSubs, contextID, inferenceType, -1); incomingChannels.addChannel(newChannel); sentTo.receiveRequest(newChannel); } } + /*** + * Report handling in Non-Rule proposition nodes. + * + * @param currentChannel + */ public void processSingleReportsChannel(Channel currentChannel) { + ReportSet reports = currentChannel.getReportsBuffer(); for (Report currentReport : reports) { - Report alteredReport = new Report(currentReport.getSubstitutions(), currentReport.getSupports(), - currentReport.getSign(), currentReport.getContextName()); - if (knownInstances.contains(alteredReport)) { - continue; + Substitutions reportSubs = currentReport.getSubstitutions(); + Set reportSupportSet = currentReport.getSupports(); + boolean reportSign = currentReport.isPositive(); + String reportContextName = currentReport.getContextName(); + boolean toBeSentFlag = true; + if (currentChannel instanceof MatchChannel) { + int channelMatchType = ((MatchChannel) currentChannel).getMatchType(); + reportSign = channelMatchType == 2 ? !reportSign : reportSign; + toBeSentFlag = (channelMatchType != 1) || reportSign; } - for (Channel outChannel : outgoingChannels) - outChannel.addReport(alteredReport); + Report alteredReport = new Report(reportSubs, reportSupportSet, reportSign, reportContextName); + if (knownInstances.contains(alteredReport)) + continue; + if (toBeSentFlag) + broadcastReport(alteredReport); currentChannel.clearReportsBuffer(); } currentChannel.clearReportsBuffer(); } + // PROCESS REPORT : 3adi -> , forward + // -> same as 3adi , plus matching to send and get the nodes el howa lihom + // antecedents we send reports public void processReports() { for (Channel inChannel : incomingChannels) @@ -168,33 +192,28 @@ public void processSingleRequestsChannel(Channel currentChannel) Context desiredContext = Controller.getContextByName(currentContextName); if (assertedInContext(desiredContext)) { // TODO change the subs to hashsubs - /** - * Sends an instance of this report - */ Set support = new HashSet(); support.add(new Support(instanceNodeId)); Report reply = new Report(new LinearSubstitutions(), support, true, currentChannel.getContextName()); knownInstances.addReport(reply); broadcastReport(reply); } else { - /** - * Sends any previously known instances - */ boolean sentAtLeastOne = false; for (Report currentReport : knownInstances) { sentAtLeastOne |= sendReport(currentReport, currentChannel); } - // TODO Akram: passed the filter subs to isWhQuest, is that correct? - // TODO Youssef: passed the switch subs to isWhQuest, is that also correct? Substitutions switchSubs = currentChannel.getSwitch().getSubstitutions(); Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); - if (!sentAtLeastOne || isWhQuestion(switchSubs, filterSubs)) - if (!alreadyWorking(currentChannel)) { - getNodesToSendRequests(ChannelTypes.RuleCons, currentChannel.getContextName(), - currentChannel.getFilter().getSubstitutions()); - if (!(currentChannel instanceof MatchChannel)) - getNodesToSendRequests(ChannelTypes.MATCHED, currentChannel.getContextName(), null); - } + if (!sentAtLeastOne || isWhQuestion(filterSubs)) { + NodeSet dominatingRules = getDominatingRules(); + NodeSet workingNodes = dominatingRules.alreadyWorking(currentChannel, false); + NodeSet toBeSentTo = dominatingRules.difference(workingNodes); + sendRequests(toBeSentTo, new LinearSubstitutions(), currentContextName, ChannelTypes.RuleAnt, + currentChannel.getInferenceType()); + if (!(currentChannel instanceof MatchChannel)) // was in !alreadyWorking if condition + getNodesToSendRequests(ChannelTypes.MATCHED, currentChannel.getContextName(), null, + currentChannel.getInferenceType()); + } } } @@ -243,11 +262,15 @@ public void receiveReports(Channel channel) { public void deduce() { Runner.initiate(); String currentContextName = Controller.getCurrentContextName(); - getNodesToSendRequests(ChannelTypes.RuleCons, currentContextName, null); - getNodesToSendRequests(ChannelTypes.MATCHED, currentContextName, null); + getNodesToSendRequests(ChannelTypes.RuleCons, currentContextName, null, InferenceTypes.BACKWARD); + getNodesToSendRequests(ChannelTypes.MATCHED, currentContextName, null, InferenceTypes.BACKWARD); Runner.run(); // what to return here ? } + public void add() { + + } + /*** * Method handling all types of Nodes retrieval and sending different type-based * requests to each Node Type @@ -255,20 +278,22 @@ public void deduce() { * @param type type of channel being addressed * @param currentContextName context name used * @param substitutions channel substitutions applied over the channel + * @param inferenceType inference type used for this process */ - private void getNodesToSendRequests(ChannelTypes type, String currentContextName, Substitutions substitutions) { + protected void getNodesToSendRequests(ChannelTypes channelType, String currentContextName, + Substitutions substitutions, InferenceTypes inferenceType) { try { - switch (type) { + switch (channelType) { case MATCHED: List matchesReturned = Matcher.match(this); if (matchesReturned != null) - sendRequests(matchesReturned, currentContextName, type); + sendRequests(matchesReturned, currentContextName, channelType, inferenceType); break; case RuleCons: NodeSet dominatingRules = getDominatingRules(); // TODO Youssef: check if passing a new LinearSubstitutions is correct Substitutions linearSubs = substitutions == null ? new LinearSubstitutions() : substitutions; - sendRequests(dominatingRules, linearSubs, currentContextName, type); + sendRequests(dominatingRules, linearSubs, currentContextName, channelType, inferenceType); break; default: break; @@ -279,27 +304,6 @@ private void getNodesToSendRequests(ChannelTypes type, String currentContextName } - /*** - * Method checking if a similar more generic request is being processed and - * awaits a report in order not to re-send the same request - * - * @param channel current channel handling the current request - * @return boolean represents whether a more generic request has been received - */ - public boolean alreadyWorking(Channel channel) { - ChannelSet filteredChannelsSet = incomingChannels.getFilteredRequestChannels(true); - Substitutions currentChannelFilterSubs = channel.getFilter().getSubstitutions(); - for (Channel incomingChannel : filteredChannelsSet) { - if (incomingChannel != channel) { - Substitutions processedChannelFilterSubs = incomingChannel.getFilter().getSubstitutions(); - if (processedChannelFilterSubs.isSubSet(currentChannelFilterSubs)) { - return true; - } - } - } - return false; - } - public Support getBasicSupport() { return basicSupport; } diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index 17f0aa40..c7431acf 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -281,58 +281,65 @@ public void processSingleRequestsChannel(Channel currentChannel) throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { if (currentChannel instanceof RuleToConsequentChannel) { boolean closedTypeTerm = term instanceof Closed; - VariableSet variablesList = ((Open) this.term).getFreeVariables(); + String currentContextName = currentChannel.getContextName(); + Context currentContext = Controller.getContextByName(currentContextName); +// VariableSet variablesList = ((Open) this.term).getFreeVariables(); Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); Substitutions switchSubs = currentChannel.getSwitch().getSubstitutions(); - // law closed type yb2a awel case, law open type yb2a two other cases, - // areVariablesBound check law el filter fadi wala la2: fadi case 2, la2 case 3 if (closedTypeTerm) { - String currentContextName = currentChannel.getContextName(); - Context currentContext = Controller.getContextByName(currentContextName); if (assertedInContext(currentContext)) { NodeSet antecedentNodeSet = getDownAntNodeSet(); - NodeSet toBeSentTo = new NodeSet(); - for (Node currentNode : antecedentNodeSet) { + + /* + * fel rule node haguib el incoming channels we hastore ay haga ba3atlha request + * el filter beta3o subset lel request el ana baservo, we hashil el list dih men + * el antecdents + */ + for (Node currentNode : antecedentNodeSet /* mengheir el prementioned set */) { + /* only needed for the andor & thresh */ if (currentNode == currentChannel.getRequester()) continue; // TODO Akram: if not yet been requested for this // instance // TODO Youssef: added requestServing to monitor requests status over each // channel established -// Substitutions currentChannelFilterSubs = currentChannel.getFilter().getSubstitutions(); -// currentChannel.processedGeneralizedRequest(currentChannelFilterSubs) - if (!alreadyWorking(currentChannel)) { - toBeSentTo.addNode(currentNode); - } + // check incoming channels coming from current node law filter subsumes the + // filter of currentchannel + } + NodeSet workingNodes = antecedentNodeSet.alreadyWorking(currentChannel, true); + NodeSet toBeSentTo = antecedentNodeSet.difference(workingNodes); sendRequests(toBeSentTo, currentChannel.getFilter().getSubstitutions(), - currentChannel.getContextName(), ChannelTypes.RuleAnt); + currentChannel.getContextName(), ChannelTypes.RuleAnt, currentChannel.getInferenceType()); return; } - } else if (areAllVariablesConstants(switchSubs, filterSubs)) { + } else { // TODO Akram: there are free variables but each is bound; check filter beta3 el // channel law empty - if (true) { - return; - } - - } else { - // TODO Akram: there is a free variable not bound; check filter - if (true) { - return; + ReportSet knownReportSet = knownInstances; + for (Report report : knownReportSet) { + Substitutions reportSubstitutions = report.getSubstitutions(); + if (filterSubs.isEqual(reportSubstitutions)) { + getNodesToSendRequests(ChannelTypes.RuleCons, currentContextName, null, + currentChannel.getInferenceType()); + if (areAllVariablesConstants(switchSubs, filterSubs)) + return; + else + break; + } } } - - } - try { - super.processSingleRequestsChannel(currentChannel); - } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException | DuplicatePropositionException e) { - e.printStackTrace(); } + super.processSingleRequestsChannel(currentChannel); } - @Override + // PROCESS REPORT : 3adi -> outgoing channels node we ab3at accordingly, forard + // -> outgoing channels and the rest of the consequents kolohom we ab3at 3adi + + /*** + * Report handling in Rule proposition nodes. + */ public void processReports() { for (Channel currentChannel : incomingChannels) { ReportSet channelReports = currentChannel.getReportsBuffer(); diff --git a/src/sneps/network/classes/setClasses/ChannelSet.java b/src/sneps/network/classes/setClasses/ChannelSet.java index 5eaa0fc6..a381b188 100644 --- a/src/sneps/network/classes/setClasses/ChannelSet.java +++ b/src/sneps/network/classes/setClasses/ChannelSet.java @@ -32,7 +32,7 @@ public void addChannel(Channel newChannel) { */ public ChannelSet getFilteredRequestChannels(boolean processedRequest) { ChannelSet processedRequestsChannels = new ChannelSet(); - for (Channel channel : processedRequestsChannels) { + for (Channel channel : channels) { if (channel.isRequestProcessed() == processedRequest) processedRequestsChannels.addChannel(channel); } diff --git a/src/sneps/network/classes/setClasses/NodeSet.java b/src/sneps/network/classes/setClasses/NodeSet.java index 2da30f39..cf8e337f 100644 --- a/src/sneps/network/classes/setClasses/NodeSet.java +++ b/src/sneps/network/classes/setClasses/NodeSet.java @@ -1,10 +1,14 @@ package sneps.network.classes.setClasses; import java.io.Serializable; +import java.util.Arrays; import java.util.Iterator; import java.util.Vector; import sneps.network.Node; +import sneps.network.PropositionNode; +import sneps.snip.channels.Channel; +import sneps.snip.matching.Substitutions; public class NodeSet implements Iterable, Serializable { private Vector nodes; @@ -48,6 +52,33 @@ public boolean contains(Node node) { return this.nodes.contains(node); } + /*** + * Method checking if a similar more generic request is being processed and + * awaits a report in order not to re-send the same request + * + * @param node set on which we will check existing request + * @param channel current channel handling the current request + * @return boolean represents whether a more generic request has been received + */ + public NodeSet alreadyWorking(Channel channel, boolean ruleType) { + NodeSet toSentTo = new NodeSet(); + for (Node sourceNode : nodes) + if (sourceNode instanceof PropositionNode) { + Substitutions currentChannelFilterSubs = channel.getFilter().getSubstitutions(); + ChannelSet incomingChannels = ((PropositionNode) sourceNode).getIncomingChannels(); + ChannelSet filteredChannelsSet = incomingChannels.getFilteredRequestChannels(true); + boolean conditionMet = true; + for (Channel incomingChannel : filteredChannelsSet) { + Substitutions processedChannelFilterSubs = incomingChannel.getFilter().getSubstitutions(); + conditionMet |= (ruleType ? sourceNode != incomingChannel.getRequester() : true) + && !processedChannelFilterSubs.isSubSet(currentChannelFilterSubs); + } + if (conditionMet) + toSentTo.addNode(sourceNode); + } + return toSentTo; + } + public NodeSet Union(NodeSet ns) { NodeSet unionSet = new NodeSet(); unionSet.addAll(this); 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 41124609..0df5ecba 100644 --- a/src/sneps/snip/Report.java +++ b/src/sneps/snip/Report.java @@ -5,6 +5,7 @@ import sneps.snebr.Support; import sneps.snip.matching.Substitutions; +/*add type of inference*/ public class Report { private Substitutions substitution; private Set supports; @@ -45,6 +46,10 @@ public boolean isNegative() { return !sign; } + public void toggleSign() { + this.sign = !this.sign; + } + public String toString() { return "ContextID : " + contextName + "\nSign: " + sign + "\nSubstitution: " + substitution + "\nSupport: " + supports; diff --git a/src/sneps/snip/channels/AntecedentToRuleChannel.java b/src/sneps/snip/channels/AntecedentToRuleChannel.java index c7332d7f..d32583b5 100644 --- a/src/sneps/snip/channels/AntecedentToRuleChannel.java +++ b/src/sneps/snip/channels/AntecedentToRuleChannel.java @@ -1,11 +1,13 @@ package sneps.snip.channels; import sneps.network.Node; +import sneps.snip.InferenceTypes; import sneps.snip.matching.Substitutions; public class AntecedentToRuleChannel extends Channel { - public AntecedentToRuleChannel(Substitutions switchSubstitution, Substitutions filterSubstitutions, String contextID, Node requester, Node reporter, boolean v) { - super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v); + public AntecedentToRuleChannel(Substitutions switchSubstitution, Substitutions filterSubstitutions, + String contextID, Node requester, Node reporter, boolean v, InferenceTypes inferenceType) { + super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v, inferenceType); } } diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index e48a2c1f..426e1a10 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -5,6 +5,7 @@ import sneps.network.classes.setClasses.ChannelSet; import sneps.network.classes.setClasses.ReportSet; import sneps.snip.Filter; +import sneps.snip.InferenceTypes; import sneps.snip.Report; import sneps.snip.Runner; import sneps.snip.Switch; @@ -21,6 +22,7 @@ public abstract class Channel { private ReportSet reportsBuffer; private boolean requestProcessed = false; private boolean reportProcessed = false; + private InferenceTypes inferenceType; public Channel() { filter = new Filter(); @@ -29,7 +31,7 @@ public Channel() { } public Channel(Substitutions switcherSubstitution, Substitutions filterSubstitutions, String contextID, - Node requester, Node reporter, boolean v) { + Node requester, Node reporter, boolean v, InferenceTypes inferenceType) { this.filter = new Filter(filterSubstitutions); this.switcher = new Switch(switcherSubstitution); this.contextName = contextID; @@ -38,9 +40,10 @@ public Channel(Substitutions switcherSubstitution, Substitutions filterSubstitut this.valve = v; this.reporter = reporter; reportsBuffer = new ReportSet(); + this.inferenceType = inferenceType; } - public boolean addReport(Report report) { + public boolean testReportToAdd(Report report) { boolean passTest = filter.canPass(report); System.out.println("Can pass " + passTest); if (passTest && contextName.equals(report.getContextName())) { @@ -97,6 +100,14 @@ public void setReportProcessed(boolean reportProcessed) { this.reportProcessed = reportProcessed; } + public InferenceTypes getInferenceType() { + return inferenceType; + } + + public void setInferenceType(InferenceTypes inferenceType) { + this.inferenceType = inferenceType; + } + public void setValve(boolean valve) { this.valve = valve; } diff --git a/src/sneps/snip/channels/MatchChannel.java b/src/sneps/snip/channels/MatchChannel.java index 3a4658d4..ea8c6ba9 100644 --- a/src/sneps/snip/channels/MatchChannel.java +++ b/src/sneps/snip/channels/MatchChannel.java @@ -1,17 +1,28 @@ package sneps.snip.channels; import sneps.network.Node; +import sneps.snip.InferenceTypes; import sneps.snip.matching.Substitutions; public class MatchChannel extends Channel { + private int matchType; public MatchChannel() { super(); } public MatchChannel(Substitutions switchSubstitution, Substitutions filterSubstitutions, String contextID, - Node requester, Node reporter, boolean v) { - super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v); + Node requester, Node reporter, boolean v, InferenceTypes inferenceType, int matchType) { + super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v, inferenceType); + this.setMatchType(matchType); + } + + public int getMatchType() { + return matchType; + } + + public void setMatchType(int matchType) { + this.matchType = matchType; } } diff --git a/src/sneps/snip/channels/RuleToConsequentChannel.java b/src/sneps/snip/channels/RuleToConsequentChannel.java index f3bf0fed..46f242a9 100644 --- a/src/sneps/snip/channels/RuleToConsequentChannel.java +++ b/src/sneps/snip/channels/RuleToConsequentChannel.java @@ -1,13 +1,14 @@ package sneps.snip.channels; import sneps.network.Node; +import sneps.snip.InferenceTypes; import sneps.snip.matching.Substitutions; public class RuleToConsequentChannel extends Channel { public RuleToConsequentChannel(Substitutions switchSubstitution, Substitutions filterSubstitutions, - String contextID, Node requester, Node reporter, boolean v) { - super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v); + String contextID, Node requester, Node reporter, boolean v, InferenceTypes inferenceType) { + super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v, inferenceType); } } diff --git a/src/sneps/snip/rules/OrNode.java b/src/sneps/snip/rules/OrNode.java index 12cf08a2..91b1b4c4 100644 --- a/src/sneps/snip/rules/OrNode.java +++ b/src/sneps/snip/rules/OrNode.java @@ -35,7 +35,7 @@ public void applyRuleHandler(Report report, Node node) { Report reply = new Report(report.getSubstitutions(), sup, true, report.getContextName()); for (Channel outChannel : outgoingChannels) - outChannel.addReport(reply); + outChannel.testReportToAdd(reply); } From 3815172b56204f3433aa596ade9d437d1256f785 Mon Sep 17 00:00:00 2001 From: Youssef Date: Thu, 18 Apr 2019 05:08:03 +0200 Subject: [PATCH 06/22] checkpoint before feedback modifications over Requests handling and process --- src/sneps/network/Node.java | 9 ++ src/sneps/network/PropositionNode.java | 94 +++++++++++++++++-- src/sneps/network/RuleNode.java | 43 +++++---- .../network/classes/setClasses/NodeSet.java | 27 +----- src/sneps/snip/Report.java | 1 - src/sneps/snip/channels/Channel.java | 2 +- src/sneps/snip/rules/OrNode.java | 2 +- 7 files changed, 118 insertions(+), 60 deletions(-) diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java index e657d017..8d85f7e6 100644 --- a/src/sneps/network/Node.java +++ b/src/sneps/network/Node.java @@ -161,6 +161,11 @@ public void receiveRequest(Channel newChannel) { } + public void receiveReport(Channel newChannel) { + // TODO Auto-generated method stub + + } + public void processReports() { // TODO Auto-generated method stub @@ -210,6 +215,10 @@ public boolean isWhQuestion(Substitutions filterSubs) { return filterCardn < variablesCardn; } + /* + * Every variable that occurs free in the rule matches ma3 an element fel filter + * substitutions + */ public boolean areAllVariablesConstants(Substitutions switchSubs, Substitutions filterSubs) { int switchCardn = switchSubs.cardinality(); int filterCardn = filterSubs.cardinality(); diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 48ac13f7..9a210f0c 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -67,20 +67,53 @@ public PropositionNode(Term trm) { */ public void broadcastReport(Report report) { for (Channel outChannel : outgoingChannels) { - if (outChannel.testReportToAdd(report)) { + if (outChannel.testReportToSend(report)) { // System.out.println("SENDING REPORT " + this); } } } public boolean sendReport(Report report, Channel channel) { - if (channel.testReportToAdd(report)) { + if (channel.testReportToSend(report)) { // System.out.println("SENDING REPORT " + this); return true; } return false; } + protected void sendReports(NodeSet isAntecedentTo, ReportSet reports, ChannelTypes channelType) { + for (Node node : isAntecedentTo) { + for (Report report : reports) { + Substitutions reportSubs = report.getSubstitutions(); + Set reportSuppSet = report.getSupports(); + boolean reportSign = report.getSign(); + String reportContextName = report.getContextName(); + Channel newChannel = establishChannel(channelType, node, null, reportSubs, reportContextName, + InferenceTypes.FORWARD, -1); + outgoingChannels.addChannel(newChannel); + node.receiveReport(newChannel); + } + } + + } + + protected void sendReports(List list, ReportSet reports) { + for (Match match : list) { + for (Report report : reports) { + Substitutions reportSubs = report.getSubstitutions(); + Set reportSuppSet = report.getSupports(); + Node sentTo = match.getNode(); + boolean reportSign = report.getSign(); + String reportContextName = report.getContextName(); + int matchType = match.getMatchType(); + Channel newChannel = establishChannel(ChannelTypes.MATCHED, sentTo, null, reportSubs, reportContextName, + InferenceTypes.FORWARD, matchType); + outgoingChannels.addChannel(newChannel); + sentTo.receiveReport(newChannel); + } + } + } + /*** * Method handling all types of Channels establishment according to different * channel types passed through the matching. @@ -91,6 +124,8 @@ public boolean sendReport(Report report, Channel channel) { * @param filterSubs constraints substitutions for a specific request * @param contextId context name used * @param inferenceType inference type used for this process + * @param matchType int representing the match Type. -1 if not a matching + * node scenario * @return the established type based channel */ protected Channel establishChannel(ChannelTypes type, Object currentElement, Substitutions switchSubs, @@ -143,9 +178,9 @@ public void sendRequests(NodeSet ns, Substitutions filterSubs, String contextID, * @param currentChannel */ public void processSingleReportsChannel(Channel currentChannel) { - ReportSet reports = currentChannel.getReportsBuffer(); for (Report currentReport : reports) { + Substitutions reportSubs = currentReport.getSubstitutions(); Set reportSupportSet = currentReport.getSupports(); boolean reportSign = currentReport.isPositive(); @@ -153,8 +188,8 @@ public void processSingleReportsChannel(Channel currentChannel) { boolean toBeSentFlag = true; if (currentChannel instanceof MatchChannel) { int channelMatchType = ((MatchChannel) currentChannel).getMatchType(); - reportSign = channelMatchType == 2 ? !reportSign : reportSign; - toBeSentFlag = (channelMatchType != 1) || reportSign; + toBeSentFlag = (channelMatchType == 0) || (channelMatchType == 1 && currentReport.isPositive()) + || (channelMatchType == 2 && currentReport.isNegative()); } Report alteredReport = new Report(reportSubs, reportSupportSet, reportSign, reportContextName); if (knownInstances.contains(alteredReport)) @@ -163,8 +198,17 @@ public void processSingleReportsChannel(Channel currentChannel) { broadcastReport(alteredReport); currentChannel.clearReportsBuffer(); } + /* Handling forward inference broadcasting */ + if (currentChannel.getInferenceType() == InferenceTypes.FORWARD) { + List matchesReturned = Matcher.match(this); + if (matchesReturned != null) + sendReports(matchesReturned, reports); + NodeSet isAntecedentTo = getDominatingRules(); + sendReports(isAntecedentTo, reports, ChannelTypes.RuleAnt); + } currentChannel.clearReportsBuffer(); } + // PROCESS REPORT : 3adi -> , forward // -> same as 3adi , plus matching to send and get the nodes el howa lihom // antecedents we send reports @@ -199,14 +243,12 @@ public void processSingleRequestsChannel(Channel currentChannel) broadcastReport(reply); } else { boolean sentAtLeastOne = false; - for (Report currentReport : knownInstances) { + for (Report currentReport : knownInstances) sentAtLeastOne |= sendReport(currentReport, currentChannel); - } - Substitutions switchSubs = currentChannel.getSwitch().getSubstitutions(); Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); if (!sentAtLeastOne || isWhQuestion(filterSubs)) { NodeSet dominatingRules = getDominatingRules(); - NodeSet workingNodes = dominatingRules.alreadyWorking(currentChannel, false); + NodeSet workingNodes = alreadyWorking(dominatingRules, currentChannel, false); NodeSet toBeSentTo = dominatingRules.difference(workingNodes); sendRequests(toBeSentTo, new LinearSubstitutions(), currentContextName, ChannelTypes.RuleAnt, currentChannel.getInferenceType()); @@ -304,6 +346,40 @@ protected void getNodesToSendRequests(ChannelTypes channelType, String currentCo } + /*** + * Method comparing opened incoming channels over each node of the nodes whether + * a more generic request of the specified channel was previously sent in order + * not to re-send redundant requests -- ruleType gets applied on Andor or Thresh + * part. -- PropositionNode we static + * + * @param node set on which we will check existing request + * @param channel current channel handling the current request + * @return NodeSet containing all nodes previously requesting the subset of the + * specified channel request + */ + public static NodeSet alreadyWorking(NodeSet nodes, Channel channel, boolean ruleType) { + NodeSet nodesToNeglect = new NodeSet(); + for (Node sourceNode : nodes) + if (sourceNode instanceof PropositionNode) { + Substitutions currentChannelFilterSubs = channel.getFilter().getSubstitutions(); + ChannelSet incomingChannels = ((PropositionNode) sourceNode).getOutgoingChannels(); + ChannelSet filteredChannelsSet = incomingChannels.getFilteredRequestChannels(true); + boolean conditionMet = ruleType && sourceNode == channel.getRequester(); + if (!conditionMet) { + for (Channel incomingChannel : filteredChannelsSet) { + Substitutions processedChannelFilterSubs = incomingChannel.getFilter().getSubstitutions(); + conditionMet |= processedChannelFilterSubs.isSubSet(currentChannelFilterSubs) + && incomingChannel.getRequester() == channel.getReporter(); + if (conditionMet) { + nodesToNeglect.addNode(sourceNode); + break; + } + } + } + } + return nodesToNeglect; + } + public Support getBasicSupport() { return basicSupport; } diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index c7431acf..f3d6210b 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -283,54 +283,53 @@ public void processSingleRequestsChannel(Channel currentChannel) boolean closedTypeTerm = term instanceof Closed; String currentContextName = currentChannel.getContextName(); Context currentContext = Controller.getContextByName(currentContextName); -// VariableSet variablesList = ((Open) this.term).getFreeVariables(); Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); Substitutions switchSubs = currentChannel.getSwitch().getSubstitutions(); if (closedTypeTerm) { if (assertedInContext(currentContext)) { NodeSet antecedentNodeSet = getDownAntNodeSet(); - /* * fel rule node haguib el incoming channels we hastore ay haga ba3atlha request * el filter beta3o subset lel request el ana baservo, we hashil el list dih men * el antecdents + * + * ghayar el logic we hat el tosend 3alatoul */ - for (Node currentNode : antecedentNodeSet /* mengheir el prementioned set */) { - /* only needed for the andor & thresh */ - if (currentNode == currentChannel.getRequester()) - continue; - // TODO Akram: if not yet been requested for this - // instance - // TODO Youssef: added requestServing to monitor requests status over each - // channel established - // check incoming channels coming from current node law filter subsumes the - // filter of currentchannel - - } - NodeSet workingNodes = antecedentNodeSet.alreadyWorking(currentChannel, true); - NodeSet toBeSentTo = antecedentNodeSet.difference(workingNodes); + NodeSet neglectingNodes = alreadyWorking(antecedentNodeSet, currentChannel, true); + NodeSet toBeSentTo = antecedentNodeSet.difference(neglectingNodes); sendRequests(toBeSentTo, currentChannel.getFilter().getSubstitutions(), currentChannel.getContextName(), ChannelTypes.RuleAnt, currentChannel.getInferenceType()); return; + } else { + super.processSingleRequestsChannel(currentChannel) } } else { // TODO Akram: there are free variables but each is bound; check filter beta3 el // channel law empty ReportSet knownReportSet = knownInstances; + for (Report report : knownReportSet) { Substitutions reportSubstitutions = report.getSubstitutions(); - if (filterSubs.isEqual(reportSubstitutions)) { - getNodesToSendRequests(ChannelTypes.RuleCons, currentContextName, null, - currentChannel.getInferenceType()); + if (filterSubs.isSubSet(reportSubstitutions) && true /*atleast support of the report is asserted in the context*/) { + + /*men antecedents lel rule*/ +//Case 1: asserted same logic law kolo constants + //getNodesToSendRequests(ChannelTypes.RuleAnt, currentContextName, null, + // currentChannel.getInferenceType()); if (areAllVariablesConstants(switchSubs, filterSubs)) return; - else + else { + + // Case 3: fih one free variale le kol instance hab3at lel antecedents request bel filter beta3 each istance while checking if alreadyWorking on it, we call super.proccessSingle break; + } + } else { + } } } - } - super.processSingleRequestsChannel(currentChannel); + } else + super.processSingleRequestsChannel(currentChannel); } diff --git a/src/sneps/network/classes/setClasses/NodeSet.java b/src/sneps/network/classes/setClasses/NodeSet.java index cf8e337f..b1d2aa0e 100644 --- a/src/sneps/network/classes/setClasses/NodeSet.java +++ b/src/sneps/network/classes/setClasses/NodeSet.java @@ -52,32 +52,7 @@ public boolean contains(Node node) { return this.nodes.contains(node); } - /*** - * Method checking if a similar more generic request is being processed and - * awaits a report in order not to re-send the same request - * - * @param node set on which we will check existing request - * @param channel current channel handling the current request - * @return boolean represents whether a more generic request has been received - */ - public NodeSet alreadyWorking(Channel channel, boolean ruleType) { - NodeSet toSentTo = new NodeSet(); - for (Node sourceNode : nodes) - if (sourceNode instanceof PropositionNode) { - Substitutions currentChannelFilterSubs = channel.getFilter().getSubstitutions(); - ChannelSet incomingChannels = ((PropositionNode) sourceNode).getIncomingChannels(); - ChannelSet filteredChannelsSet = incomingChannels.getFilteredRequestChannels(true); - boolean conditionMet = true; - for (Channel incomingChannel : filteredChannelsSet) { - Substitutions processedChannelFilterSubs = incomingChannel.getFilter().getSubstitutions(); - conditionMet |= (ruleType ? sourceNode != incomingChannel.getRequester() : true) - && !processedChannelFilterSubs.isSubSet(currentChannelFilterSubs); - } - if (conditionMet) - toSentTo.addNode(sourceNode); - } - return toSentTo; - } + public NodeSet Union(NodeSet ns) { NodeSet unionSet = new NodeSet(); diff --git a/src/sneps/snip/Report.java b/src/sneps/snip/Report.java index 0df5ecba..01cedc44 100644 --- a/src/sneps/snip/Report.java +++ b/src/sneps/snip/Report.java @@ -5,7 +5,6 @@ import sneps.snebr.Support; import sneps.snip.matching.Substitutions; -/*add type of inference*/ public class Report { private Substitutions substitution; private Set supports; diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index 426e1a10..6ae2ba01 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -43,7 +43,7 @@ public Channel(Substitutions switcherSubstitution, Substitutions filterSubstitut this.inferenceType = inferenceType; } - public boolean testReportToAdd(Report report) { + public boolean testReportToSend(Report report) { boolean passTest = filter.canPass(report); System.out.println("Can pass " + passTest); if (passTest && contextName.equals(report.getContextName())) { diff --git a/src/sneps/snip/rules/OrNode.java b/src/sneps/snip/rules/OrNode.java index 91b1b4c4..a61ee28b 100644 --- a/src/sneps/snip/rules/OrNode.java +++ b/src/sneps/snip/rules/OrNode.java @@ -35,7 +35,7 @@ public void applyRuleHandler(Report report, Node node) { Report reply = new Report(report.getSubstitutions(), sup, true, report.getContextName()); for (Channel outChannel : outgoingChannels) - outChannel.testReportToAdd(reply); + outChannel.testReportToSend(reply); } From 0229584a1bd7784ac2345645f894e994b0543c03 Mon Sep 17 00:00:00 2001 From: Youssef Date: Wed, 24 Apr 2019 04:12:53 +0200 Subject: [PATCH 07/22] fixing processSingleRequestsChannel in RuleNode --- src/sneps/network/Node.java | 10 ++-- src/sneps/network/PropositionNode.java | 30 +++++------ src/sneps/network/RuleNode.java | 53 ++++++++++--------- src/sneps/snip/Filter.java | 2 +- src/sneps/snip/Switch.java | 4 +- src/sneps/snip/matching/Binding.java | 4 +- .../snip/matching/LinearSubstitutions.java | 41 +++++++++----- src/sneps/snip/matching/Substitutions.java | 3 +- 8 files changed, 83 insertions(+), 64 deletions(-) diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java index 8d85f7e6..49123191 100644 --- a/src/sneps/network/Node.java +++ b/src/sneps/network/Node.java @@ -219,10 +219,12 @@ public boolean isWhQuestion(Substitutions filterSubs) { * Every variable that occurs free in the rule matches ma3 an element fel filter * substitutions */ - public boolean areAllVariablesConstants(Substitutions switchSubs, Substitutions filterSubs) { - int switchCardn = switchSubs.cardinality(); - int filterCardn = filterSubs.cardinality(); - return switchCardn > 0 && filterCardn == switchCardn; + public boolean areAllVariablesConstants(Substitutions filterSubs) { + VariableSet freeVariables = new VariableSet(); + if (term instanceof Open) + freeVariables = ((Open) term).getFreeVariables(); + return filterSubs.eachBound(freeVariables); + } Context fake() { diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 9a210f0c..7e9433d5 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -248,8 +248,7 @@ public void processSingleRequestsChannel(Channel currentChannel) Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); if (!sentAtLeastOne || isWhQuestion(filterSubs)) { NodeSet dominatingRules = getDominatingRules(); - NodeSet workingNodes = alreadyWorking(dominatingRules, currentChannel, false); - NodeSet toBeSentTo = dominatingRules.difference(workingNodes); + NodeSet toBeSentTo = alreadyWorking(dominatingRules, currentChannel, false); sendRequests(toBeSentTo, new LinearSubstitutions(), currentContextName, ChannelTypes.RuleAnt, currentChannel.getInferenceType()); if (!(currentChannel instanceof MatchChannel)) // was in !alreadyWorking if condition @@ -350,34 +349,35 @@ protected void getNodesToSendRequests(ChannelTypes channelType, String currentCo * Method comparing opened incoming channels over each node of the nodes whether * a more generic request of the specified channel was previously sent in order * not to re-send redundant requests -- ruleType gets applied on Andor or Thresh - * part. -- PropositionNode we static + * part. * * @param node set on which we will check existing request * @param channel current channel handling the current request - * @return NodeSet containing all nodes previously requesting the subset of the - * specified channel request + * @return NodeSet containing all nodes that has not previously requested the + * subset of the specified channel request */ public static NodeSet alreadyWorking(NodeSet nodes, Channel channel, boolean ruleType) { - NodeSet nodesToNeglect = new NodeSet(); + NodeSet nodesToConsider = new NodeSet(); for (Node sourceNode : nodes) if (sourceNode instanceof PropositionNode) { - Substitutions currentChannelFilterSubs = channel.getFilter().getSubstitutions(); - ChannelSet incomingChannels = ((PropositionNode) sourceNode).getOutgoingChannels(); - ChannelSet filteredChannelsSet = incomingChannels.getFilteredRequestChannels(true); boolean conditionMet = ruleType && sourceNode == channel.getRequester(); if (!conditionMet) { - for (Channel incomingChannel : filteredChannelsSet) { - Substitutions processedChannelFilterSubs = incomingChannel.getFilter().getSubstitutions(); - conditionMet |= processedChannelFilterSubs.isSubSet(currentChannelFilterSubs) - && incomingChannel.getRequester() == channel.getReporter(); + conditionMet = true; + Substitutions currentChannelFilterSubs = channel.getFilter().getSubstitutions(); + ChannelSet outgoingChannels = ((PropositionNode) sourceNode).getOutgoingChannels(); + ChannelSet filteredChannelsSet = outgoingChannels.getFilteredRequestChannels(true); + for (Channel outgoingChannel : filteredChannelsSet) { + Substitutions processedChannelFilterSubs = outgoingChannel.getFilter().getSubstitutions(); + conditionMet &= !processedChannelFilterSubs.isSubSet(currentChannelFilterSubs) + && outgoingChannel.getRequester() == channel.getReporter(); if (conditionMet) { - nodesToNeglect.addNode(sourceNode); + nodesToConsider.addNode(sourceNode); break; } } } } - return nodesToNeglect; + return nodesToConsider; } public Support getBasicSupport() { diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index f3d6210b..30c113b0 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -34,6 +34,8 @@ import sneps.snip.classes.SIndex; import sneps.snip.matching.LinearSubstitutions; import sneps.snip.matching.Substitutions; +import sneps.snip.rules.AndOrNode; +import sneps.snip.rules.ThreshNode; public abstract class RuleNode extends PropositionNode implements Serializable { @@ -269,6 +271,14 @@ public void processRequests() { } } + public void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel) { + NodeSet antecedentNodeSet = getDownAntNodeSet(); + boolean ruleType = this instanceof ThreshNode || this instanceof AndOrNode; + NodeSet toBeSentTo = alreadyWorking(antecedentNodeSet, currentChannel, ruleType); + sendRequests(toBeSentTo, currentChannel.getFilter().getSubstitutions(), currentChannel.getContextName(), + ChannelTypes.RuleAnt, currentChannel.getInferenceType()); + } + /*** * Request handling in Rule proposition nodes. * @@ -284,52 +294,43 @@ public void processSingleRequestsChannel(Channel currentChannel) String currentContextName = currentChannel.getContextName(); Context currentContext = Controller.getContextByName(currentContextName); Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); - Substitutions switchSubs = currentChannel.getSwitch().getSubstitutions(); if (closedTypeTerm) { if (assertedInContext(currentContext)) { - NodeSet antecedentNodeSet = getDownAntNodeSet(); - /* - * fel rule node haguib el incoming channels we hastore ay haga ba3atlha request - * el filter beta3o subset lel request el ana baservo, we hashil el list dih men - * el antecdents - * - * ghayar el logic we hat el tosend 3alatoul - */ - NodeSet neglectingNodes = alreadyWorking(antecedentNodeSet, currentChannel, true); - NodeSet toBeSentTo = antecedentNodeSet.difference(neglectingNodes); - sendRequests(toBeSentTo, currentChannel.getFilter().getSubstitutions(), - currentChannel.getContextName(), ChannelTypes.RuleAnt, currentChannel.getInferenceType()); + requestAntecedentsNotAlreadyWorkingOn(currentChannel); return; } else { - super.processSingleRequestsChannel(currentChannel) + super.processSingleRequestsChannel(currentChannel); } } else { // TODO Akram: there are free variables but each is bound; check filter beta3 el // channel law empty ReportSet knownReportSet = knownInstances; - for (Report report : knownReportSet) { Substitutions reportSubstitutions = report.getSubstitutions(); - if (filterSubs.isSubSet(reportSubstitutions) && true /*atleast support of the report is asserted in the context*/) { - - /*men antecedents lel rule*/ + if (filterSubs.isSubSet(reportSubstitutions) + && true /* atleast support of the report is asserted in the context */) { + + /* men antecedents lel rule */ //Case 1: asserted same logic law kolo constants - //getNodesToSendRequests(ChannelTypes.RuleAnt, currentContextName, null, - // currentChannel.getInferenceType()); - if (areAllVariablesConstants(switchSubs, filterSubs)) + // getNodesToSendRequests(ChannelTypes.RuleAnt, currentContextName, null, + // currentChannel.getInferenceType()); + if (areAllVariablesConstants(filterSubs)) { + requestAntecedentsNotAlreadyWorkingOn(currentChannel); return; - else { - - // Case 3: fih one free variale le kol instance hab3at lel antecedents request bel filter beta3 each istance while checking if alreadyWorking on it, we call super.proccessSingle + } else { + + // Case 3: fih one free variale le kol instance hab3at lel antecedents request + // bel filter beta3 each istance while checking if alreadyWorking on it, we call + // super.proccessSingle break; } } else { - + } } } } else - super.processSingleRequestsChannel(currentChannel); + super.processSingleRequestsChannel(currentChannel); } diff --git a/src/sneps/snip/Filter.java b/src/sneps/snip/Filter.java index a5bf26a5..bffc3773 100644 --- a/src/sneps/snip/Filter.java +++ b/src/sneps/snip/Filter.java @@ -31,7 +31,7 @@ public boolean canPass(Report report) { for (int i = 0; i < this.substitutions.cardinality(); i++) { Binding currentFilterBinding = substitutions.getBinding(i); Binding currentReportBinding = report.getSubstitutions() - .getBindingByVariable(currentFilterBinding.getVariable()); + .getBindingByVariable(currentFilterBinding.getVariableNode()); System.out.println("Bindings " + currentFilterBinding + " " + report.getSubstitutions()); if (currentReportBinding != null && currentFilterBinding.getNode() != currentReportBinding.getNode()) return false; diff --git a/src/sneps/snip/Switch.java b/src/sneps/snip/Switch.java index f7ac2e66..e626b6fd 100644 --- a/src/sneps/snip/Switch.java +++ b/src/sneps/snip/Switch.java @@ -26,8 +26,8 @@ public Switch(Substitutions substitution) { public void switchReport(Report r) { for (int i = 0; i < this.substitutions.cardinality(); i++) { - Binding b = r.getSubstitutions().getBindingByVariable(this.substitutions.getBinding(i).getVariable()); - System.out.println(this.substitutions.getBinding(i).getVariable()); + Binding b = r.getSubstitutions().getBindingByVariable(this.substitutions.getBinding(i).getVariableNode()); + System.out.println(this.substitutions.getBinding(i).getVariableNode()); System.out.println("i: " + i + " binding: " + b); if (b != null) { b.setVariable((VariableNode) this.substitutions.getBinding(i).getNode()); diff --git a/src/sneps/snip/matching/Binding.java b/src/sneps/snip/matching/Binding.java index 07a89aba..9106a889 100644 --- a/src/sneps/snip/matching/Binding.java +++ b/src/sneps/snip/matching/Binding.java @@ -23,7 +23,7 @@ public Binding(VariableNode variable, Node node) { * * @return variable */ - public VariableNode getVariable() { + public VariableNode getVariableNode() { return variable; } @@ -43,7 +43,7 @@ public Node getNode() { * @return true if equal false otherwise */ public boolean isEqual(Binding binding) { - if (this.getNode() == binding.getNode() && this.getVariable() == binding.getVariable()) + if (this.getNode() == binding.getNode() && this.getVariableNode() == binding.getVariableNode()) return true; return false; } diff --git a/src/sneps/snip/matching/LinearSubstitutions.java b/src/sneps/snip/matching/LinearSubstitutions.java index a93f1478..e500e94b 100644 --- a/src/sneps/snip/matching/LinearSubstitutions.java +++ b/src/sneps/snip/matching/LinearSubstitutions.java @@ -4,6 +4,8 @@ import sneps.network.Node; import sneps.network.VariableNode; +import sneps.network.classes.setClasses.VariableSet; +import sneps.network.classes.term.Variable; public class LinearSubstitutions implements Substitutions { private Vector sub; @@ -67,7 +69,7 @@ public void update(Binding mb, Node mn) { */ public boolean isBound(VariableNode mv) { for (int i = 0; i < sub.size(); i++) { - if (sub.get(i).getVariable() == mv) { + if (sub.get(i).getVariableNode() == mv) { return true; } } @@ -99,7 +101,7 @@ public boolean isValue(Node mn) { public VariableNode srcNode(Node mn) { for (int i = 0; i < sub.size(); i++) { if (sub.get(i).getNode() == mn) { - return sub.get(i).getVariable(); + return sub.get(i).getVariableNode(); } } return null; @@ -114,7 +116,7 @@ public VariableNode srcNode(Node mn) { */ public Binding getBindingByVariable(VariableNode mv) { for (int i = 0; i < sub.size(); i++) { - if (sub.get(i).getVariable() == mv) { + if (sub.get(i).getVariableNode() == mv) { return sub.get(i); } } @@ -260,7 +262,7 @@ public Substitutions restrict(VariableNode[] ns) { */ public Node term(VariableNode mv) { for (int i = 0; i < sub.size(); i++) { - if (sub.get(i).getVariable() == mv) { + if (sub.get(i).getVariableNode() == mv) { return sub.get(i).getNode(); } } @@ -341,11 +343,11 @@ public boolean isCompatible(Substitutions s) { LinearSubstitutions sl = (LinearSubstitutions) s; for (int i = 0; i < this.sub.size(); i++) { for (int j = 0; j < sl.sub.size(); j++) { - if (sl.sub.get(j).getVariable() == this.sub.get(i).getVariable()) { + if (sl.sub.get(j).getVariableNode() == this.sub.get(i).getVariableNode()) { if (sl.sub.get(j).getNode() != this.sub.get(i).getNode()) return false; } else if (sl.sub.get(j).getNode() == this.sub.get(i).getNode()) - if (sl.sub.get(j).getVariable() != this.sub.get(i).getVariable()) + if (sl.sub.get(j).getVariableNode() != this.sub.get(i).getVariableNode()) return false; } } @@ -427,7 +429,7 @@ public boolean sub(String x, String y) { public String toString() { String res = ""; for (int i = 0; i < sub.size(); i++) { - res += sub.get(i).getNode().getIdentifier() + " substitutes " + sub.get(i).getVariable().getIdentifier() + res += sub.get(i).getNode().getIdentifier() + " substitutes " + sub.get(i).getVariableNode().getIdentifier() + '\n'; } return res; @@ -435,26 +437,39 @@ public String toString() { public int termID(int variableID) { for (int i = 0; i < sub.size(); i++) - if (sub.get(i).getVariable().getId() == variableID) + if (sub.get(i).getVariableNode().getId() == variableID) return sub.get(i).getNode().getId(); return -1; } @Override public void insertOrUpdate(Binding mb) { - if (isBound(mb.getVariable())) - update(getBindingByVariable(mb.getVariable()), mb.getNode()); + if (isBound(mb.getVariableNode())) + update(getBindingByVariable(mb.getVariableNode()), mb.getNode()); else putIn(mb); } - /*** + /** * Method to iterate over all variables in the Vector to check for * their bound status */ - public boolean areVariablesBound() { - return isNew(); + public boolean eachBound(VariableSet freeVariables) { + boolean condition = true; + for (Binding binding : sub) { + VariableSet bindingFreeVariables = binding.getVariableNode().getFreeVariables(); + for (Variable bindVariable : bindingFreeVariables) { + + } + for (Variable variable : freeVariables) { + + String variableIdentifier = variable.getIdentifier(); + + } + } + return condition; + } } \ No newline at end of file diff --git a/src/sneps/snip/matching/Substitutions.java b/src/sneps/snip/matching/Substitutions.java index adb59781..34c01423 100644 --- a/src/sneps/snip/matching/Substitutions.java +++ b/src/sneps/snip/matching/Substitutions.java @@ -2,6 +2,7 @@ import sneps.network.Node; import sneps.network.VariableNode; +import sneps.network.classes.setClasses.VariableSet; public interface Substitutions { @@ -65,6 +66,6 @@ public interface Substitutions { public void insertOrUpdate(Binding mb); - public boolean areVariablesBound(); + public boolean eachBound(VariableSet freeVariables); } From 7bd3260cd65c39ef692b27a269a42dc1a4f41a11 Mon Sep 17 00:00:00 2001 From: Youssef Date: Fri, 26 Apr 2019 00:17:19 +0200 Subject: [PATCH 08/22] defined new Class VariableNodeStats for easier logic and changed the Report to Hashtable computing corresponding changes and further mods in proccesSingleRequestsChannel in RuleNode and PropositionNode --- src/sneps/network/Node.java | 22 +- src/sneps/network/PropositionNode.java | 66 +++- src/sneps/network/RuleNode.java | 77 +++- src/sneps/snebr/Context.java | 360 +++++++++--------- src/sneps/snip/Filter.java | 7 +- src/sneps/snip/Report.java | 8 +- src/sneps/snip/channels/Channel.java | 1 + src/sneps/snip/classes/FlagNode.java | 12 +- src/sneps/snip/classes/VariableNodeStats.java | 61 +++ .../snip/matching/LinearSubstitutions.java | 32 +- src/sneps/snip/matching/Substitutions.java | 3 +- src/sneps/snip/rules/OrNode.java | 21 +- 12 files changed, 416 insertions(+), 254 deletions(-) create mode 100644 src/sneps/snip/classes/VariableNodeStats.java diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java index 49123191..0f1f6ffe 100644 --- a/src/sneps/network/Node.java +++ b/src/sneps/network/Node.java @@ -23,6 +23,7 @@ import sneps.snip.channels.ChannelTypes; import sneps.snip.channels.MatchChannel; import sneps.snip.channels.RuleToConsequentChannel; +import sneps.snip.classes.VariableNodeStats; import sneps.snip.matching.LinearSubstitutions; import sneps.snip.matching.Substitutions; @@ -208,6 +209,7 @@ public NodeSet getDominatingRules() { public boolean isWhQuestion(Substitutions filterSubs) { if (!(this instanceof VariableNode)) return false; + /* change sizes check as they are no longer important */.IMP. VariableNode node = (VariableNode) this; VariableSet variables = node.getFreeVariables(); int variablesCardn = variables.size(); @@ -215,15 +217,25 @@ public boolean isWhQuestion(Substitutions filterSubs) { return filterCardn < variablesCardn; } - /* - * Every variable that occurs free in the rule matches ma3 an element fel filter - * substitutions + /*** + * Method computing an output of VariableNodeStats containing info about a + * certain node with variables by checking the input Substitutions and comparing + * them with the instance freeVariables, stating whether over a given + * substitutions the node will have all its freeVariables bound and also + * filtering the input substitutions to match the free variables (not including + * extra irrelevant filters) + * + * @param filterSubs Substitutions the given substitutions on which bindings + * check will occur + * @return VariableNodeStats */ - public boolean areAllVariablesConstants(Substitutions filterSubs) { + public VariableNodeStats computeNodeStats(Substitutions filterSubs) { VariableSet freeVariables = new VariableSet(); if (term instanceof Open) freeVariables = ((Open) term).getFreeVariables(); - return filterSubs.eachBound(freeVariables); + VariableNodeStats toBeReturned = filterSubs.extractBoundStatus(freeVariables); + toBeReturned.setNodeId(id); + return toBeReturned; } diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 7e9433d5..2e6b0e84 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -85,7 +85,7 @@ protected void sendReports(NodeSet isAntecedentTo, ReportSet reports, ChannelTyp for (Node node : isAntecedentTo) { for (Report report : reports) { Substitutions reportSubs = report.getSubstitutions(); - Set reportSuppSet = report.getSupports(); + Hashtable reportSuppSet = report.getSupports(); boolean reportSign = report.getSign(); String reportContextName = report.getContextName(); Channel newChannel = establishChannel(channelType, node, null, reportSubs, reportContextName, @@ -101,7 +101,7 @@ protected void sendReports(List list, ReportSet reports) { for (Match match : list) { for (Report report : reports) { Substitutions reportSubs = report.getSubstitutions(); - Set reportSuppSet = report.getSupports(); + Hashtable reportSuppSet = report.getSupports(); Node sentTo = match.getNode(); boolean reportSign = report.getSign(); String reportContextName = report.getContextName(); @@ -182,7 +182,7 @@ public void processSingleReportsChannel(Channel currentChannel) { for (Report currentReport : reports) { Substitutions reportSubs = currentReport.getSubstitutions(); - Set reportSupportSet = currentReport.getSupports(); + Hashtable reportSupportSet = currentReport.getSupports(); boolean reportSign = currentReport.isPositive(); String reportContextName = currentReport.getContextName(); boolean toBeSentFlag = true; @@ -232,13 +232,16 @@ public void processSingleRequestsChannel(Channel currentChannel) int instanceNodeId = getId(); PropositionSet propSet = new PropositionSet(); propSet.add(instanceNodeId); + Hashtable nodeAssumptionBasedSupport = getAssumptionBasedSupport(); + String currentContextName = currentChannel.getContextName(); Context desiredContext = Controller.getContextByName(currentContextName); if (assertedInContext(desiredContext)) { // TODO change the subs to hashsubs - Set support = new HashSet(); - support.add(new Support(instanceNodeId)); - Report reply = new Report(new LinearSubstitutions(), support, true, currentChannel.getContextName()); + Hashtable support = new Hashtable(); +// support.put("1", propSet); + Report reply = new Report(new LinearSubstitutions(), nodeAssumptionBasedSupport, true, + currentChannel.getContextName()); knownInstances.addReport(reply); broadcastReport(reply); } else { @@ -248,12 +251,20 @@ public void processSingleRequestsChannel(Channel currentChannel) Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); if (!sentAtLeastOne || isWhQuestion(filterSubs)) { NodeSet dominatingRules = getDominatingRules(); - NodeSet toBeSentTo = alreadyWorking(dominatingRules, currentChannel, false); - sendRequests(toBeSentTo, new LinearSubstitutions(), currentContextName, ChannelTypes.RuleAnt, + NodeSet toBeSentToDom = alreadyWorking(dominatingRules, currentChannel, false); + sendRequests(toBeSentToDom, new LinearSubstitutions(), currentContextName, ChannelTypes.RuleAnt, currentChannel.getInferenceType()); - if (!(currentChannel instanceof MatchChannel)) // was in !alreadyWorking if condition - getNodesToSendRequests(ChannelTypes.MATCHED, currentChannel.getContextName(), null, + if (!(currentChannel instanceof MatchChannel)) { + List matchingNodes = Matcher.match(this); + List toBeSentToMatch = alreadyWorking(matchingNodes, currentChannel, false); + sendRequests(toBeSentToMatch, currentContextName, ChannelTypes.MATCHED, currentChannel.getInferenceType()); + } + /* + * if (!(currentChannel instanceof MatchChannel)) // was in !alreadyWorking if + * condition getNodesToSendRequests(ChannelTypes.MATCHED, + * currentChannel.getContextName(), null, currentChannel.getInferenceType()); + */ } } } @@ -270,6 +281,11 @@ public boolean assertedInContext(Context desiredContext) return desiredContext.isAsserted(this); } + public boolean assertedInContext(String desiredContextName) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + return Controller.getContextByName(desiredContextName).isAsserted(this); + } + public void processRequests() { for (Channel outChannel : outgoingChannels) try { @@ -345,6 +361,30 @@ protected void getNodesToSendRequests(ChannelTypes channelType, String currentCo } + public List alreadyWorking(List matchingNodes, Channel currentChannel, boolean ruleType) { + List nodesToConsider = new ArrayList(); + for (Match sourceMatch : matchingNodes) { + Node sourceNode = sourceMatch.getNode(); + if (sourceNode instanceof PropositionNode) { + boolean conditionMet = ruleType && sourceNode == currentChannel.getRequester(); + if (!conditionMet) { + conditionMet = true; + Substitutions currentChannelFilterSubs = currentChannel.getFilter().getSubstitutions(); + ChannelSet outgoingChannels = ((PropositionNode) sourceNode).getOutgoingChannels(); + ChannelSet filteredChannelsSet = outgoingChannels.getFilteredRequestChannels(true); + for (Channel outgoingChannel : filteredChannelsSet) { + Substitutions processedChannelFilterSubs = outgoingChannel.getFilter().getSubstitutions(); + conditionMet &= !processedChannelFilterSubs.isSubSet(currentChannelFilterSubs) + && outgoingChannel.getRequester() == currentChannel.getReporter(); + } + if (conditionMet) + nodesToConsider.add(sourceMatch); + } + } + } + return nodesToConsider; + } + /*** * Method comparing opened incoming channels over each node of the nodes whether * a more generic request of the specified channel was previously sent in order @@ -370,11 +410,9 @@ public static NodeSet alreadyWorking(NodeSet nodes, Channel channel, boolean rul Substitutions processedChannelFilterSubs = outgoingChannel.getFilter().getSubstitutions(); conditionMet &= !processedChannelFilterSubs.isSubSet(currentChannelFilterSubs) && outgoingChannel.getRequester() == channel.getReporter(); - if (conditionMet) { - nodesToConsider.addNode(sourceNode); - break; - } } + if (conditionMet) + nodesToConsider.addNode(sourceNode); } } return nodesToConsider; diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index 30c113b0..f837439d 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -1,9 +1,11 @@ package sneps.network; import java.io.Serializable; +import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; import java.util.Set; +import java.util.Vector; import sneps.exceptions.DuplicatePropositionException; import sneps.exceptions.NodeNotFoundInNetworkException; @@ -32,6 +34,8 @@ import sneps.snip.classes.FlagNode; import sneps.snip.classes.RuleUseInfo; import sneps.snip.classes.SIndex; +import sneps.snip.classes.VariableNodeStats; +import sneps.snip.matching.Binding; import sneps.snip.matching.LinearSubstitutions; import sneps.snip.matching.Substitutions; import sneps.snip.rules.AndOrNode; @@ -279,6 +283,35 @@ public void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel) { ChannelTypes.RuleAnt, currentChannel.getInferenceType()); } + /* Check error in COntext */ +// public boolean anySupportAssertedInContext(Report report) +// throws NotAPropositionNodeException, NodeNotFoundInNetworkException { +// String reportContextName = report.getContextName(); +// Set reportSupports = report.getSupports(); +// for (Support support : reportSupports) { +// int supportId = support.getId(); +// PropositionNode supportNode = (PropositionNode) Network.getNodeById(supportId); +// if (supportNode.assertedInContext(reportContextName)) +// return true; +// } +// return false; +// } + + public boolean anySupportAssertedInContext(Report report) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + String reportContextName = report.getContextName(); + Context reportContext = Controller.getContextByName(reportContextName); + Hashtable reportSupports = report.getSupports(); + PropositionSet contextHypothesisSet = reportContext.getHypothesisSet(); + Collection reportSupportsSet = reportSupports.values(); + for (PropositionSet assumptionHyps : reportSupportsSet) { + if (assumptionHyps.isSubSet(contextHypothesisSet)) { + return true; + } + } + return false; + } + /*** * Request handling in Rule proposition nodes. * @@ -295,6 +328,7 @@ public void processSingleRequestsChannel(Channel currentChannel) Context currentContext = Controller.getContextByName(currentContextName); Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); if (closedTypeTerm) { + /* Case 1 */ if (assertedInContext(currentContext)) { requestAntecedentsNotAlreadyWorkingOn(currentChannel); return; @@ -302,33 +336,34 @@ public void processSingleRequestsChannel(Channel currentChannel) super.processSingleRequestsChannel(currentChannel); } } else { - // TODO Akram: there are free variables but each is bound; check filter beta3 el - // channel law empty - ReportSet knownReportSet = knownInstances; - for (Report report : knownReportSet) { - Substitutions reportSubstitutions = report.getSubstitutions(); - if (filterSubs.isSubSet(reportSubstitutions) - && true /* atleast support of the report is asserted in the context */) { - - /* men antecedents lel rule */ -//Case 1: asserted same logic law kolo constants - // getNodesToSendRequests(ChannelTypes.RuleAnt, currentContextName, null, - // currentChannel.getInferenceType()); - if (areAllVariablesConstants(filterSubs)) { + VariableNodeStats ruleNodeStats = computeNodeStats(filterSubs); + boolean ruleNodeAllVariablesBound = ruleNodeStats.areAllVariablesBound(); + Vector ruleNodeExtractedSubs = ruleNodeStats.getVariableNodeSubs(); + if (ruleNodeAllVariablesBound) { + /* Case 2 */ + ReportSet knownReportSet = knownInstances; + for (Report report : knownReportSet) { + Substitutions reportSubstitutions = report.getSubstitutions(); + VariableNodeStats reportNodeStats = computeNodeStats(reportSubstitutions); + Vector reportNodeExtractedSubs = reportNodeStats.getVariableNodeSubs(); + if (ruleNodeExtractedSubs.size() == reportNodeExtractedSubs.size() + && anySupportAssertedInContext(report)) { requestAntecedentsNotAlreadyWorkingOn(currentChannel); return; - } else { - - // Case 3: fih one free variale le kol instance hab3at lel antecedents request - // bel filter beta3 each istance while checking if alreadyWorking on it, we call - // super.proccessSingle - break; } - } else { - } + super.processSingleRequestsChannel(currentChannel); + return; + } else { + /* Case 3 */ + // Case 3: fih one free variale le kol instance hab3at lel antecedents request + // bel filter beta3 each istance while checking if alreadyWorking on it, we call + // super.proccessSingle + super.processSingleRequestsChannel(currentChannel); } + } + } else super.processSingleRequestsChannel(currentChannel); diff --git a/src/sneps/snebr/Context.java b/src/sneps/snebr/Context.java index ba45503f..9b8cd348 100644 --- a/src/sneps/snebr/Context.java +++ b/src/sneps/snebr/Context.java @@ -13,182 +13,188 @@ import java.util.Collection; import java.util.HashSet; - -public class Context implements Serializable{ - private PropositionSet hyps; - - private HashSet names; - - protected BitSet getHypsBitset() { - return hypsBitset; - } - - private BitSet hypsBitset; - - /** - * Constructs a new empty Context - */ - protected Context() { - names = new HashSet(); - this.hyps = new PropositionSet(); - this.hypsBitset = new BitSet(); - } - - /** - * Constructs a new Context given its name - * - * @param contextName the name of the Context to be created - */ - protected Context(String contextName) { - this(); - names.add(contextName); - } - - /** - * Constructs a new Context from another Context - * - * @param c the context that the new Context is constructed from - */ - protected Context(Context c) { - this.hyps = c.getHypothesisSet(); - this.names = c.getNames(); - this.hypsBitset = c.getHypsBitset(); - } - - /** - * Constructs a new Context from a Context and asserts a hypothesis hyp in it. - * - * @param c the context to be used for constructing this new Context - * @param hyp the hyp to be asserted in the new Context - * @throws DuplicatePropositionException if the hyp is present in the context c - * @throws NodeNotFoundInNetworkException - */ - protected Context(Context c, int hyp) throws NotAPropositionNodeException, DuplicatePropositionException, NodeNotFoundInNetworkException { - this.names = c.getNames(); - this.hyps = c.getHypothesisSet().add(hyp); - this.hypsBitset = (BitSet) c.getHypsBitset().clone(); - this.hypsBitset.set(hyp); - } - - /** - * Constructs a new Context from an old Context c, and adds a new name to this new Context - * - * @param contextName - * @param c - */ - protected Context(String contextName, Context c) { - this(c); - this.names.add(contextName); - } - - /** - * Constructs a new Context using its name and sets the Context's hyps to a passed Proposition set hyps. - * - * @param contextName name of the new Context - * @param hyps the hyps the Context's hyps should be set to - */ - protected Context(String contextName, PropositionSet hyps) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - this(contextName); - this.hyps = hyps; - this.hypsBitset = new BitSet(); - int [] arr = PropositionSet.getPropsSafely(this.hyps); - for (int i = 0; i < arr.length; i++) - this.hypsBitset.set(arr[i]); - } - - /** - * Returns the hyps of this Context - * - * @return a PropositionSet containing the hyps of this Context - */ - public PropositionSet getHypothesisSet() { - return hyps; - } - - /** - * Returns the names of this Context object. - * - * @return a Hashset of type String containing the names of this context. - */ - protected HashSet getNames() { - return names; - } - - public String getName() { - return null; - } - - /** - * Checks if a propositions is asserted in this context - * - * @param p the proposition to be checked for assertion. - * @return true if the proposition exists, otherwise false - * @throws NotAPropositionNodeException If the node p is not a proposition. - * @throws NodeNotFoundInNetworkException If the node p doesn't exist in the network. - */ - public boolean isAsserted(PropositionNode p) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - int hyp = p.getId(); - - return Arrays.binarySearch(PropositionSet.getPropsSafely(this.hyps), hyp) > 0 - || isSupported(p); - } - - public boolean isSupported(PropositionNode node) { - Collection assumptionSet = node.getBasicSupport() - .getAssumptionBasedSupport() - .values(); - for (PropositionSet assumptionHyps : assumptionSet) { - if (assumptionHyps.isSubSet(this.hyps)) { - return true; - } - } - return false; - } - - public PropositionSet allAsserted() throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { - Collection allPropositionNodes = Network.getPropositionNodes().values(); - PropositionSet asserted = new PropositionSet(); - int[] hyps; - hyps = PropositionSet.getPropsSafely(this.hyps); - for (PropositionNode node : allPropositionNodes) { - if (Arrays.binarySearch(hyps, node.getId()) > 0) { - asserted = asserted.add(node.getId()); - } else if (isSupported(node)) { - asserted = asserted.add(node.getId()); - } - } - - return asserted; - } - - /** - * Adds a name to the set of names of the context if not a duplicate. - * - * @param name Name to be added to the context's names - * @return true if the name isn't a duplicate false otherwise. - */ - protected boolean addName(String name) { - return this.names.add(name); - } - - /** - * Adds multiple names to this Context - * - * @param names a HashSet of type String of the names to add to this Context - * @return true if one at least one of the names isn't a duplicate false otherwise. - */ - protected boolean addNames(HashSet names) { - return this.names.addAll(names); - } - - /** - * Removes a name from the set of names of the context if present. - * - * @param name Name to be remove from the context's names - * @return true if this is found false otherwise. - */ - protected boolean removeName(String name) { - return this.names.remove(name); - } +public class Context implements Serializable { + private PropositionSet hyps; + + private HashSet names; + + protected BitSet getHypsBitset() { + return hypsBitset; + } + + private BitSet hypsBitset; + + /** + * Constructs a new empty Context + */ + protected Context() { + names = new HashSet(); + this.hyps = new PropositionSet(); + this.hypsBitset = new BitSet(); + } + + /** + * Constructs a new Context given its name + * + * @param contextName the name of the Context to be created + */ + protected Context(String contextName) { + this(); + names.add(contextName); + } + + /** + * Constructs a new Context from another Context + * + * @param c the context that the new Context is constructed from + */ + protected Context(Context c) { + this.hyps = c.getHypothesisSet(); + this.names = c.getNames(); + this.hypsBitset = c.getHypsBitset(); + } + + /** + * Constructs a new Context from a Context and asserts a hypothesis hyp + * in it. + * + * @param c the context to be used for constructing this new Context + * @param hyp the hyp to be asserted in the new Context + * @throws DuplicatePropositionException if the hyp is present in the context c + * @throws NodeNotFoundInNetworkException + */ + protected Context(Context c, int hyp) + throws NotAPropositionNodeException, DuplicatePropositionException, NodeNotFoundInNetworkException { + this.names = c.getNames(); + this.hyps = c.getHypothesisSet().add(hyp); + this.hypsBitset = (BitSet) c.getHypsBitset().clone(); + this.hypsBitset.set(hyp); + } + + /** + * Constructs a new Context from an old Context c, and adds a new name to + * this new Context + * + * @param contextName + * @param c + */ + protected Context(String contextName, Context c) { + this(c); + this.names.add(contextName); + } + + /** + * Constructs a new Context using its name and sets the Context's hyps to a + * passed Proposition set hyps. + * + * @param contextName name of the new Context + * @param hyps the hyps the Context's hyps should be set to + */ + protected Context(String contextName, PropositionSet hyps) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + this(contextName); + this.hyps = hyps; + this.hypsBitset = new BitSet(); + int[] arr = PropositionSet.getPropsSafely(this.hyps); + for (int i = 0; i < arr.length; i++) + this.hypsBitset.set(arr[i]); + } + + /** + * Returns the hyps of this Context + * + * @return a PropositionSet containing the hyps of this Context + */ + public PropositionSet getHypothesisSet() { + return hyps; + } + + /** + * Returns the names of this Context object. + * + * @return a Hashset of type String containing the names of this context. + */ + protected HashSet getNames() { + return names; + } + + public String getName() { + return null; + } + + /** + * Checks if a propositions is asserted in this context + * + * @param p the proposition to be checked for assertion. + * @return true if the proposition exists, otherwise + * false + * @throws NotAPropositionNodeException If the node p is not a proposition. + * @throws NodeNotFoundInNetworkException If the node p doesn't exist in the + * network. + */ + public boolean isAsserted(PropositionNode p) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + int hyp = p.getId(); + + return Arrays.binarySearch(PropositionSet.getPropsSafely(this.hyps), hyp) > 0 || isSupported(p); + } + + public boolean isSupported(PropositionNode node) { + Collection assumptionSet = node.getBasicSupport().getAssumptionBasedSupport().values(); + for (PropositionSet assumptionHyps : assumptionSet) { + if (assumptionHyps.isSubSet(this.hyps)) { + return true; + } + } + return false; + } + + public PropositionSet allAsserted() + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { + Collection allPropositionNodes = Network.getPropositionNodes().values(); + PropositionSet asserted = new PropositionSet(); + int[] hyps; + hyps = PropositionSet.getPropsSafely(this.hyps); + for (PropositionNode node : allPropositionNodes) { + if (Arrays.binarySearch(hyps, node.getId()) > 0) { + asserted = asserted.add(node.getId()); + } else if (isSupported(node)) { + asserted = asserted.add(node.getId()); + } + } + + return asserted; + } + + /** + * Adds a name to the set of names of the context if not a duplicate. + * + * @param name Name to be added to the context's names + * @return true if the name isn't a duplicate false + * otherwise. + */ + protected boolean addName(String name) { + return this.names.add(name); + } + + /** + * Adds multiple names to this Context + * + * @param names a HashSet of type String of the names to add to this Context + * @return true if one at least one of the names isn't a duplicate + * false otherwise. + */ + protected boolean addNames(HashSet names) { + return this.names.addAll(names); + } + + /** + * Removes a name from the set of names of the context if present. + * + * @param name Name to be remove from the context's names + * @return true if this is found false otherwise. + */ + protected boolean removeName(String name) { + return this.names.remove(name); + } } \ No newline at end of file diff --git a/src/sneps/snip/Filter.java b/src/sneps/snip/Filter.java index bffc3773..31e4759a 100644 --- a/src/sneps/snip/Filter.java +++ b/src/sneps/snip/Filter.java @@ -1,5 +1,6 @@ package sneps.snip; +import sneps.network.VariableNode; import sneps.snip.matching.Binding; import sneps.snip.matching.LinearSubstitutions; import sneps.snip.matching.Substitutions; @@ -28,10 +29,10 @@ public boolean equals(Object filter) { } public boolean canPass(Report report) { - for (int i = 0; i < this.substitutions.cardinality(); i++) { + for (int i = 0; i < substitutions.cardinality(); i++) { Binding currentFilterBinding = substitutions.getBinding(i); - Binding currentReportBinding = report.getSubstitutions() - .getBindingByVariable(currentFilterBinding.getVariableNode()); + VariableNode currentFilterVariableNode = currentFilterBinding.getVariableNode(); + Binding currentReportBinding = report.getSubstitutions().getBindingByVariable(currentFilterVariableNode); System.out.println("Bindings " + currentFilterBinding + " " + report.getSubstitutions()); if (currentReportBinding != null && currentFilterBinding.getNode() != currentReportBinding.getNode()) return false; diff --git a/src/sneps/snip/Report.java b/src/sneps/snip/Report.java index 01cedc44..00f4d133 100644 --- a/src/sneps/snip/Report.java +++ b/src/sneps/snip/Report.java @@ -1,17 +1,19 @@ package sneps.snip; +import java.util.Hashtable; import java.util.Set; +import sneps.network.classes.setClasses.PropositionSet; import sneps.snebr.Support; import sneps.snip.matching.Substitutions; public class Report { private Substitutions substitution; - private Set supports; + private Hashtable supports; private boolean sign; private String contextName; - public Report(Substitutions substitution, Set set, boolean sign, String contextID) { + public Report(Substitutions substitution, Hashtable set, boolean sign, String contextID) { this.substitution = substitution; this.supports = set; this.sign = sign; @@ -22,7 +24,7 @@ public Substitutions getSubstitutions() { return substitution; } - public Set getSupports() { + public Hashtable getSupports() { return supports; } diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index 6ae2ba01..bf4b2ea4 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -46,6 +46,7 @@ public Channel(Substitutions switcherSubstitution, Substitutions filterSubstitut public boolean testReportToSend(Report report) { boolean passTest = filter.canPass(report); System.out.println("Can pass " + passTest); + .passTest. /*Test the context name if it will pass or not*/ if (passTest && contextName.equals(report.getContextName())) { System.out.println("\n\nThe switcher data:\n" + switcher); switcher.switchReport(report); diff --git a/src/sneps/snip/classes/FlagNode.java b/src/sneps/snip/classes/FlagNode.java index 3ebb170c..00d40794 100644 --- a/src/sneps/snip/classes/FlagNode.java +++ b/src/sneps/snip/classes/FlagNode.java @@ -1,14 +1,16 @@ package sneps.snip.classes; +import java.util.Hashtable; import java.util.Set; import sneps.network.Node; +import sneps.network.classes.setClasses.PropositionSet; import sneps.snebr.Support; public class FlagNode { private Node node; - private Set supports; + private Hashtable supports; private int flag; /** @@ -16,14 +18,14 @@ public class FlagNode { * * @param n * node - * @param set + * @param hashtable * support * @param f * true or false */ - public FlagNode(Node n, Set set, int f) { + public FlagNode(Node n, Hashtable hashtable, int f) { node = n; - supports = set; + supports = hashtable; flag = f; } @@ -41,7 +43,7 @@ public Node getNode() { * * @return support */ - public Set getSupports() { + public Hashtable getSupports() { return supports; } diff --git a/src/sneps/snip/classes/VariableNodeStats.java b/src/sneps/snip/classes/VariableNodeStats.java new file mode 100644 index 00000000..164f88de --- /dev/null +++ b/src/sneps/snip/classes/VariableNodeStats.java @@ -0,0 +1,61 @@ +package sneps.snip.classes; + +import java.util.Vector; + +import sneps.snip.matching.Binding; +import sneps.snip.matching.LinearSubstitutions; +import sneps.snip.matching.Substitutions; + +public class VariableNodeStats { + private boolean allVariablesBound; + private Substitutions referenceSubs; + private int nodeId; + private Vector variableNodeSubs; + + public VariableNodeStats(boolean variablesBound, Vector extractedFilterRelevantToVariables, + Substitutions refSubs, int id) { + allVariablesBound = variablesBound; + variableNodeSubs = extractedFilterRelevantToVariables; + referenceSubs = refSubs; + nodeId = id; + } + + public VariableNodeStats(boolean variablesBound, Vector extractedFilterRelevantToVariables, + Substitutions refSubs) { + allVariablesBound = variablesBound; + variableNodeSubs = extractedFilterRelevantToVariables; + referenceSubs = refSubs; + } + + public Substitutions getReferenceSubs() { + return referenceSubs; + } + + public void setReferenceSubs(Substitutions referenceSubs) { + this.referenceSubs = referenceSubs; + } + + public int getNodeId() { + return nodeId; + } + + public void setNodeId(int nodeId) { + this.nodeId = nodeId; + } + + public boolean areAllVariablesBound() { + return allVariablesBound; + } + + public void setAllVariablesBound(boolean allVariablesBound) { + this.allVariablesBound = allVariablesBound; + } + + public Vector getVariableNodeSubs() { + return variableNodeSubs; + } + + public void setVariableNodeSubs(Vector variableNodeSubs) { + this.variableNodeSubs = variableNodeSubs; + } +} diff --git a/src/sneps/snip/matching/LinearSubstitutions.java b/src/sneps/snip/matching/LinearSubstitutions.java index e500e94b..51ce0038 100644 --- a/src/sneps/snip/matching/LinearSubstitutions.java +++ b/src/sneps/snip/matching/LinearSubstitutions.java @@ -6,6 +6,7 @@ import sneps.network.VariableNode; import sneps.network.classes.setClasses.VariableSet; import sneps.network.classes.term.Variable; +import sneps.snip.classes.VariableNodeStats; public class LinearSubstitutions implements Substitutions { private Vector sub; @@ -451,24 +452,29 @@ public void insertOrUpdate(Binding mb) { } - /** - * Method to iterate over all variables in the Vector to check for - * their bound status + /*** + * Method checking the freeVariables Set making sure each has a compatible + * Binding in the instance Vector + * + * @param freeVariables VariableSet + * + * @return VariableNodeStats */ - public boolean eachBound(VariableSet freeVariables) { - boolean condition = true; + public VariableNodeStats extractBoundStatus(VariableSet freeVariables) { + boolean forAllCondition = true; + Vector extractedFilterRelevantToVariables = new Vector(); for (Binding binding : sub) { - VariableSet bindingFreeVariables = binding.getVariableNode().getFreeVariables(); - for (Variable bindVariable : bindingFreeVariables) { - - } + VariableNode bindingVariableNode = binding.getVariableNode(); + boolean bindingFound = false; for (Variable variable : freeVariables) { - - String variableIdentifier = variable.getIdentifier(); - + Variable bindingVariable = (Variable) bindingVariableNode.getTerm(); + bindingFound |= variable.equals(bindingVariable); } + if (bindingFound) + extractedFilterRelevantToVariables.add(binding); + forAllCondition &= bindingFound; } - return condition; + return new VariableNodeStats(forAllCondition, extractedFilterRelevantToVariables, this); } diff --git a/src/sneps/snip/matching/Substitutions.java b/src/sneps/snip/matching/Substitutions.java index 34c01423..0ee95a7e 100644 --- a/src/sneps/snip/matching/Substitutions.java +++ b/src/sneps/snip/matching/Substitutions.java @@ -3,6 +3,7 @@ import sneps.network.Node; import sneps.network.VariableNode; import sneps.network.classes.setClasses.VariableSet; +import sneps.snip.classes.VariableNodeStats; public interface Substitutions { @@ -66,6 +67,6 @@ public interface Substitutions { public void insertOrUpdate(Binding mb); - public boolean eachBound(VariableSet freeVariables); + public VariableNodeStats extractBoundStatus(VariableSet freeVariables); } diff --git a/src/sneps/snip/rules/OrNode.java b/src/sneps/snip/rules/OrNode.java index a61ee28b..f00c68f9 100644 --- a/src/sneps/snip/rules/OrNode.java +++ b/src/sneps/snip/rules/OrNode.java @@ -16,32 +16,29 @@ public class OrNode extends RuleNode { - private int ant,cq; - + private int ant, cq; public OrNode(Term syn) { super(syn); ant = getDownNodeSet("ant").size(); cq = getDownNodeSet("cq").size(); } - + public void applyRuleHandler(Report report, Node node) { - - if(report.isPositive()) { - + + if (report.isPositive()) { + Support originSupports = this.getBasicSupport(); HashSet sup = new HashSet(); sup.add(originSupports); Report reply = new Report(report.getSubstitutions(), sup, true, report.getContextName()); - + for (Channel outChannel : outgoingChannels) outChannel.testReportToSend(reply); - + } - -} - + } @Override public NodeSet getDownAntNodeSet() { @@ -62,7 +59,7 @@ public NodeSet getDownAntNodeSet() { @Override protected void sendRui(RuleUseInfo tRui, String contextID) { // TODO Auto-generated method stub - + } } From 95e165deed8d13f4f89fa466fe3e97dea179fb0f Mon Sep 17 00:00:00 2001 From: Youssef Date: Sat, 27 Apr 2019 00:24:01 +0200 Subject: [PATCH 09/22] changed OrNode support type to Hashtable, fixed isWhQuestion to use computeNodeStats for similar logic --- src/sneps/network/Node.java | 22 ++++++++++++------- src/sneps/snip/classes/VariableNodeStats.java | 6 +++++ src/sneps/snip/rules/OrNode.java | 4 +++- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java index 0f1f6ffe..8a75d3b9 100644 --- a/src/sneps/network/Node.java +++ b/src/sneps/network/Node.java @@ -206,15 +206,21 @@ public NodeSet getDominatingRules() { return ret; } + /*** + * Checking if this node instance contains not yet bound free variables + * + * @param filterSubs reference substitutions + * @return boolean computed from VariableNodeStats.areAllVariablesBound() + */ public boolean isWhQuestion(Substitutions filterSubs) { - if (!(this instanceof VariableNode)) - return false; - /* change sizes check as they are no longer important */.IMP. - VariableNode node = (VariableNode) this; - VariableSet variables = node.getFreeVariables(); - int variablesCardn = variables.size(); - int filterCardn = filterSubs.cardinality(); - return filterCardn < variablesCardn; + VariableNodeStats currentNodeStats = computeNodeStats(filterSubs); + return !currentNodeStats.areAllVariablesBound(); + /* + * if (!(this instanceof VariableNode)) return false; VariableNode node = + * (VariableNode) this; VariableSet variables = node.getFreeVariables(); int + * variablesCardn = variables.size(); int filterCardn = + * filterSubs.cardinality(); return filterCardn < variablesCardn; + */ } /*** diff --git a/src/sneps/snip/classes/VariableNodeStats.java b/src/sneps/snip/classes/VariableNodeStats.java index 164f88de..6c551910 100644 --- a/src/sneps/snip/classes/VariableNodeStats.java +++ b/src/sneps/snip/classes/VariableNodeStats.java @@ -43,6 +43,12 @@ public void setNodeId(int nodeId) { this.nodeId = nodeId; } + /*** + * Method returns whether all freeVariables concerning this node are bound + * through the origin substitutions or not + * + * @return boolean + */ public boolean areAllVariablesBound() { return allVariablesBound; } diff --git a/src/sneps/snip/rules/OrNode.java b/src/sneps/snip/rules/OrNode.java index f00c68f9..9f794c9b 100644 --- a/src/sneps/snip/rules/OrNode.java +++ b/src/sneps/snip/rules/OrNode.java @@ -1,12 +1,14 @@ package sneps.snip.rules; import java.util.HashSet; +import java.util.Hashtable; import java.util.Set; import sneps.network.Node; import sneps.network.RuleNode; import sneps.network.classes.Semantic; import sneps.network.classes.setClasses.NodeSet; +import sneps.network.classes.setClasses.PropositionSet; import sneps.network.PropositionNode; import sneps.network.classes.term.Term; import sneps.snebr.Support; @@ -29,7 +31,7 @@ public void applyRuleHandler(Report report, Node node) { if (report.isPositive()) { Support originSupports = this.getBasicSupport(); - HashSet sup = new HashSet(); + Hashtable sup = new Hashtable(); sup.add(originSupports); Report reply = new Report(report.getSubstitutions(), sup, true, report.getContextName()); From ce2f44360601a69f311c58ec645d492d18f714ae Mon Sep 17 00:00:00 2001 From: Youssef Date: Sat, 27 Apr 2019 00:39:06 +0200 Subject: [PATCH 10/22] combined last two cases for RuleNode processRequests before deletion --- src/sneps/network/PropositionNode.java | 1 - src/sneps/network/RuleNode.java | 24 ++++++++++++++++++------ 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 2e6b0e84..673d506e 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -233,7 +233,6 @@ public void processSingleRequestsChannel(Channel currentChannel) PropositionSet propSet = new PropositionSet(); propSet.add(instanceNodeId); Hashtable nodeAssumptionBasedSupport = getAssumptionBasedSupport(); - String currentContextName = currentChannel.getContextName(); Context desiredContext = Controller.getContextByName(currentContextName); if (assertedInContext(desiredContext)) { diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index f837439d..edcaa37f 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -346,19 +346,31 @@ public void processSingleRequestsChannel(Channel currentChannel) Substitutions reportSubstitutions = report.getSubstitutions(); VariableNodeStats reportNodeStats = computeNodeStats(reportSubstitutions); Vector reportNodeExtractedSubs = reportNodeStats.getVariableNodeSubs(); - if (ruleNodeExtractedSubs.size() == reportNodeExtractedSubs.size() - && anySupportAssertedInContext(report)) { + boolean caseCondition = ruleNodeAllVariablesBound + ? reportNodeExtractedSubs.size() == ruleNodeExtractedSubs.size() + : reportNodeExtractedSubs.size() < ruleNodeExtractedSubs.size(); + if (caseCondition && anySupportAssertedInContext(report)) { requestAntecedentsNotAlreadyWorkingOn(currentChannel); - return; + if (ruleNodeAllVariablesBound) + return; } } super.processSingleRequestsChannel(currentChannel); return; } else { /* Case 3 */ - // Case 3: fih one free variale le kol instance hab3at lel antecedents request - // bel filter beta3 each istance while checking if alreadyWorking on it, we call - // super.proccessSingle + // Case 3: fih one free variable le kol instance hab3at lel antecedents request + // bel filter beta3 each istance while checking if alreadyWorking on it + ReportSet knownReportSet = knownInstances; + for (Report report : knownReportSet) { + Substitutions reportSubstitutions = report.getSubstitutions(); + VariableNodeStats reportNodeStats = computeNodeStats(reportSubstitutions); + Vector reportNodeExtractedSubs = reportNodeStats.getVariableNodeSubs(); + if (reportNodeExtractedSubs.size() < ruleNodeExtractedSubs.size() + && anySupportAssertedInContext(report)) { + requestAntecedentsNotAlreadyWorkingOn(currentChannel); + } + } super.processSingleRequestsChannel(currentChannel); } From 24a649ed26d75484e1c7268bcc470884986947cf Mon Sep 17 00:00:00 2001 From: Youssef Date: Sat, 27 Apr 2019 01:17:51 +0200 Subject: [PATCH 11/22] applied modifications for latest cases in processRequestsChannel --- src/sneps/network/RuleNode.java | 50 ++++++++++----------------------- 1 file changed, 15 insertions(+), 35 deletions(-) diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index edcaa37f..7318f138 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -339,46 +339,26 @@ public void processSingleRequestsChannel(Channel currentChannel) VariableNodeStats ruleNodeStats = computeNodeStats(filterSubs); boolean ruleNodeAllVariablesBound = ruleNodeStats.areAllVariablesBound(); Vector ruleNodeExtractedSubs = ruleNodeStats.getVariableNodeSubs(); - if (ruleNodeAllVariablesBound) { - /* Case 2 */ - ReportSet knownReportSet = knownInstances; - for (Report report : knownReportSet) { - Substitutions reportSubstitutions = report.getSubstitutions(); - VariableNodeStats reportNodeStats = computeNodeStats(reportSubstitutions); - Vector reportNodeExtractedSubs = reportNodeStats.getVariableNodeSubs(); - boolean caseCondition = ruleNodeAllVariablesBound - ? reportNodeExtractedSubs.size() == ruleNodeExtractedSubs.size() - : reportNodeExtractedSubs.size() < ruleNodeExtractedSubs.size(); - if (caseCondition && anySupportAssertedInContext(report)) { - requestAntecedentsNotAlreadyWorkingOn(currentChannel); - if (ruleNodeAllVariablesBound) - return; - } + /* Case 2 & 3 */ + ReportSet knownReportSet = knownInstances; + for (Report report : knownReportSet) { + Substitutions reportSubstitutions = report.getSubstitutions(); + VariableNodeStats reportNodeStats = computeNodeStats(reportSubstitutions); + Vector reportNodeExtractedSubs = reportNodeStats.getVariableNodeSubs(); + boolean caseCondition = ruleNodeAllVariablesBound + ? reportNodeExtractedSubs.size() == ruleNodeExtractedSubs.size() + : reportNodeExtractedSubs.size() < ruleNodeExtractedSubs.size(); + if (caseCondition && anySupportAssertedInContext(report)) { + requestAntecedentsNotAlreadyWorkingOn(currentChannel); + if (ruleNodeAllVariablesBound) + return; } - super.processSingleRequestsChannel(currentChannel); - return; - } else { - /* Case 3 */ - // Case 3: fih one free variable le kol instance hab3at lel antecedents request - // bel filter beta3 each istance while checking if alreadyWorking on it - ReportSet knownReportSet = knownInstances; - for (Report report : knownReportSet) { - Substitutions reportSubstitutions = report.getSubstitutions(); - VariableNodeStats reportNodeStats = computeNodeStats(reportSubstitutions); - Vector reportNodeExtractedSubs = reportNodeStats.getVariableNodeSubs(); - if (reportNodeExtractedSubs.size() < ruleNodeExtractedSubs.size() - && anySupportAssertedInContext(report)) { - requestAntecedentsNotAlreadyWorkingOn(currentChannel); - } - } - super.processSingleRequestsChannel(currentChannel); } - + super.processSingleRequestsChannel(currentChannel); + return; } - } else super.processSingleRequestsChannel(currentChannel); - } // PROCESS REPORT : 3adi -> outgoing channels node we ab3at accordingly, forard From c067af3077e4b0f0f1ab5b10c32d4560b656576a Mon Sep 17 00:00:00 2001 From: Youssef Date: Thu, 2 May 2019 19:58:22 +0200 Subject: [PATCH 12/22] finalized handling requests before May's feedback --- src/sneps/network/PropositionNode.java | 227 ++++++++++++++----------- src/sneps/network/RuleNode.java | 103 ++++++----- src/sneps/snip/Report.java | 31 ++-- src/sneps/snip/channels/Channel.java | 13 +- src/sneps/snip/classes/FlagNode.java | 31 ++-- src/sneps/snip/rules/OrNode.java | 11 +- 6 files changed, 228 insertions(+), 188 deletions(-) diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 673d506e..4dcdc0ac 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -2,6 +2,7 @@ import java.io.Serializable; import java.util.ArrayList; +import java.util.Collection; import java.util.HashSet; import sneps.exceptions.CannotInsertJustificationSupportException; @@ -67,28 +68,39 @@ public PropositionNode(Term trm) { */ public void broadcastReport(Report report) { for (Channel outChannel : outgoingChannels) { - if (outChannel.testReportToSend(report)) { - // System.out.println("SENDING REPORT " + this); + try { + if (outChannel.testReportToSend(report)) { + // System.out.println("SENDING REPORT " + this); + } + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } } } public boolean sendReport(Report report, Channel channel) { - if (channel.testReportToSend(report)) { - // System.out.println("SENDING REPORT " + this); - return true; + try { + if (channel.testReportToSend(report)) { + // System.out.println("SENDING REPORT " + this); + return true; + } + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } return false; } - protected void sendReports(NodeSet isAntecedentTo, ReportSet reports, ChannelTypes channelType) { + private void sendReports(NodeSet isAntecedentTo, ReportSet reports, ChannelTypes channelType, + Channel currentChannel) { for (Node node : isAntecedentTo) { for (Report report : reports) { Substitutions reportSubs = report.getSubstitutions(); - Hashtable reportSuppSet = report.getSupports(); + Collection reportSuppSet = report.getSupports(); boolean reportSign = report.getSign(); - String reportContextName = report.getContextName(); - Channel newChannel = establishChannel(channelType, node, null, reportSubs, reportContextName, + String currentChannelContextName = currentChannel.getContextName(); + Channel newChannel = establishChannel(channelType, node, null, reportSubs, currentChannelContextName, InferenceTypes.FORWARD, -1); outgoingChannels.addChannel(newChannel); node.receiveReport(newChannel); @@ -97,17 +109,17 @@ protected void sendReports(NodeSet isAntecedentTo, ReportSet reports, ChannelTyp } - protected void sendReports(List list, ReportSet reports) { + private void sendReports(List list, ReportSet reports, Channel currentChannel) { for (Match match : list) { for (Report report : reports) { Substitutions reportSubs = report.getSubstitutions(); - Hashtable reportSuppSet = report.getSupports(); + Collection reportSuppSet = report.getSupports(); Node sentTo = match.getNode(); boolean reportSign = report.getSign(); - String reportContextName = report.getContextName(); + String currentChannelContextName = currentChannel.getContextName(); int matchType = match.getMatchType(); - Channel newChannel = establishChannel(ChannelTypes.MATCHED, sentTo, null, reportSubs, reportContextName, - InferenceTypes.FORWARD, matchType); + Channel newChannel = establishChannel(ChannelTypes.MATCHED, sentTo, null, reportSubs, + currentChannelContextName, InferenceTypes.FORWARD, matchType); outgoingChannels.addChannel(newChannel); sentTo.receiveReport(newChannel); } @@ -122,49 +134,67 @@ protected void sendReports(List list, ReportSet reports) { * @param currentElement source Node/Match element being addressed * @param switchSubs mapped substitutions from origin node * @param filterSubs constraints substitutions for a specific request - * @param contextId context name used + * @param contextName context name used * @param inferenceType inference type used for this process * @param matchType int representing the match Type. -1 if not a matching * node scenario * @return the established type based channel */ - protected Channel establishChannel(ChannelTypes type, Object currentElement, Substitutions switchSubs, - Substitutions filterSubs, String contextId, InferenceTypes inferenceType, int matchType) { + private Channel establishChannel(ChannelTypes type, Object currentElement, Substitutions switchSubs, + Substitutions filterSubs, String contextName, InferenceTypes inferenceType, int matchType) { boolean matchTypeEstablishing = currentElement instanceof Match; Node evaluatedReporter = matchTypeEstablishing ? ((Match) currentElement).getNode() : (Node) currentElement; Substitutions switchLinearSubs = switchSubs == null ? new LinearSubstitutions() : switchSubs; Channel newChannel; switch (type) { case MATCHED: - newChannel = new MatchChannel(switchLinearSubs, filterSubs, contextId, this, evaluatedReporter, true, + newChannel = new MatchChannel(switchLinearSubs, filterSubs, contextName, this, evaluatedReporter, true, inferenceType, matchType); break; case RuleAnt: - newChannel = new AntecedentToRuleChannel(switchLinearSubs, filterSubs, contextId, this, evaluatedReporter, + newChannel = new AntecedentToRuleChannel(switchLinearSubs, filterSubs, contextName, this, evaluatedReporter, true, inferenceType); default: - newChannel = new RuleToConsequentChannel(switchLinearSubs, filterSubs, contextId, this, evaluatedReporter, + newChannel = new RuleToConsequentChannel(switchLinearSubs, filterSubs, contextName, this, evaluatedReporter, true, inferenceType); } return newChannel; } - public void sendRequests(List list, String contextId, ChannelTypes channelType, - InferenceTypes inferenceType) { + /*** + * Helper method responsible for establishing channels between this current node + * and each of the List to further request instances with the given + * inputs + * + * @param list + * @param contextId + * @param inferenceType + */ + protected void sendRequestsToMatches(List list, String contextId, InferenceTypes inferenceType) { for (Match currentMatch : list) { Substitutions switchSubs = currentMatch.getSwitchSubs(); Substitutions filterSubs = currentMatch.getFilterSubs(); int matchType = currentMatch.getMatchType(); - Channel newChannel = establishChannel(channelType, currentMatch, switchSubs, filterSubs, contextId, + Channel newChannel = establishChannel(ChannelTypes.MATCHED, currentMatch, switchSubs, filterSubs, contextId, inferenceType, matchType); incomingChannels.addChannel(newChannel); currentMatch.getNode().receiveRequest(newChannel); } } - public void sendRequests(NodeSet ns, Substitutions filterSubs, String contextID, ChannelTypes channelType, - InferenceTypes inferenceType) { + /*** + * Helper method responsible for establishing channels between this current node + * and each of the NodeSet to further request instances with the given inputs + * + * @param ns NodeSet to be sent to + * @param filterSubs Substitutions to be passed + * @param contextID latest channel context + * @param channelType + * @param inferenceType + */ + protected void sendRequestsToNodeSet(NodeSet ns, Substitutions filterSubs, String contextID, + ChannelTypes channelType, InferenceTypes inferenceType) { for (Node sentTo : ns) { Channel newChannel = establishChannel(channelType, sentTo, null, filterSubs, contextID, inferenceType, -1); incomingChannels.addChannel(newChannel); @@ -172,50 +202,15 @@ public void sendRequests(NodeSet ns, Substitutions filterSubs, String contextID, } } - /*** - * Report handling in Non-Rule proposition nodes. - * - * @param currentChannel - */ - public void processSingleReportsChannel(Channel currentChannel) { - ReportSet reports = currentChannel.getReportsBuffer(); - for (Report currentReport : reports) { - - Substitutions reportSubs = currentReport.getSubstitutions(); - Hashtable reportSupportSet = currentReport.getSupports(); - boolean reportSign = currentReport.isPositive(); - String reportContextName = currentReport.getContextName(); - boolean toBeSentFlag = true; - if (currentChannel instanceof MatchChannel) { - int channelMatchType = ((MatchChannel) currentChannel).getMatchType(); - toBeSentFlag = (channelMatchType == 0) || (channelMatchType == 1 && currentReport.isPositive()) - || (channelMatchType == 2 && currentReport.isNegative()); + public void processRequests() { + for (Channel outChannel : outgoingChannels) + try { + processSingleRequestsChannel(outChannel); + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { + e.printStackTrace(); + } catch (DuplicatePropositionException e) { + e.printStackTrace(); } - Report alteredReport = new Report(reportSubs, reportSupportSet, reportSign, reportContextName); - if (knownInstances.contains(alteredReport)) - continue; - if (toBeSentFlag) - broadcastReport(alteredReport); - currentChannel.clearReportsBuffer(); - } - /* Handling forward inference broadcasting */ - if (currentChannel.getInferenceType() == InferenceTypes.FORWARD) { - List matchesReturned = Matcher.match(this); - if (matchesReturned != null) - sendReports(matchesReturned, reports); - NodeSet isAntecedentTo = getDominatingRules(); - sendReports(isAntecedentTo, reports, ChannelTypes.RuleAnt); - } - currentChannel.clearReportsBuffer(); - } - - // PROCESS REPORT : 3adi -> , forward - // -> same as 3adi , plus matching to send and get the nodes el howa lihom - // antecedents we send reports - - public void processReports() { - for (Channel inChannel : incomingChannels) - processSingleReportsChannel(inChannel); } /*** @@ -226,21 +221,20 @@ public void processReports() { * @throws NotAPropositionNodeException * @throws DuplicatePropositionException */ - public void processSingleRequestsChannel(Channel currentChannel) + protected void processSingleRequestsChannel(Channel currentChannel) throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { // TODO check correctness int instanceNodeId = getId(); PropositionSet propSet = new PropositionSet(); propSet.add(instanceNodeId); - Hashtable nodeAssumptionBasedSupport = getAssumptionBasedSupport(); + Collection nodeAssumptionBasedSupport = getAssumptionBasedSupport().values(); String currentContextName = currentChannel.getContextName(); Context desiredContext = Controller.getContextByName(currentContextName); if (assertedInContext(desiredContext)) { // TODO change the subs to hashsubs - Hashtable support = new Hashtable(); -// support.put("1", propSet); - Report reply = new Report(new LinearSubstitutions(), nodeAssumptionBasedSupport, true, - currentChannel.getContextName()); + Collection support = new ArrayList(); + support.add(propSet); + Report reply = new Report(new LinearSubstitutions(), nodeAssumptionBasedSupport, true); knownInstances.addReport(reply); broadcastReport(reply); } else { @@ -250,14 +244,13 @@ public void processSingleRequestsChannel(Channel currentChannel) Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); if (!sentAtLeastOne || isWhQuestion(filterSubs)) { NodeSet dominatingRules = getDominatingRules(); - NodeSet toBeSentToDom = alreadyWorking(dominatingRules, currentChannel, false); - sendRequests(toBeSentToDom, new LinearSubstitutions(), currentContextName, ChannelTypes.RuleAnt, - currentChannel.getInferenceType()); + NodeSet toBeSentToDom = removeAlreadyWorkingOn(dominatingRules, currentChannel, false); + sendRequestsToNodeSet(toBeSentToDom, new LinearSubstitutions(), currentContextName, + ChannelTypes.RuleAnt, currentChannel.getInferenceType()); if (!(currentChannel instanceof MatchChannel)) { List matchingNodes = Matcher.match(this); - List toBeSentToMatch = alreadyWorking(matchingNodes, currentChannel, false); - sendRequests(toBeSentToMatch, currentContextName, ChannelTypes.MATCHED, - currentChannel.getInferenceType()); + List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel, false); + sendRequestsToMatches(toBeSentToMatch, currentContextName, currentChannel.getInferenceType()); } /* * if (!(currentChannel instanceof MatchChannel)) // was in !alreadyWorking if @@ -268,6 +261,50 @@ public void processSingleRequestsChannel(Channel currentChannel) } } + public void processReports() { + for (Channel inChannel : incomingChannels) + processSingleReportsChannel(inChannel); + } + + /*** + * Report handling in Non-Rule proposition nodes. + * + * @param currentChannel + */ + protected void processSingleReportsChannel(Channel currentChannel) { + ReportSet reports = currentChannel.getReportsBuffer(); + for (Report currentReport : reports) { + Substitutions reportSubs = currentReport.getSubstitutions(); + Collection reportSupportSet = currentReport.getSupports(); + boolean reportSign = currentReport.isPositive(); + String currentChannelContextName = currentChannel.getContextName(); + boolean toBeSentFlag = true; + if (currentChannel instanceof MatchChannel) { + int channelMatchType = ((MatchChannel) currentChannel).getMatchType(); + toBeSentFlag = (channelMatchType == 0) || (channelMatchType == 1 && currentReport.isPositive()) + || (channelMatchType == 2 && currentReport.isNegative()); + } + Report alteredReport = new Report(reportSubs, reportSupportSet, reportSign); + if (knownInstances.contains(alteredReport)) + continue; + if (toBeSentFlag) + broadcastReport(alteredReport); + } + /* Handling forward inference broadcasting */ + if (currentChannel.getInferenceType() == InferenceTypes.FORWARD) { + List matchesReturned = Matcher.match(this); + if (matchesReturned != null) + sendReports(matchesReturned, reports, currentChannel); + NodeSet isAntecedentTo = getDominatingRules(); + sendReports(isAntecedentTo, reports, ChannelTypes.RuleAnt, currentChannel); + } + currentChannel.clearReportsBuffer(); + } + + // PROCESS REPORT : 3adi -> , forward + // -> same as 3adi , plus matching to send and get the nodes el howa lihom + // antecedents we send reports + /*** * * @param desiredContext @@ -285,17 +322,6 @@ public boolean assertedInContext(String desiredContextName) return Controller.getContextByName(desiredContextName).isAsserted(this); } - public void processRequests() { - for (Channel outChannel : outgoingChannels) - try { - processSingleRequestsChannel(outChannel); - } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { - e.printStackTrace(); - } catch (DuplicatePropositionException e) { - e.printStackTrace(); - } - } - /*** * Requests received added to the low priority queue to be served accordingly * through the runner. @@ -343,13 +369,13 @@ protected void getNodesToSendRequests(ChannelTypes channelType, String currentCo case MATCHED: List matchesReturned = Matcher.match(this); if (matchesReturned != null) - sendRequests(matchesReturned, currentContextName, channelType, inferenceType); + sendRequestsToMatches(matchesReturned, currentContextName, inferenceType); break; case RuleCons: NodeSet dominatingRules = getDominatingRules(); // TODO Youssef: check if passing a new LinearSubstitutions is correct Substitutions linearSubs = substitutions == null ? new LinearSubstitutions() : substitutions; - sendRequests(dominatingRules, linearSubs, currentContextName, channelType, inferenceType); + sendRequestsToNodeSet(dominatingRules, linearSubs, currentContextName, channelType, inferenceType); break; default: break; @@ -360,7 +386,18 @@ protected void getNodesToSendRequests(ChannelTypes channelType, String currentCo } - public List alreadyWorking(List matchingNodes, Channel currentChannel, boolean ruleType) { + /*** + * Method comparing opened incoming channels over each match's node of the + * matches whether a more generic request of the specified channel was + * previously sent in order not to re-send redundant requests -- ruleType gets + * applied on Andor or Thresh part. + * + * @param matchingNodes + * @param currentChannel + * @param ruleType + * @return + */ + protected List removeAlreadyWorkingOn(List matchingNodes, Channel currentChannel, boolean ruleType) { List nodesToConsider = new ArrayList(); for (Match sourceMatch : matchingNodes) { Node sourceNode = sourceMatch.getNode(); @@ -395,7 +432,7 @@ public List alreadyWorking(List matchingNodes, Channel currentChan * @return NodeSet containing all nodes that has not previously requested the * subset of the specified channel request */ - public static NodeSet alreadyWorking(NodeSet nodes, Channel channel, boolean ruleType) { + protected static NodeSet removeAlreadyWorkingOn(NodeSet nodes, Channel channel, boolean ruleType) { NodeSet nodesToConsider = new NodeSet(); for (Node sourceNode : nodes) if (sourceNode instanceof PropositionNode) { diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index 7318f138..c78b11aa 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -107,17 +107,18 @@ protected void processNodes(NodeSet antNodes) { sharedVars = getSharedVarsInts(antNodesWithVars); } - public void applyRuleHandler(Report report, Node signature) { - String contextID = report.getContextName(); + public void applyRuleHandler(Report report, Channel currentChannel) { + Node currentChannelReporter = currentChannel.getReporter(); + String contextID = currentChannel.getContextName(); // Context context = SNeBR.getContextByID(contextID); RuleUseInfo rui; if (report.isPositive()) { - FlagNode fn = new FlagNode(signature, report.getSupports(), 1); + FlagNode fn = new FlagNode(currentChannelReporter, report.getSupports(), 1); FlagNodeSet fns = new FlagNodeSet(); fns.putIn(fn); rui = new RuleUseInfo(report.getSubstitutions(), 1, 0, fns); } else { - FlagNode fn = new FlagNode(signature, report.getSupports(), 2); + FlagNode fn = new FlagNode(currentChannelReporter, report.getSupports(), 2); FlagNodeSet fns = new FlagNodeSet(); fns.putIn(fn); rui = new RuleUseInfo(report.getSubstitutions(), 0, 1, fns); @@ -263,7 +264,34 @@ public static boolean isConstantNode(Node n) { return !(n instanceof VariableNode) || n instanceof RuleNode || ((VariableNode) n).getFreeVariables().isEmpty(); } - @Override + protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel) { + NodeSet antecedentNodeSet = getDownAntNodeSet(); + boolean ruleType = this instanceof ThreshNode || this instanceof AndOrNode; + NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentNodeSet, currentChannel, ruleType); + sendRequestsToNodeSet(toBeSentTo, currentChannel.getFilter().getSubstitutions(), + currentChannel.getContextName(), ChannelTypes.RuleAnt, currentChannel.getInferenceType()); + } + + protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel, Report report) { + NodeSet antecedentNodeSet = getDownAntNodeSet(); + boolean ruleType = this instanceof ThreshNode || this instanceof AndOrNode; + NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentNodeSet, currentChannel, ruleType); + sendRequestsToNodeSet(toBeSentTo, report.getSubstitutions(), currentChannel.getContextName(), + ChannelTypes.RuleAnt, currentChannel.getInferenceType()); + + } + + /* + * Check error in Context public boolean anySupportAssertedInContext(Report + * report) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + * String reportContextName = report.getContextName(); Set + * reportSupports = report.getSupports(); for (Support support : reportSupports) + * { int supportId = support.getId(); PropositionNode supportNode = + * (PropositionNode) Network.getNodeById(supportId); if + * (supportNode.assertedInContext(reportContextName)) return true; } return + * false; } + */ + public void processRequests() { for (Channel outChannel : outgoingChannels) try { @@ -275,43 +303,6 @@ public void processRequests() { } } - public void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel) { - NodeSet antecedentNodeSet = getDownAntNodeSet(); - boolean ruleType = this instanceof ThreshNode || this instanceof AndOrNode; - NodeSet toBeSentTo = alreadyWorking(antecedentNodeSet, currentChannel, ruleType); - sendRequests(toBeSentTo, currentChannel.getFilter().getSubstitutions(), currentChannel.getContextName(), - ChannelTypes.RuleAnt, currentChannel.getInferenceType()); - } - - /* Check error in COntext */ -// public boolean anySupportAssertedInContext(Report report) -// throws NotAPropositionNodeException, NodeNotFoundInNetworkException { -// String reportContextName = report.getContextName(); -// Set reportSupports = report.getSupports(); -// for (Support support : reportSupports) { -// int supportId = support.getId(); -// PropositionNode supportNode = (PropositionNode) Network.getNodeById(supportId); -// if (supportNode.assertedInContext(reportContextName)) -// return true; -// } -// return false; -// } - - public boolean anySupportAssertedInContext(Report report) - throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - String reportContextName = report.getContextName(); - Context reportContext = Controller.getContextByName(reportContextName); - Hashtable reportSupports = report.getSupports(); - PropositionSet contextHypothesisSet = reportContext.getHypothesisSet(); - Collection reportSupportsSet = reportSupports.values(); - for (PropositionSet assumptionHyps : reportSupportsSet) { - if (assumptionHyps.isSubSet(contextHypothesisSet)) { - return true; - } - } - return false; - } - /*** * Request handling in Rule proposition nodes. * @@ -320,7 +311,7 @@ public boolean anySupportAssertedInContext(Report report) * @throws NotAPropositionNodeException * @throws DuplicatePropositionException */ - public void processSingleRequestsChannel(Channel currentChannel) + protected void processSingleRequestsChannel(Channel currentChannel) throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { if (currentChannel instanceof RuleToConsequentChannel) { boolean closedTypeTerm = term instanceof Closed; @@ -348,10 +339,13 @@ public void processSingleRequestsChannel(Channel currentChannel) boolean caseCondition = ruleNodeAllVariablesBound ? reportNodeExtractedSubs.size() == ruleNodeExtractedSubs.size() : reportNodeExtractedSubs.size() < ruleNodeExtractedSubs.size(); - if (caseCondition && anySupportAssertedInContext(report)) { - requestAntecedentsNotAlreadyWorkingOn(currentChannel); - if (ruleNodeAllVariablesBound) + if (caseCondition && report.anySupportAssertedInContext(currentContext)) { + if (ruleNodeAllVariablesBound) { + requestAntecedentsNotAlreadyWorkingOn(currentChannel); return; + } else + requestAntecedentsNotAlreadyWorkingOn(currentChannel, report); + } } super.processSingleRequestsChannel(currentChannel); @@ -368,15 +362,18 @@ public void processSingleRequestsChannel(Channel currentChannel) * Report handling in Rule proposition nodes. */ public void processReports() { - for (Channel currentChannel : incomingChannels) { - ReportSet channelReports = currentChannel.getReportsBuffer(); - for (Report currentReport : channelReports) { - if (currentChannel instanceof AntecedentToRuleChannel) { - applyRuleHandler(currentReport, currentChannel.getReporter()); - } + for (Channel currentChannel : incomingChannels) + processSingleReportsChannel(currentChannel); + } + + protected void processSingleReportsChannel(Channel currentChannel) { + ReportSet channelReports = currentChannel.getReportsBuffer(); + for (Report currentReport : channelReports) { + if (currentChannel instanceof AntecedentToRuleChannel) { + applyRuleHandler(currentReport, currentChannel); } - currentChannel.clearReportsBuffer(); } + currentChannel.clearReportsBuffer(); } } diff --git a/src/sneps/snip/Report.java b/src/sneps/snip/Report.java index 00f4d133..56ebdd4b 100644 --- a/src/sneps/snip/Report.java +++ b/src/sneps/snip/Report.java @@ -1,38 +1,49 @@ package sneps.snip; +import java.util.Collection; import java.util.Hashtable; import java.util.Set; +import sneps.exceptions.NodeNotFoundInNetworkException; +import sneps.exceptions.NotAPropositionNodeException; import sneps.network.classes.setClasses.PropositionSet; +import sneps.snebr.Context; import sneps.snebr.Support; import sneps.snip.matching.Substitutions; public class Report { private Substitutions substitution; - private Hashtable supports; + private Collection supports; private boolean sign; - private String contextName; - public Report(Substitutions substitution, Hashtable set, boolean sign, String contextID) { + public Report(Substitutions substitution, Collection set, boolean sign) { this.substitution = substitution; this.supports = set; this.sign = sign; - this.contextName = contextID; + } + + public boolean anySupportAssertedInContext(Context reportContext) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + Collection reportSupportsSet = getSupports(); + PropositionSet contextHypothesisSet = reportContext.getHypothesisSet(); + for (PropositionSet assumptionHyps : reportSupportsSet) + if (assumptionHyps.isSubSet(contextHypothesisSet)) + return true; + return false; } public Substitutions getSubstitutions() { return substitution; } - public Hashtable getSupports() { + public Collection getSupports() { return supports; } @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() { @@ -52,11 +63,7 @@ public void toggleSign() { } public String toString() { - return "ContextID : " + contextName + "\nSign: " + sign + "\nSubstitution: " + substitution + "\nSupport: " - + supports; + return "Sign: " + sign + "\nSubstitution: " + substitution + "\nSupport: " + supports; } - public String getContextName() { - return contextName; - } } diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index bf4b2ea4..112142b7 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -1,9 +1,13 @@ package sneps.snip.channels; +import sneps.exceptions.NodeNotFoundInNetworkException; +import sneps.exceptions.NotAPropositionNodeException; import sneps.network.Node; import sneps.network.PropositionNode; import sneps.network.classes.setClasses.ChannelSet; import sneps.network.classes.setClasses.ReportSet; +import sneps.snebr.Context; +import sneps.snebr.Controller; import sneps.snip.Filter; import sneps.snip.InferenceTypes; import sneps.snip.Report; @@ -43,12 +47,13 @@ public Channel(Substitutions switcherSubstitution, Substitutions filterSubstitut this.inferenceType = inferenceType; } - public boolean testReportToSend(Report report) { + public boolean testReportToSend(Report report) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { boolean passTest = filter.canPass(report); System.out.println("Can pass " + passTest); - .passTest. /*Test the context name if it will pass or not*/ - if (passTest && contextName.equals(report.getContextName())) { - System.out.println("\n\nThe switcher data:\n" + switcher); + /* Test the context name if it will pass or not */ + Context channelContext = Controller.getContextByName(getContextName()); + if (passTest && report.anySupportAssertedInContext(channelContext)) { + System.out.println("\nThe switcher data:\n" + switcher); switcher.switchReport(report); reportsBuffer.addReport(report); Runner.addToHighQueue(requester); diff --git a/src/sneps/snip/classes/FlagNode.java b/src/sneps/snip/classes/FlagNode.java index 00d40794..23bf76d7 100644 --- a/src/sneps/snip/classes/FlagNode.java +++ b/src/sneps/snip/classes/FlagNode.java @@ -1,5 +1,6 @@ package sneps.snip.classes; +import java.util.Collection; import java.util.Hashtable; import java.util.Set; @@ -10,22 +11,19 @@ public class FlagNode { private Node node; - private Hashtable supports; + private Collection supports; private int flag; /** * Create a new flag node * - * @param n - * node - * @param hashtable - * support - * @param f - * true or false + * @param n node + * @param collection support + * @param f true or false */ - public FlagNode(Node n, Hashtable hashtable, int f) { + public FlagNode(Node n, Collection collection, int f) { node = n; - supports = hashtable; + supports = collection; flag = f; } @@ -43,13 +41,13 @@ public Node getNode() { * * @return support */ - public Hashtable getSupports() { + public Collection getSupports() { return supports; } /** - * Return the flag of the flag node (1 is true, 2 is false, 3 is unknown and - * 4 is requested) + * Return the flag of the flag node (1 is true, 2 is false, 3 is unknown and 4 + * is requested) * * @return Node */ @@ -60,8 +58,7 @@ public int getFlag() { /** * Check if this and fn are equal * - * @param fn - * flag node + * @param fn flag node * @return true or false */ public boolean isEqual(FlagNode fn) { @@ -71,12 +68,10 @@ public boolean isEqual(FlagNode fn) { /** * Set the value of the flag to x * - * @param x - * int + * @param x int */ public void setFlag(int x) { flag = x; } - - + } diff --git a/src/sneps/snip/rules/OrNode.java b/src/sneps/snip/rules/OrNode.java index 9f794c9b..7e13575e 100644 --- a/src/sneps/snip/rules/OrNode.java +++ b/src/sneps/snip/rules/OrNode.java @@ -1,5 +1,7 @@ package sneps.snip.rules; +import java.util.ArrayList; +import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; import java.util.Set; @@ -27,17 +29,14 @@ public OrNode(Term syn) { } public void applyRuleHandler(Report report, Node node) { - if (report.isPositive()) { - Support originSupports = this.getBasicSupport(); - Hashtable sup = new Hashtable(); + Collection originSupportsSet = originSupports.getAssumptionBasedSupport().values(); + Collection sup = new ArrayList(); sup.add(originSupports); - Report reply = new Report(report.getSubstitutions(), sup, true, report.getContextName()); - + Report reply = new Report(report.getSubstitutions(), sup, true); for (Channel outChannel : outgoingChannels) outChannel.testReportToSend(reply); - } } From 9ca83b1923fa13c84e4fcf5d0ec867b9d97c149d Mon Sep 17 00:00:00 2001 From: Youssef Date: Wed, 8 May 2019 09:25:03 +0200 Subject: [PATCH 13/22] implemented rule node reports processing --- src/sneps/gui/FXController.java | 3065 ++++++++--------- src/sneps/network/Node.java | 10 +- src/sneps/network/PropositionNode.java | 157 +- src/sneps/network/RuleNode.java | 62 +- .../classes/setClasses/ChannelSet.java | 86 +- src/sneps/snip/Report.java | 24 +- .../channels/AntecedentToRuleChannel.java | 4 +- src/sneps/snip/channels/Channel.java | 12 +- src/sneps/snip/channels/ChannelSet.java | 22 - src/sneps/snip/channels/MatchChannel.java | 4 +- .../channels/RuleToConsequentChannel.java | 4 +- src/sneps/snip/classes/FlagNode.java | 14 +- src/sneps/snip/classes/RuleResponse.java | 35 + .../snip/matching/LinearSubstitutions.java | 5 +- src/sneps/snip/matching/Match.java | 4 +- src/sneps/snip/rules/OrNode.java | 15 +- tests/InferenceTest.java | 12 + tests/PropositionSetTest.java | 249 +- tests/SupportTest.java | 1530 ++++---- 19 files changed, 2646 insertions(+), 2668 deletions(-) delete mode 100644 src/sneps/snip/channels/ChannelSet.java create mode 100644 src/sneps/snip/classes/RuleResponse.java create mode 100644 tests/InferenceTest.java diff --git a/src/sneps/gui/FXController.java b/src/sneps/gui/FXController.java index eb6c3728..27db001b 100644 --- a/src/sneps/gui/FXController.java +++ b/src/sneps/gui/FXController.java @@ -123,8 +123,7 @@ public class FXController implements Initializable { private LinkedList sdcs = new LinkedList(); private ArrayList cfSignsArray = new ArrayList(); private Hashtable paths = new Hashtable(); - - + private CaseFrame curCF = null; private RelationsRestrictedCaseFrame curRRCF = null; boolean moveMode = false; @@ -140,35 +139,30 @@ public class FXController implements Initializable { private ArrayList listOfMolNodesDrawn = new ArrayList(); private LinkedList rrcflist = new LinkedList(); private int bpcounter = 0; - + @FXML private TextArea console; @FXML private Label nodeDetails, relationDetails, ppath, qpath, ppath1, qpath1; @FXML - private TextField newRN, newRL, baseNodeIdentPop, - caseFrameSTN, baseNodeID, overrideLimit, newNetName, cableMinNodes, - cableMaxNodes, - signPriority, contextName, semanticName, searchNodes; + private TextField newRN, newRL, baseNodeIdentPop, caseFrameSTN, baseNodeID, overrideLimit, newNetName, + cableMinNodes, cableMaxNodes, signPriority, contextName, semanticName, searchNodes; @FXML private ListView relationSetList, relationSetList1, relationSetList2, cfRS, caseFramesList, - caseFrameRelationList, nodesList, wiresList, variableNodesList, baseNodesList, caseFramesDrawList, - relationOfDrawnCF, rrcfrslist, selectCFForSign, selectCFRelForSign, - cablesList, sdcsList, listOfSigns, cfListForSign, - cfSignsList, propoNodesList, propSet, pathsList, pathRelations, - contextList, propoNodesList1, propSet1, composeList, propNodesListOfSelCont; + caseFrameRelationList, nodesList, wiresList, variableNodesList, baseNodesList, caseFramesDrawList, + relationOfDrawnCF, rrcfrslist, selectCFForSign, selectCFRelForSign, cablesList, sdcsList, listOfSigns, + cfListForSign, cfSignsList, propoNodesList, propSet, pathsList, pathRelations, contextList, propoNodesList1, + propSet1, composeList, propNodesListOfSelCont; @FXML private Group dragBaseNode, dragVarNode, wireModeBtn, dragMolNode; @FXML - private AnchorPane drawArea, baseNodepopBox, varNodepopBox, drawMolCF, - relationCFDrawSelect, consoleOutput; + private AnchorPane drawArea, baseNodepopBox, varNodepopBox, drawMolCF, relationCFDrawSelect, consoleOutput; @FXML private ScrollPane drawScroll, consoleScroll; @FXML - private MenuButton caseFrameChoice, netChoice1, netChoice2, netChoice3, - baseNodeSemType, newRT, rrcfSem, resultSemType, cableSem, baseNodeSemTyPop, - newRA, overrideAdjust, pathNodes1, pathNodes2, selectedPath, pathCF, definePathRelations, - chooseContext, chooseContext1, parentSemChoice; + private MenuButton caseFrameChoice, netChoice1, netChoice2, netChoice3, baseNodeSemType, newRT, rrcfSem, + resultSemType, cableSem, baseNodeSemTyPop, newRA, overrideAdjust, pathNodes1, pathNodes2, selectedPath, + pathCF, definePathRelations, chooseContext, chooseContext1, parentSemChoice; @FXML private Button drawModeBtn, deleteModeBtn, moveModeBtn, createPathBTN, assertBTN, deduceBTN; @FXML @@ -177,10 +171,10 @@ public class FXController implements Initializable { private WebView webView; @FXML private Tab displayNetTab; - + @Override public void initialize(URL location, ResourceBundle resources) { - + nodesList.setOnMouseClicked(new EventHandler() { @Override @@ -194,28 +188,29 @@ public void handle(MouseEvent arg0) { // TODO Auto-generated catch block e.printStackTrace(); } - if(!(n.getTerm() instanceof Variable) && n.getSemantic().getSemanticType().equalsIgnoreCase("proposition")) { + if (!(n.getTerm() instanceof Variable) + && n.getSemantic().getSemanticType().equalsIgnoreCase("proposition")) { assertBTN.setDisable(false); deduceBTN.setDisable(false); - }else { + } else { assertBTN.setDisable(true); deduceBTN.setDisable(true); } } - + }); - + relationSetList.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent event) { String relationName = relationSetList.getSelectionModel().getSelectedItem(); relationDetails(relationName); - + } - + }); - + dragMolNode(); dragBaseNode(); dragVariableNode(); @@ -236,22 +231,20 @@ public void handle(MouseEvent event) { updateNetLists(); } catch (FileNotFoundException e) { System.out.println("Files Not Found!"); - //e.printStackTrace(); + // e.printStackTrace(); } catch (ClassNotFoundException e) { System.out.println("Files Not Found!"); - //e.printStackTrace(); + // e.printStackTrace(); } catch (IOException e) { System.out.println("Files Not Found!"); - //e.printStackTrace(); + // e.printStackTrace(); } - + pathsList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); } - - //..........SNePS Log Methods.......................................... - //Controls The SNePS Log + // Controls The SNePS Log public void consoleHandler() { consoleScroll.setFitToHeight(true); consoleScroll.setFitToWidth(true); @@ -262,19 +255,19 @@ public void consoleHandler() { public void handle(KeyEvent event) { ArrayList lines = new ArrayList(); ArrayList resLines = new ArrayList(); - if(event.getCode() == KeyCode.ENTER) { - for(String line : console.getText().split("\n")) { + if (event.getCode() == KeyCode.ENTER) { + for (String line : console.getText().split("\n")) { String tempLine = line.substring(1, line.length()); lines.add(tempLine); } - + String cmd = lines.get(lines.size() - 1); - + String res = AP.executeSnepslogCommand(cmd); - for(String rl : res.split("\n")) { + for (String rl : res.split("\n")) { resLines.add(rl); } - for(int i = 0; i { - if (response == yes) { - drawArea.getChildren().clear(); + if (response == yes) { + drawArea.getChildren().clear(); drawnWiresList.clear(); drawnRelationsList.clear(); arrows.clear(); listOfBaseNodesDrawn.clear(); listOfVarNodesDrawn.clear(); listOfMolNodesDrawn.clear(); - } else if (response == cancel) { - - } + } else if (response == cancel) { + + } }); } - - //Drag Base Node to draw area + + // Drag Base Node to draw area public void dragMolNode() { - - dragMolNode.setOnMouseEntered(new EventHandler () { - @Override - public void handle(MouseEvent event) { - dragMolNode.setCursor(Cursor.HAND); - } - }); - - dragMolNode.setOnDragDetected(new EventHandler() { - @Override - public void handle(MouseEvent event) { - //System.out.println("onDragDetected"); - if(Network.getCaseFrames().size() != 0) { - Dragboard db = dragMolNode.startDragAndDrop(TransferMode.ANY); - ClipboardContent content = new ClipboardContent(); - content.putString("MolNode"); - db.setContent(content); - event.consume(); - }else { - Alert a = new Alert(AlertType.ERROR); - a.setTitle("Error!"); - a.setContentText("There are no case frames in the network, please create a case frame."); - a.showAndWait(); - } - + dragMolNode.setOnMouseEntered(new EventHandler() { + @Override + public void handle(MouseEvent event) { + dragMolNode.setCursor(Cursor.HAND); + } + }); + + dragMolNode.setOnDragDetected(new EventHandler() { + + @Override + public void handle(MouseEvent event) { + // System.out.println("onDragDetected"); + if (Network.getCaseFrames().size() != 0) { + Dragboard db = dragMolNode.startDragAndDrop(TransferMode.ANY); + ClipboardContent content = new ClipboardContent(); + content.putString("MolNode"); + db.setContent(content); + event.consume(); + } else { + Alert a = new Alert(AlertType.ERROR); + a.setTitle("Error!"); + a.setContentText("There are no case frames in the network, please create a case frame."); + a.showAndWait(); } - - }); - - } - - //Drag Base Node to draw area + + } + + }); + + } + + // Drag Base Node to draw area public void dragBaseNode() { - - dragBaseNode.setOnMouseEntered(new EventHandler () { + + dragBaseNode.setOnMouseEntered(new EventHandler() { @Override public void handle(MouseEvent event) { dragBaseNode.setCursor(Cursor.HAND); } }); - + dragBaseNode.setOnDragDetected(new EventHandler() { @Override public void handle(MouseEvent event) { - //System.out.println("onDragDetected"); - Dragboard db = dragBaseNode.startDragAndDrop(TransferMode.ANY); - ClipboardContent content = new ClipboardContent(); - content.putString("BaseNode"); - db.setContent(content); - event.consume(); - - } - + // System.out.println("onDragDetected"); + Dragboard db = dragBaseNode.startDragAndDrop(TransferMode.ANY); + ClipboardContent content = new ClipboardContent(); + content.putString("BaseNode"); + db.setContent(content); + event.consume(); + + } + }); - + } - //Drag Base Node to draw area + // Drag Base Node to draw area public void dragVariableNode() { - - dragVarNode.setOnMouseEntered(new EventHandler () { + + dragVarNode.setOnMouseEntered(new EventHandler() { @Override public void handle(MouseEvent event) { dragVarNode.setCursor(Cursor.HAND); } }); - + dragVarNode.setOnDragDetected(new EventHandler() { @Override public void handle(MouseEvent event) { - //System.out.println("onDragDetected"); - Dragboard db = dragVarNode.startDragAndDrop(TransferMode.ANY); - ClipboardContent content = new ClipboardContent(); - content.putString("VarNode"); - db.setContent(content); - event.consume(); - - } - + // System.out.println("onDragDetected"); + Dragboard db = dragVarNode.startDragAndDrop(TransferMode.ANY); + ClipboardContent content = new ClipboardContent(); + content.putString("VarNode"); + db.setContent(content); + event.consume(); + + } + }); - + } - - //Handling draw area + + // Handling draw area public void drawArea() { - - drawArea.setOnDragOver(new EventHandler () { - public void handle(DragEvent event) { - Dragboard db = event.getDragboard(); - event.acceptTransferModes(TransferMode.ANY); - if(db.getString() == "BaseNode") { - - } - event.consume(); - } - }); - + + drawArea.setOnDragOver(new EventHandler() { + public void handle(DragEvent event) { + Dragboard db = event.getDragboard(); + event.acceptTransferModes(TransferMode.ANY); + if (db.getString() == "BaseNode") { + + } + event.consume(); + } + }); + drawArea.setOnDragDropped(new EventHandler() { - @Override - public void handle(DragEvent event) { - Dragboard db = event.getDragboard(); - event.acceptTransferModes(TransferMode.ANY); - if(db.getString() == "BaseNode") { - curX = event.getX(); - curY = event.getY(); - baseNodepopBox.setVisible(true); - } - else if(db.getString() == "VarNode") { - curX = event.getX(); - curY = event.getY(); - varNodepopBox.setVisible(true); - } - - else if(db.getString() == "MoveNode" && moveMode == true) { - curX = event.getX(); - curY = event.getY(); - } - else if(db.getString() == "MolNode") { - curX = event.getX(); - curY = event.getY(); - drawMolCF.setVisible(true); - } - } - }); - - } - - //Draw the molecular node + @Override + public void handle(DragEvent event) { + Dragboard db = event.getDragboard(); + event.acceptTransferModes(TransferMode.ANY); + if (db.getString() == "BaseNode") { + curX = event.getX(); + curY = event.getY(); + baseNodepopBox.setVisible(true); + } else if (db.getString() == "VarNode") { + curX = event.getX(); + curY = event.getY(); + varNodepopBox.setVisible(true); + } + + else if (db.getString() == "MoveNode" && moveMode == true) { + curX = event.getX(); + curY = event.getY(); + } else if (db.getString() == "MolNode") { + curX = event.getX(); + curY = event.getY(); + drawMolCF.setVisible(true); + } + } + }); + + } + + // Draw the molecular node public void submitMolNode() { String cfname = caseFramesDrawList.getSelectionModel().getSelectedItem(); CaseFrame cf = null; @@ -511,29 +495,29 @@ public void submitMolNode() { @Override public void handle(MouseEvent event) { - if(deleteMode == true && wireMode == false) { - double xPos = shape.getLayoutX()+50; - double yPos = shape.getLayoutY()+40; - for(int i = 0; i relations = drawAreaRelations(cfname); relationOfDrawnCF.getItems().clear(); - for(Relation r: relations) { + for (Relation r : relations) { relationOfDrawnCF.getItems().add(r.getName()); } - relationCFDrawSelect.setVisible(true); + relationCFDrawSelect.setVisible(true); } } - + }); - - shape.setOnDragDetected(new EventHandler() { + + shape.setOnDragDetected(new EventHandler() { @Override public void handle(MouseEvent event) { - if(moveMode == true) { + if (moveMode == true) { Dragboard db = shape.startDragAndDrop(TransferMode.ANY); - ClipboardContent content = new ClipboardContent(); - content.putString("MoveNode"); - db.setContent(content); - event.consume(); + ClipboardContent content = new ClipboardContent(); + content.putString("MoveNode"); + db.setContent(content); + event.consume(); } - - if(wireMode == true) { + + if (wireMode == true) { Dragboard db = shape.startDragAndDrop(TransferMode.ANY); - ClipboardContent content = new ClipboardContent(); - content.putString("wireMode"); - wireXStart = shape.getLayoutX() + 50; - wireYStart = shape.getLayoutY() + 40; - db.setContent(content); - event.consume(); - } - } - - }); - - // Moving the node - shape.setOnDragDone(new EventHandler() { - public void handle(DragEvent event) { - if(moveMode == true && wireMode == false) { - double oldPosX = shape.getLayoutX() + 50; - double oldPosY = shape.getLayoutY() + 40; - shape.setLayoutX(curX-50); - shape.setLayoutY(curY-40); - - for(int x = 0; x() { + ClipboardContent content = new ClipboardContent(); + content.putString("wireMode"); + wireXStart = shape.getLayoutX() + 50; + wireYStart = shape.getLayoutY() + 40; + db.setContent(content); + event.consume(); + } + } + + }); + + // Moving the node + shape.setOnDragDone(new EventHandler() { + public void handle(DragEvent event) { + if (moveMode == true && wireMode == false) { + double oldPosX = shape.getLayoutX() + 50; + double oldPosY = shape.getLayoutY() + 40; + shape.setLayoutX(curX - 50); + shape.setLayoutY(curY - 40); + + for (int x = 0; x < listOfMolNodesDrawn.size(); x++) { + MolNodeShape temp = listOfMolNodesDrawn.get(x); + if (temp == mns) { + temp.setX(curX); + temp.setY(curY); + listOfMolNodesDrawn.set(x, temp); + } + } + + for (int i = 0; i < drawnWiresList.size(); i++) { + Line l = drawnWiresList.get(i); + if (l != null) { + Label lbl = drawnRelationsList.get(i); + Circle c = arrows.get(i); + if (l.getStartX() == oldPosX && l.getStartY() == oldPosY) { + drawnWiresList.get(i).setStartX(curX); + drawnWiresList.get(i).setStartY(curY); + + l.setStartX(curX); + l.setStartY(curY); + + lbl.setLayoutX((l.getStartX() + l.getEndX()) / 2); + lbl.setLayoutY((l.getStartY() + l.getEndY()) / 2); + drawnRelationsList.get(i).setLayoutX((l.getStartX() + l.getEndX()) / 2); + drawnRelationsList.get(i).setLayoutY((l.getStartY() + l.getEndY()) / 2); + + double vx = l.getEndX() - l.getStartX(); + double vy = l.getEndY() - l.getStartY(); + double vn = Math.sqrt((vx * vx) + (vy * vy)); + double vnx = vx / vn; + double vny = vy / vn; + double td = (vx * vx) + (vy * vy); + double d = Math.sqrt(td) - 50; + double newX = l.getStartX() + (d * vnx); + double newY = l.getStartY() + (d * vny); + c.setCenterX(newX); + c.setCenterY(newY); + + double ax = l.getStartX() - l.getEndX(); + double ay = l.getStartY() - l.getEndY(); + double bx = l.getStartX() - (l.getStartX() + 5); + double by = 0; + double a = Math.sqrt((ax * ax) + (ay * ay)); + double b = Math.sqrt((bx * bx) + (by * by)); + double ab = (ax * bx) + (ay * by); + double abn = a * b; + double angle = Math.acos(ab / abn) * (180 / Math.PI); + if (l.getEndY() < l.getStartY()) { + c.setRotate(-angle); + } else { + c.setRotate(angle); + } + } else if (l.getEndX() == oldPosX && l.getEndY() == oldPosY) { + drawnWiresList.get(i).setEndX(curX); + drawnWiresList.get(i).setEndY(curY); + + l.setEndX(curX); + l.setEndY(curY); + + lbl.setLayoutX((l.getStartX() + l.getEndX()) / 2); + lbl.setLayoutY((l.getStartY() + l.getEndY()) / 2); + drawnRelationsList.get(i).setLayoutX((l.getStartX() + l.getEndX()) / 2); + drawnRelationsList.get(i).setLayoutY((l.getStartY() + l.getEndY()) / 2); + + double vx = l.getEndX() - l.getStartX(); + double vy = l.getEndY() - l.getStartY(); + double vn = Math.sqrt((vx * vx) + (vy * vy)); + double vnx = vx / vn; + double vny = vy / vn; + double td = (vx * vx) + (vy * vy); + double d = Math.sqrt(td) - 50; + double newX = l.getStartX() + (d * vnx); + double newY = l.getStartY() + (d * vny); + c.setCenterX(newX); + c.setCenterY(newY); + + double ax = l.getStartX() - l.getEndX(); + double ay = l.getStartY() - l.getEndY(); + double bx = l.getStartX() - (l.getStartX() + 5); + double by = 0; + double a = Math.sqrt((ax * ax) + (ay * ay)); + double b = Math.sqrt((bx * bx) + (by * by)); + double ab = (ax * bx) + (ay * by); + double abn = a * b; + double angle = Math.acos(ab / abn) * (180 / Math.PI); + if (l.getEndY() < l.getStartY()) { + c.setRotate(-angle); + } else { + c.setRotate(angle); + } + + } + } + } + event.consume(); + } + } + }); + + shape.setOnDragDropped(new EventHandler() { @Override public void handle(DragEvent event) { - if(wireMode == true) { + if (wireMode == true) { Dragboard db = event.getDragboard(); - if(db.getString() == "wireMode" && currentSelectedRelation != null) { - wireXEnd = shape.getLayoutX() + 50; - wireYEnd = shape.getLayoutY() + 40; - WireRelation wr = new WireRelation(wireXStart, wireYStart, wireXEnd, wireYEnd); - Line l = wr.drawLine(); - double vx = wireXEnd - wireXStart; - double vy = wireYEnd - wireYStart; - double vn = Math.sqrt((vx*vx) + (vy*vy)); - double vnx = vx/vn; - double vny = vy/vn; - double td = (vx*vx) + (vy*vy); - double d = Math.sqrt(td) -50; - double newX = wireXStart + (d*vnx); - double newY = wireYStart + (d*vny); - Circle cir = new Circle(); - cir.setCenterX(newX); - cir.setCenterY(newY); - cir.setRadius(12.5); - Image img = new Image("sneps/gui/AH.png"); - cir.setFill(new ImagePattern(img)); - double ax = wireXStart - wireXEnd; - double ay = wireYStart - wireYEnd; - double bx = wireXStart - (wireXStart + 5); - double by = wireYStart - wireYStart; - double a = Math.sqrt((ax*ax) + (ay*ay)); - double b = Math.sqrt((bx*bx) + (by*by)); - double ab = (ax*bx) + (ay*by); - double abn = a * b; - double angle = Math.acos(ab/abn) * (180/Math.PI); - if(wireYEnd < wireYStart) { - cir.setRotate(-angle); - } - else { - cir.setRotate(angle); - } - drawArea.getChildren().add(l); - drawArea.getChildren().add(cir); - l.toBack(); - Label relationName = new Label(currentSelectedRelation); - relationName.setLayoutX((l.getStartX() + l.getEndX()) / 2); - relationName.setLayoutY((l.getStartY() + l.getEndY()) / 2); - drawArea.getChildren().add(relationName); - l.setOnMouseClicked(new EventHandler() { + if (db.getString() == "wireMode" && currentSelectedRelation != null) { + wireXEnd = shape.getLayoutX() + 50; + wireYEnd = shape.getLayoutY() + 40; + WireRelation wr = new WireRelation(wireXStart, wireYStart, wireXEnd, wireYEnd); + Line l = wr.drawLine(); + double vx = wireXEnd - wireXStart; + double vy = wireYEnd - wireYStart; + double vn = Math.sqrt((vx * vx) + (vy * vy)); + double vnx = vx / vn; + double vny = vy / vn; + double td = (vx * vx) + (vy * vy); + double d = Math.sqrt(td) - 50; + double newX = wireXStart + (d * vnx); + double newY = wireYStart + (d * vny); + Circle cir = new Circle(); + cir.setCenterX(newX); + cir.setCenterY(newY); + cir.setRadius(12.5); + Image img = new Image("sneps/gui/AH.png"); + cir.setFill(new ImagePattern(img)); + double ax = wireXStart - wireXEnd; + double ay = wireYStart - wireYEnd; + double bx = wireXStart - (wireXStart + 5); + double by = wireYStart - wireYStart; + double a = Math.sqrt((ax * ax) + (ay * ay)); + double b = Math.sqrt((bx * bx) + (by * by)); + double ab = (ax * bx) + (ay * by); + double abn = a * b; + double angle = Math.acos(ab / abn) * (180 / Math.PI); + if (wireYEnd < wireYStart) { + cir.setRotate(-angle); + } else { + cir.setRotate(angle); + } + drawArea.getChildren().add(l); + drawArea.getChildren().add(cir); + l.toBack(); + Label relationName = new Label(currentSelectedRelation); + relationName.setLayoutX((l.getStartX() + l.getEndX()) / 2); + relationName.setLayoutY((l.getStartY() + l.getEndY()) / 2); + drawArea.getChildren().add(relationName); + l.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent arg0) { - if(deleteMode == true) { + if (deleteMode == true) { drawArea.getChildren().remove(l); drawArea.getChildren().remove(relationName); drawArea.getChildren().remove(cir); @@ -764,28 +743,28 @@ public void handle(MouseEvent arg0) { arrows.remove(cir); } } - - }); - currentSelectedRelation = null; - drawnWiresList.add(l); - drawnRelationsList.add(relationName); - arrows.add(cir); - } - event.consume(); + + }); + currentSelectedRelation = null; + drawnWiresList.add(l); + drawnRelationsList.add(relationName); + arrows.add(cir); + } + event.consume(); } } - - }); + + }); } - - //Draw the relation + + // Draw the relation public void drawRelation() { String rname = relationOfDrawnCF.getSelectionModel().getSelectedItem(); currentSelectedRelation = rname; relationCFDrawSelect.setVisible(false); } - - //Submit base node drawn in draw area + + // Submit base node drawn in draw area public void submitExistBaseNode() { String identifier = baseNodesList.getSelectionModel().getSelectedItem(); Node n = null; @@ -800,38 +779,37 @@ public void submitExistBaseNode() { BaseNodeShape baseNode = new BaseNodeShape(identifier, semType, curX, curY); listOfBaseNodesDrawn.add(baseNode); Group shape = baseNode.makeShape(); - shape.setLayoutX(curX-50); - shape.setLayoutY(curY-40); + shape.setLayoutX(curX - 50); + shape.setLayoutY(curY - 40); drawArea.getChildren().add(shape); baseNodepopBox.setVisible(false); - //Delete the node - shape.setOnMouseClicked(new EventHandler() { + // Delete the node + shape.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent event) { - if(deleteMode == true && wireMode == false) { - double xPos = shape.getLayoutX()+50; - double yPos = shape.getLayoutY()+40; - - for(int i = 0; i() { + + shape.setOnDragDetected(new EventHandler() { @Override public void handle(MouseEvent event) { - if(moveMode == true) { + if (moveMode == true) { Dragboard db = shape.startDragAndDrop(TransferMode.ANY); - ClipboardContent content = new ClipboardContent(); - content.putString("MoveNode"); - db.setContent(content); - event.consume(); - } - } - - }); - - // Moving the node - shape.setOnDragDone(new EventHandler() { - public void handle(DragEvent event) { - if(moveMode == true && wireMode == false) { - double oldPosX = shape.getLayoutX() + 50; - double oldPosY = shape.getLayoutY() + 40; - shape.setLayoutX(curX-50); - shape.setLayoutY(curY-40); - - for(int x = 0; x() { + ClipboardContent content = new ClipboardContent(); + content.putString("MoveNode"); + db.setContent(content); + event.consume(); + } + } + + }); + + // Moving the node + shape.setOnDragDone(new EventHandler() { + public void handle(DragEvent event) { + if (moveMode == true && wireMode == false) { + double oldPosX = shape.getLayoutX() + 50; + double oldPosY = shape.getLayoutY() + 40; + shape.setLayoutX(curX - 50); + shape.setLayoutY(curY - 40); + + for (int x = 0; x < listOfBaseNodesDrawn.size(); x++) { + BaseNodeShape temp = listOfBaseNodesDrawn.get(x); + if (temp == baseNode) { + temp.setX(curX); + temp.setY(curY); + listOfBaseNodesDrawn.set(x, temp); + } + } + + for (int i = 0; i < drawnWiresList.size(); i++) { + Line l = drawnWiresList.get(i); + if (l != null) { + Label lbl = drawnRelationsList.get(i); + Circle c = arrows.get(i); + if (l.getEndX() == oldPosX && l.getEndY() == oldPosY) { + drawnWiresList.get(i).setEndX(curX); + drawnWiresList.get(i).setEndY(curY); + + l.setEndX(curX); + l.setEndY(curY); + + lbl.setLayoutX((l.getStartX() + l.getEndX()) / 2); + lbl.setLayoutY((l.getStartY() + l.getEndY()) / 2); + drawnRelationsList.get(i).setLayoutX((l.getStartX() + l.getEndX()) / 2); + drawnRelationsList.get(i).setLayoutY((l.getStartY() + l.getEndY()) / 2); + + double vx = l.getEndX() - l.getStartX(); + double vy = l.getEndY() - l.getStartY(); + double vn = Math.sqrt((vx * vx) + (vy * vy)); + double vnx = vx / vn; + double vny = vy / vn; + double td = (vx * vx) + (vy * vy); + double d = Math.sqrt(td) - 50; + double newX = l.getStartX() + (d * vnx); + double newY = l.getStartY() + (d * vny); + c.setCenterX(newX); + c.setCenterY(newY); + double ax = l.getStartX() - l.getEndX(); + double ay = l.getStartY() - l.getEndY(); + double bx = l.getStartX() - (l.getStartX() + 5); + double by = 0; + double a = Math.sqrt((ax * ax) + (ay * ay)); + double b = Math.sqrt((bx * bx) + (by * by)); + double ab = (ax * bx) + (ay * by); + double abn = a * b; + double angle = Math.acos(ab / abn) * (180 / Math.PI); + if (l.getEndY() < l.getStartY()) { + c.setRotate(-angle); + } else { + c.setRotate(angle); + } + } + } + } + event.consume(); + } + } + }); + + // Drawing the wires + shape.setOnDragDropped(new EventHandler() { @Override public void handle(DragEvent event) { - if(wireMode == true) { + if (wireMode == true) { Dragboard db = event.getDragboard(); - if(db.getString() == "wireMode" && currentSelectedRelation != null) { - wireXEnd = shape.getLayoutX() + 50; - wireYEnd = shape.getLayoutY() + 40; - WireRelation wr = new WireRelation(wireXStart, wireYStart, wireXEnd, wireYEnd); - Line l = wr.drawLine(); - double vx = wireXEnd - wireXStart; - double vy = wireYEnd - wireYStart; - double vn = Math.sqrt((vx*vx) + (vy*vy)); - double vnx = vx/vn; - double vny = vy/vn; - double td = (vx*vx) + (vy*vy); - double d = Math.sqrt(td) -50; - double newX = wireXStart + (d*vnx); - double newY = wireYStart + (d*vny); - Circle cir = new Circle(); - cir.setCenterX(newX); - cir.setCenterY(newY); - cir.setRadius(12.5); - Image img = new Image("sneps/gui/AH.png"); - cir.setFill(new ImagePattern(img)); - double ax = wireXStart - wireXEnd; - double ay = wireYStart - wireYEnd; - double bx = wireXStart - (wireXStart + 5); - double by = wireYStart - wireYStart; - double a = Math.sqrt((ax*ax) + (ay*ay)); - double b = Math.sqrt((bx*bx) + (by*by)); - double ab = (ax*bx) + (ay*by); - double abn = a * b; - double angle = Math.acos(ab/abn) * (180/Math.PI); - if(wireYEnd < wireYStart) { - cir.setRotate(-angle); - } - else { - cir.setRotate(angle); - } - drawArea.getChildren().add(l); - drawArea.getChildren().add(cir); - l.toBack(); - Label relationName = new Label(currentSelectedRelation); - relationName.setLayoutX((l.getStartX() + l.getEndX()) / 2); - relationName.setLayoutY((l.getStartY() + l.getEndY()) / 2); - drawArea.getChildren().add(relationName); - l.setOnMouseClicked(new EventHandler() { + if (db.getString() == "wireMode" && currentSelectedRelation != null) { + wireXEnd = shape.getLayoutX() + 50; + wireYEnd = shape.getLayoutY() + 40; + WireRelation wr = new WireRelation(wireXStart, wireYStart, wireXEnd, wireYEnd); + Line l = wr.drawLine(); + double vx = wireXEnd - wireXStart; + double vy = wireYEnd - wireYStart; + double vn = Math.sqrt((vx * vx) + (vy * vy)); + double vnx = vx / vn; + double vny = vy / vn; + double td = (vx * vx) + (vy * vy); + double d = Math.sqrt(td) - 50; + double newX = wireXStart + (d * vnx); + double newY = wireYStart + (d * vny); + Circle cir = new Circle(); + cir.setCenterX(newX); + cir.setCenterY(newY); + cir.setRadius(12.5); + Image img = new Image("sneps/gui/AH.png"); + cir.setFill(new ImagePattern(img)); + double ax = wireXStart - wireXEnd; + double ay = wireYStart - wireYEnd; + double bx = wireXStart - (wireXStart + 5); + double by = wireYStart - wireYStart; + double a = Math.sqrt((ax * ax) + (ay * ay)); + double b = Math.sqrt((bx * bx) + (by * by)); + double ab = (ax * bx) + (ay * by); + double abn = a * b; + double angle = Math.acos(ab / abn) * (180 / Math.PI); + if (wireYEnd < wireYStart) { + cir.setRotate(-angle); + } else { + cir.setRotate(angle); + } + drawArea.getChildren().add(l); + drawArea.getChildren().add(cir); + l.toBack(); + Label relationName = new Label(currentSelectedRelation); + relationName.setLayoutX((l.getStartX() + l.getEndX()) / 2); + relationName.setLayoutY((l.getStartY() + l.getEndY()) / 2); + drawArea.getChildren().add(relationName); + l.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent arg0) { - if(deleteMode == true) { + if (deleteMode == true) { drawArea.getChildren().remove(l); drawArea.getChildren().remove(relationName); drawArea.getChildren().remove(cir); @@ -993,61 +969,60 @@ public void handle(MouseEvent arg0) { arrows.remove(cir); } } - - }); - currentSelectedRelation = null; - drawnWiresList.add(l); - drawnRelationsList.add(relationName); - arrows.add(cir); - } - event.consume(); + + }); + currentSelectedRelation = null; + drawnWiresList.add(l); + drawnRelationsList.add(relationName); + arrows.add(cir); + } + event.consume(); } } - - }); + + }); } - - //Submit base node drawn in draw area + + // Submit base node drawn in draw area public void submitNewBaseNode() { - String identifier = baseNodeIdentPop.getText(); - String semType = baseNodeSemTyPop.getText(); - BaseNodeShape baseNode = new BaseNodeShape(identifier, semType, curX, curY); - Group shape = baseNode.makeShape(); - shape.setLayoutX(curX-50); - shape.setLayoutY(curY-40); - drawArea.getChildren().add(shape); - listOfBaseNodesDrawn.add(baseNode); - baseNodepopBox.setVisible(false); - baseNodeIdentPop.setText(""); - baseNodeSemTyPop.setText(""); - //Delete the node - shape.setOnMouseClicked(new EventHandler() { + String identifier = baseNodeIdentPop.getText(); + String semType = baseNodeSemTyPop.getText(); + BaseNodeShape baseNode = new BaseNodeShape(identifier, semType, curX, curY); + Group shape = baseNode.makeShape(); + shape.setLayoutX(curX - 50); + shape.setLayoutY(curY - 40); + drawArea.getChildren().add(shape); + listOfBaseNodesDrawn.add(baseNode); + baseNodepopBox.setVisible(false); + baseNodeIdentPop.setText(""); + baseNodeSemTyPop.setText(""); + // Delete the node + shape.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent event) { - if(deleteMode == true && wireMode == false) { - double xPos = shape.getLayoutX()+50; - double yPos = shape.getLayoutY()+40; - - for(int i = 0; i() { + + shape.setOnDragDetected(new EventHandler() { @Override public void handle(MouseEvent event) { - if(moveMode == true) { + if (moveMode == true) { Dragboard db = shape.startDragAndDrop(TransferMode.ANY); - ClipboardContent content = new ClipboardContent(); - content.putString("MoveNode"); - db.setContent(content); - event.consume(); - } - } - - }); - - // Moving the node - shape.setOnDragDone(new EventHandler() { - public void handle(DragEvent event) { - if(moveMode == true && wireMode == false) { - double oldPosX = shape.getLayoutX() + 50; - double oldPosY = shape.getLayoutY() + 40; - shape.setLayoutX(curX-50); - shape.setLayoutY(curY-40); - - for(int x = 0; x() { + ClipboardContent content = new ClipboardContent(); + content.putString("MoveNode"); + db.setContent(content); + event.consume(); + } + } + + }); + + // Moving the node + shape.setOnDragDone(new EventHandler() { + public void handle(DragEvent event) { + if (moveMode == true && wireMode == false) { + double oldPosX = shape.getLayoutX() + 50; + double oldPosY = shape.getLayoutY() + 40; + shape.setLayoutX(curX - 50); + shape.setLayoutY(curY - 40); + + for (int x = 0; x < listOfBaseNodesDrawn.size(); x++) { + BaseNodeShape temp = listOfBaseNodesDrawn.get(x); + if (temp == baseNode) { + temp.setX(curX); + temp.setY(curY); + listOfBaseNodesDrawn.set(x, temp); + } + } + + for (int i = 0; i < drawnWiresList.size(); i++) { + Line l = drawnWiresList.get(i); + if (l != null) { + Label lbl = drawnRelationsList.get(i); + Circle c = arrows.get(i); + if (l.getEndX() == oldPosX && l.getEndY() == oldPosY) { + drawnWiresList.get(i).setEndX(curX); + drawnWiresList.get(i).setEndY(curY); + + l.setEndX(curX); + l.setEndY(curY); + + lbl.setLayoutX((l.getStartX() + l.getEndX()) / 2); + lbl.setLayoutY((l.getStartY() + l.getEndY()) / 2); + drawnRelationsList.get(i).setLayoutX((l.getStartX() + l.getEndX()) / 2); + drawnRelationsList.get(i).setLayoutY((l.getStartY() + l.getEndY()) / 2); + + double vx = l.getEndX() - l.getStartX(); + double vy = l.getEndY() - l.getStartY(); + double vn = Math.sqrt((vx * vx) + (vy * vy)); + double vnx = vx / vn; + double vny = vy / vn; + double td = (vx * vx) + (vy * vy); + double d = Math.sqrt(td) - 50; + double newX = l.getStartX() + (d * vnx); + double newY = l.getStartY() + (d * vny); + c.setCenterX(newX); + c.setCenterY(newY); + double ax = l.getStartX() - l.getEndX(); + double ay = l.getStartY() - l.getEndY(); + double bx = l.getStartX() - (l.getStartX() + 5); + double by = 0; + double a = Math.sqrt((ax * ax) + (ay * ay)); + double b = Math.sqrt((bx * bx) + (by * by)); + double ab = (ax * bx) + (ay * by); + double abn = a * b; + double angle = Math.acos(ab / abn) * (180 / Math.PI); + if (l.getEndY() < l.getStartY()) { + c.setRotate(-angle); + } else { + c.setRotate(angle); + } + } + } + } + event.consume(); + } + } + }); + + shape.setOnDragDropped(new EventHandler() { @Override public void handle(DragEvent event) { - if(wireMode == true) { + if (wireMode == true) { Dragboard db = event.getDragboard(); - if(db.getString() == "wireMode" && currentSelectedRelation != null) { - wireXEnd = shape.getLayoutX() + 50; - wireYEnd = shape.getLayoutY() + 40; - WireRelation wr = new WireRelation(wireXStart, wireYStart, wireXEnd, wireYEnd); - Line l = wr.drawLine(); - double vx = wireXEnd - wireXStart; - double vy = wireYEnd - wireYStart; - double vn = Math.sqrt((vx*vx) + (vy*vy)); - double vnx = vx/vn; - double vny = vy/vn; - double td = (vx*vx) + (vy*vy); - double d = Math.sqrt(td) -50; - double newX = wireXStart + (d*vnx); - double newY = wireYStart + (d*vny); - Circle cir = new Circle(); - cir.setCenterX(newX); - cir.setCenterY(newY); - cir.setRadius(12.5); - Image img = new Image("sneps/gui/AH.png"); - cir.setFill(new ImagePattern(img)); - double ax = wireXStart - wireXEnd; - double ay = wireYStart - wireYEnd; - double bx = wireXStart - (wireXStart + 5); - double by = wireYStart - wireYStart; - double a = Math.sqrt((ax*ax) + (ay*ay)); - double b = Math.sqrt((bx*bx) + (by*by)); - double ab = (ax*bx) + (ay*by); - double abn = a * b; - double angle = Math.acos(ab/abn) * (180/Math.PI); - if(wireYEnd < wireYStart) { - cir.setRotate(-angle); - } - else { - cir.setRotate(angle); - } - drawArea.getChildren().add(l); - drawArea.getChildren().add(cir); - l.toBack(); - Label relationName = new Label(currentSelectedRelation); - relationName.setLayoutX((l.getStartX() + l.getEndX()) / 2); - relationName.setLayoutY((l.getStartY() + l.getEndY()) / 2); - drawArea.getChildren().add(relationName); - l.setOnMouseClicked(new EventHandler() { + if (db.getString() == "wireMode" && currentSelectedRelation != null) { + wireXEnd = shape.getLayoutX() + 50; + wireYEnd = shape.getLayoutY() + 40; + WireRelation wr = new WireRelation(wireXStart, wireYStart, wireXEnd, wireYEnd); + Line l = wr.drawLine(); + double vx = wireXEnd - wireXStart; + double vy = wireYEnd - wireYStart; + double vn = Math.sqrt((vx * vx) + (vy * vy)); + double vnx = vx / vn; + double vny = vy / vn; + double td = (vx * vx) + (vy * vy); + double d = Math.sqrt(td) - 50; + double newX = wireXStart + (d * vnx); + double newY = wireYStart + (d * vny); + Circle cir = new Circle(); + cir.setCenterX(newX); + cir.setCenterY(newY); + cir.setRadius(12.5); + Image img = new Image("sneps/gui/AH.png"); + cir.setFill(new ImagePattern(img)); + double ax = wireXStart - wireXEnd; + double ay = wireYStart - wireYEnd; + double bx = wireXStart - (wireXStart + 5); + double by = wireYStart - wireYStart; + double a = Math.sqrt((ax * ax) + (ay * ay)); + double b = Math.sqrt((bx * bx) + (by * by)); + double ab = (ax * bx) + (ay * by); + double abn = a * b; + double angle = Math.acos(ab / abn) * (180 / Math.PI); + if (wireYEnd < wireYStart) { + cir.setRotate(-angle); + } else { + cir.setRotate(angle); + } + drawArea.getChildren().add(l); + drawArea.getChildren().add(cir); + l.toBack(); + Label relationName = new Label(currentSelectedRelation); + relationName.setLayoutX((l.getStartX() + l.getEndX()) / 2); + relationName.setLayoutY((l.getStartY() + l.getEndY()) / 2); + drawArea.getChildren().add(relationName); + l.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent arg0) { - if(deleteMode == true) { + if (deleteMode == true) { drawArea.getChildren().remove(l); drawArea.getChildren().remove(relationName); drawArea.getChildren().remove(cir); drawnWiresList.remove(l); drawnRelationsList.remove(relationName); arrows.remove(cir); - + } } - - }); - currentSelectedRelation = null; - drawnWiresList.add(l); - drawnRelationsList.add(relationName); - arrows.add(cir); - } - event.consume(); + + }); + currentSelectedRelation = null; + drawnWiresList.add(l); + drawnRelationsList.add(relationName); + arrows.add(cir); + } + event.consume(); } } - - }); + + }); } - //Submit existing variable node drawn in draw area + // Submit existing variable node drawn in draw area public void submitExistVariableNode() { - String varNode = variableNodesList.getSelectionModel().getSelectedItem(); - Node n = null; - try { - n = Network.getNode(varNode); - } catch (NodeNotFoundInNetworkException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - String identifier = n.getIdentifier(); - VarNodeShape varNodeS = new VarNodeShape(identifier, curX, curY); - listOfVarNodesDrawn.add(varNodeS); - Group shape = varNodeS.makeShape(); - shape.setLayoutX(curX-50); - shape.setLayoutY(curY-40); - drawArea.getChildren().add(shape); - varNodepopBox.setVisible(false); - //Delete the node - shape.setOnMouseClicked(new EventHandler() { + String varNode = variableNodesList.getSelectionModel().getSelectedItem(); + Node n = null; + try { + n = Network.getNode(varNode); + } catch (NodeNotFoundInNetworkException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + String identifier = n.getIdentifier(); + VarNodeShape varNodeS = new VarNodeShape(identifier, curX, curY); + listOfVarNodesDrawn.add(varNodeS); + Group shape = varNodeS.makeShape(); + shape.setLayoutX(curX - 50); + shape.setLayoutY(curY - 40); + drawArea.getChildren().add(shape); + varNodepopBox.setVisible(false); + // Delete the node + shape.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent event) { - if(deleteMode == true && wireMode == false) { - double xPos = shape.getLayoutX()+50; - double yPos = shape.getLayoutY()+40; - - for(int i = 0; i() { + + shape.setOnDragDetected(new EventHandler() { @Override public void handle(MouseEvent event) { - if(moveMode == true) { + if (moveMode == true) { Dragboard db = shape.startDragAndDrop(TransferMode.ANY); - ClipboardContent content = new ClipboardContent(); - content.putString("MoveNode"); - db.setContent(content); - event.consume(); - } - } - - }); - - // Moving the node - shape.setOnDragDone(new EventHandler() { - public void handle(DragEvent event) { - if(moveMode == true && wireMode == false) { - double oldPosX = shape.getLayoutX() + 50; - double oldPosY = shape.getLayoutY() + 40; - shape.setLayoutX(curX-50); - shape.setLayoutY(curY-40); - - - for(int x = 0; x() { + ClipboardContent content = new ClipboardContent(); + content.putString("MoveNode"); + db.setContent(content); + event.consume(); + } + } + + }); + + // Moving the node + shape.setOnDragDone(new EventHandler() { + public void handle(DragEvent event) { + if (moveMode == true && wireMode == false) { + double oldPosX = shape.getLayoutX() + 50; + double oldPosY = shape.getLayoutY() + 40; + shape.setLayoutX(curX - 50); + shape.setLayoutY(curY - 40); + + for (int x = 0; x < listOfVarNodesDrawn.size(); x++) { + VarNodeShape temp = listOfVarNodesDrawn.get(x); + if (temp == varNodeS) { + temp.setX(curX); + temp.setY(curY); + listOfVarNodesDrawn.set(x, temp); + } + } + + for (int i = 0; i < drawnWiresList.size(); i++) { + Line l = drawnWiresList.get(i); + if (l != null) { + Label lbl = drawnRelationsList.get(i); + Circle c = arrows.get(i); + if (l.getEndX() == oldPosX && l.getEndY() == oldPosY) { + drawnWiresList.get(i).setEndX(curX); + drawnWiresList.get(i).setEndY(curY); + + l.setEndX(curX); + l.setEndY(curY); + + lbl.setLayoutX((l.getStartX() + l.getEndX()) / 2); + lbl.setLayoutY((l.getStartY() + l.getEndY()) / 2); + drawnRelationsList.get(i).setLayoutX((l.getStartX() + l.getEndX()) / 2); + drawnRelationsList.get(i).setLayoutY((l.getStartY() + l.getEndY()) / 2); + + double vx = l.getEndX() - l.getStartX(); + double vy = l.getEndY() - l.getStartY(); + double vn = Math.sqrt((vx * vx) + (vy * vy)); + double vnx = vx / vn; + double vny = vy / vn; + double td = (vx * vx) + (vy * vy); + double d = Math.sqrt(td) - 50; + double newX = l.getStartX() + (d * vnx); + double newY = l.getStartY() + (d * vny); + c.setCenterX(newX); + c.setCenterY(newY); + double ax = l.getStartX() - l.getEndX(); + double ay = l.getStartY() - l.getEndY(); + double bx = l.getStartX() - (l.getStartX() + 5); + double by = 0; + double a = Math.sqrt((ax * ax) + (ay * ay)); + double b = Math.sqrt((bx * bx) + (by * by)); + double ab = (ax * bx) + (ay * by); + double abn = a * b; + double angle = Math.acos(ab / abn) * (180 / Math.PI); + if (l.getEndY() < l.getStartY()) { + c.setRotate(-angle); + } else { + c.setRotate(angle); + } + } + } + } + event.consume(); + } + } + }); + + shape.setOnDragDropped(new EventHandler() { @Override public void handle(DragEvent event) { - if(wireMode == true) { + if (wireMode == true) { Dragboard db = event.getDragboard(); - if(db.getString() == "wireMode" && currentSelectedRelation != null) { - wireXEnd = shape.getLayoutX() + 50; - wireYEnd = shape.getLayoutY() + 40; - WireRelation wr = new WireRelation(wireXStart, wireYStart, wireXEnd, wireYEnd); - Line l = wr.drawLine(); - double vx = wireXEnd - wireXStart; - double vy = wireYEnd - wireYStart; - double vn = Math.sqrt((vx*vx) + (vy*vy)); - double vnx = vx/vn; - double vny = vy/vn; - double td = (vx*vx) + (vy*vy); - double d = Math.sqrt(td) -50; - double newX = wireXStart + (d*vnx); - double newY = wireYStart + (d*vny); - Circle cir = new Circle(); - cir.setCenterX(newX); - cir.setCenterY(newY); - cir.setRadius(12.5); - Image img = new Image("sneps/gui/AH.png"); - cir.setFill(new ImagePattern(img)); - double ax = wireXStart - wireXEnd; - double ay = wireYStart - wireYEnd; - double bx = wireXStart - (wireXStart + 5); - double by = wireYStart - wireYStart; - double a = Math.sqrt((ax*ax) + (ay*ay)); - double b = Math.sqrt((bx*bx) + (by*by)); - double ab = (ax*bx) + (ay*by); - double abn = a * b; - double angle = Math.acos(ab/abn) * (180/Math.PI); - if(wireYEnd < wireYStart) { - cir.setRotate(-angle); - } - else { - cir.setRotate(angle); - } - drawArea.getChildren().add(l); - drawArea.getChildren().add(cir); - l.toBack(); - Label relationName = new Label(currentSelectedRelation); - relationName.setLayoutX((l.getStartX() + l.getEndX()) / 2); - relationName.setLayoutY((l.getStartY() + l.getEndY()) / 2); - drawArea.getChildren().add(relationName); - l.setOnMouseClicked(new EventHandler() { + if (db.getString() == "wireMode" && currentSelectedRelation != null) { + wireXEnd = shape.getLayoutX() + 50; + wireYEnd = shape.getLayoutY() + 40; + WireRelation wr = new WireRelation(wireXStart, wireYStart, wireXEnd, wireYEnd); + Line l = wr.drawLine(); + double vx = wireXEnd - wireXStart; + double vy = wireYEnd - wireYStart; + double vn = Math.sqrt((vx * vx) + (vy * vy)); + double vnx = vx / vn; + double vny = vy / vn; + double td = (vx * vx) + (vy * vy); + double d = Math.sqrt(td) - 50; + double newX = wireXStart + (d * vnx); + double newY = wireYStart + (d * vny); + Circle cir = new Circle(); + cir.setCenterX(newX); + cir.setCenterY(newY); + cir.setRadius(12.5); + Image img = new Image("sneps/gui/AH.png"); + cir.setFill(new ImagePattern(img)); + double ax = wireXStart - wireXEnd; + double ay = wireYStart - wireYEnd; + double bx = wireXStart - (wireXStart + 5); + double by = wireYStart - wireYStart; + double a = Math.sqrt((ax * ax) + (ay * ay)); + double b = Math.sqrt((bx * bx) + (by * by)); + double ab = (ax * bx) + (ay * by); + double abn = a * b; + double angle = Math.acos(ab / abn) * (180 / Math.PI); + if (wireYEnd < wireYStart) { + cir.setRotate(-angle); + } else { + cir.setRotate(angle); + } + drawArea.getChildren().add(l); + drawArea.getChildren().add(cir); + l.toBack(); + Label relationName = new Label(currentSelectedRelation); + relationName.setLayoutX((l.getStartX() + l.getEndX()) / 2); + relationName.setLayoutY((l.getStartY() + l.getEndY()) / 2); + drawArea.getChildren().add(relationName); + l.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent arg0) { - if(deleteMode == true) { + if (deleteMode == true) { drawArea.getChildren().remove(l); drawArea.getChildren().remove(relationName); drawArea.getChildren().remove(cir); @@ -1431,60 +1399,59 @@ public void handle(MouseEvent arg0) { arrows.remove(cir); } } - - }); - currentSelectedRelation = null; - drawnWiresList.add(l); - drawnRelationsList.add(relationName); - arrows.add(cir); - } - event.consume(); + + }); + currentSelectedRelation = null; + drawnWiresList.add(l); + drawnRelationsList.add(relationName); + arrows.add(cir); + } + event.consume(); } } - - }); + + }); } - - //Submit new variable node drawn in draw area + + // Submit new variable node drawn in draw area public void submitNewVariableNode() { - Node n = Network.buildVariableNode(); - String identifier = n.getIdentifier(); - VarNodeShape varNode = new VarNodeShape(identifier, curX, curY); - Group shape = varNode.makeShape(); - shape.setLayoutX(curX-50); - shape.setLayoutY(curY-40); - drawArea.getChildren().add(shape); - listOfVarNodesDrawn.add(varNode); - varNodepopBox.setVisible(false); - updateNodesList(); - //Delete the node - shape.setOnMouseClicked(new EventHandler() { + Node n = Network.buildVariableNode(); + String identifier = n.getIdentifier(); + VarNodeShape varNode = new VarNodeShape(identifier, curX, curY); + Group shape = varNode.makeShape(); + shape.setLayoutX(curX - 50); + shape.setLayoutY(curY - 40); + drawArea.getChildren().add(shape); + listOfVarNodesDrawn.add(varNode); + varNodepopBox.setVisible(false); + updateNodesList(); + // Delete the node + shape.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent event) { - if(deleteMode == true && wireMode == false) { - double xPos = shape.getLayoutX()+50; - double yPos = shape.getLayoutY()+40; - - for(int i = 0; i() { + + shape.setOnDragDetected(new EventHandler() { @Override public void handle(MouseEvent event) { - if(moveMode == true) { + if (moveMode == true) { Dragboard db = shape.startDragAndDrop(TransferMode.ANY); - ClipboardContent content = new ClipboardContent(); - content.putString("MoveNode"); - db.setContent(content); - event.consume(); - } - } - - }); - - // Moving the node - shape.setOnDragDone(new EventHandler() { - public void handle(DragEvent event) { - if(moveMode == true && wireMode == false) { - double oldPosX = shape.getLayoutX() + 50; - double oldPosY = shape.getLayoutY() + 40; - shape.setLayoutX(curX-50); - shape.setLayoutY(curY-40); - - for(int x = 0; x() { + ClipboardContent content = new ClipboardContent(); + content.putString("MoveNode"); + db.setContent(content); + event.consume(); + } + } + + }); + + // Moving the node + shape.setOnDragDone(new EventHandler() { + public void handle(DragEvent event) { + if (moveMode == true && wireMode == false) { + double oldPosX = shape.getLayoutX() + 50; + double oldPosY = shape.getLayoutY() + 40; + shape.setLayoutX(curX - 50); + shape.setLayoutY(curY - 40); + + for (int x = 0; x < listOfVarNodesDrawn.size(); x++) { + VarNodeShape temp = listOfVarNodesDrawn.get(x); + if (temp == varNode) { + temp.setX(curX); + temp.setY(curY); + listOfVarNodesDrawn.set(x, temp); + } + } + + for (int i = 0; i < drawnWiresList.size(); i++) { + Line l = drawnWiresList.get(i); + if (l != null) { + Label lbl = drawnRelationsList.get(i); + Circle c = arrows.get(i); + if (l.getEndX() == oldPosX && l.getEndY() == oldPosY) { + drawnWiresList.get(i).setEndX(curX); + drawnWiresList.get(i).setEndY(curY); + + l.setEndX(curX); + l.setEndY(curY); + + lbl.setLayoutX((l.getStartX() + l.getEndX()) / 2); + lbl.setLayoutY((l.getStartY() + l.getEndY()) / 2); + drawnRelationsList.get(i).setLayoutX((l.getStartX() + l.getEndX()) / 2); + drawnRelationsList.get(i).setLayoutY((l.getStartY() + l.getEndY()) / 2); + + double vx = l.getEndX() - l.getStartX(); + double vy = l.getEndY() - l.getStartY(); + double vn = Math.sqrt((vx * vx) + (vy * vy)); + double vnx = vx / vn; + double vny = vy / vn; + double td = (vx * vx) + (vy * vy); + double d = Math.sqrt(td) - 50; + double newX = l.getStartX() + (d * vnx); + double newY = l.getStartY() + (d * vny); + c.setCenterX(newX); + c.setCenterY(newY); + double ax = l.getStartX() - l.getEndX(); + double ay = l.getStartY() - l.getEndY(); + double bx = l.getStartX() - (l.getStartX() + 5); + double by = 0; + double a = Math.sqrt((ax * ax) + (ay * ay)); + double b = Math.sqrt((bx * bx) + (by * by)); + double ab = (ax * bx) + (ay * by); + double abn = a * b; + double angle = Math.acos(ab / abn) * (180 / Math.PI); + if (l.getEndY() < l.getStartY()) { + c.setRotate(-angle); + } else { + c.setRotate(angle); + } + } + } + } + event.consume(); + } + } + }); + + shape.setOnDragDropped(new EventHandler() { @Override public void handle(DragEvent event) { - if(wireMode == true) { + if (wireMode == true) { Dragboard db = event.getDragboard(); - if(db.getString() == "wireMode" && currentSelectedRelation != null) { - wireXEnd = shape.getLayoutX() + 50; - wireYEnd = shape.getLayoutY() + 40; - WireRelation wr = new WireRelation(wireXStart, wireYStart, wireXEnd, wireYEnd); - Line l = wr.drawLine(); - double vx = wireXEnd - wireXStart; - double vy = wireYEnd - wireYStart; - double vn = Math.sqrt((vx*vx) + (vy*vy)); - double vnx = vx/vn; - double vny = vy/vn; - double td = (vx*vx) + (vy*vy); - double d = Math.sqrt(td) -50; - double newX = wireXStart + (d*vnx); - double newY = wireYStart + (d*vny); - Circle cir = new Circle(); - cir.setCenterX(newX); - cir.setCenterY(newY); - cir.setRadius(12.5); - Image img = new Image("sneps/gui/AH.png"); - cir.setFill(new ImagePattern(img)); - double ax = wireXStart - wireXEnd; - double ay = wireYStart - wireYEnd; - double bx = wireXStart - (wireXStart + 5); - double by = wireYStart - wireYStart; - double a = Math.sqrt((ax*ax) + (ay*ay)); - double b = Math.sqrt((bx*bx) + (by*by)); - double ab = (ax*bx) + (ay*by); - double abn = a * b; - double angle = Math.acos(ab/abn) * (180/Math.PI); - if(wireYEnd < wireYStart) { - cir.setRotate(-angle); - } - else { - cir.setRotate(angle); - } - drawArea.getChildren().add(l); - drawArea.getChildren().add(cir); - l.toBack(); - Label relationName = new Label(currentSelectedRelation); - relationName.setLayoutX((l.getStartX() + l.getEndX()) / 2); - relationName.setLayoutY((l.getStartY() + l.getEndY()) / 2); - drawArea.getChildren().add(relationName); - l.setOnMouseClicked(new EventHandler() { + if (db.getString() == "wireMode" && currentSelectedRelation != null) { + wireXEnd = shape.getLayoutX() + 50; + wireYEnd = shape.getLayoutY() + 40; + WireRelation wr = new WireRelation(wireXStart, wireYStart, wireXEnd, wireYEnd); + Line l = wr.drawLine(); + double vx = wireXEnd - wireXStart; + double vy = wireYEnd - wireYStart; + double vn = Math.sqrt((vx * vx) + (vy * vy)); + double vnx = vx / vn; + double vny = vy / vn; + double td = (vx * vx) + (vy * vy); + double d = Math.sqrt(td) - 50; + double newX = wireXStart + (d * vnx); + double newY = wireYStart + (d * vny); + Circle cir = new Circle(); + cir.setCenterX(newX); + cir.setCenterY(newY); + cir.setRadius(12.5); + Image img = new Image("sneps/gui/AH.png"); + cir.setFill(new ImagePattern(img)); + double ax = wireXStart - wireXEnd; + double ay = wireYStart - wireYEnd; + double bx = wireXStart - (wireXStart + 5); + double by = wireYStart - wireYStart; + double a = Math.sqrt((ax * ax) + (ay * ay)); + double b = Math.sqrt((bx * bx) + (by * by)); + double ab = (ax * bx) + (ay * by); + double abn = a * b; + double angle = Math.acos(ab / abn) * (180 / Math.PI); + if (wireYEnd < wireYStart) { + cir.setRotate(-angle); + } else { + cir.setRotate(angle); + } + drawArea.getChildren().add(l); + drawArea.getChildren().add(cir); + l.toBack(); + Label relationName = new Label(currentSelectedRelation); + relationName.setLayoutX((l.getStartX() + l.getEndX()) / 2); + relationName.setLayoutY((l.getStartY() + l.getEndY()) / 2); + drawArea.getChildren().add(relationName); + l.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent arg0) { - if(deleteMode == true) { + if (deleteMode == true) { drawArea.getChildren().remove(l); drawArea.getChildren().remove(relationName); drawArea.getChildren().remove(cir); @@ -1646,21 +1610,21 @@ public void handle(MouseEvent arg0) { arrows.remove(cir); } } - - }); - currentSelectedRelation = null; - drawnWiresList.add(l); - drawnRelationsList.add(relationName); - arrows.add(cir); - } - event.consume(); + + }); + currentSelectedRelation = null; + drawnWiresList.add(l); + drawnRelationsList.add(relationName); + arrows.add(cir); + } + event.consume(); } } - - }); + + }); } - //Selects the delete node/relation mode + // Selects the delete node/relation mode public void deleteMode() { moveMode = false; deleteMode = true; @@ -1672,8 +1636,8 @@ public void deleteMode() { deleteModeBtn.getStyleClass().add("customBtnSelected"); popUpNotification("Delete Mode", "Delete Node", "Delete Node Mode Selected", 1); } - - //Selects the move node mode + + // Selects the move node mode public void moveMode() { moveMode = true; deleteMode = false; @@ -1687,7 +1651,7 @@ public void moveMode() { popUpNotification("Move Mode", "Move Node", "Move Node Mode Selected", 1); } - //Selects the draw mode + // Selects the draw mode public void normalMode() { moveMode = false; deleteMode = false; @@ -1697,15 +1661,16 @@ public void normalMode() { deleteModeBtn.getStyleClass().add("customBtn"); moveModeBtn.getStyleClass().add("customBtn"); drawModeBtn.getStyleClass().add("customBtnSelected"); - //popUpNotification("Draw Mode", "Draw Nodes", "Draw Nodes & Wires Mode Selected", 1); - + // popUpNotification("Draw Mode", "Draw Nodes", "Draw Nodes & Wires Mode + // Selected", 1); + } - //Creates the drawn base nodes in the network + // Creates the drawn base nodes in the network public void submitDrawnBaseNodes() { - for (int i = 0; i wires = new ArrayList(); RelationsRestrictedCaseFrame cf = (RelationsRestrictedCaseFrame) temp.getCf(); double x = temp.getX(); double y = temp.getY(); - for(int j = 0; j wires = new ArrayList(); RelationsRestrictedCaseFrame cf = (RelationsRestrictedCaseFrame) mns.getCf(); double x = mns.getX(); double y = mns.getY(); - for(int j = 0; j() { @Override public void handle(MouseEvent event) { - if(wireMode == false && moveMode == false && deleteMode == false) { + if (wireMode == false && moveMode == false && deleteMode == false) { wireMode = true; wireBtnRect.setVisible(true); popUpNotification("Wire Mode", "Draw Wire", "Draw Wire Mode Selected", 1); - } - else { + } else { wireMode = false; wireBtnRect.setVisible(false); } } - + }); } - + public void popUpNotification(String title, String header, String content, int duration) { - Alert alert = new Alert( Alert.AlertType.NONE ); - alert.setTitle(title); - alert.setHeaderText(header); - alert.setContentText(content); - Timeline idlestage = new Timeline(new KeyFrame(Duration.seconds(duration), new EventHandler() - { - @Override - public void handle( ActionEvent event ) - { - alert.setResult(ButtonType.CANCEL); - alert.hide(); - } - } ) ); - idlestage.setCycleCount(1); - idlestage.play(); - alert.showAndWait(); - } - - //Returns a list of the relations of a case frame - public LinkedList drawAreaRelations(String caseFrame){ + Alert alert = new Alert(Alert.AlertType.NONE); + alert.setTitle(title); + alert.setHeaderText(header); + alert.setContentText(content); + Timeline idlestage = new Timeline(new KeyFrame(Duration.seconds(duration), new EventHandler() { + @Override + public void handle(ActionEvent event) { + alert.setResult(ButtonType.CANCEL); + alert.hide(); + } + })); + idlestage.setCycleCount(1); + idlestage.play(); + alert.showAndWait(); + } + + // Returns a list of the relations of a case frame + public LinkedList drawAreaRelations(String caseFrame) { CaseFrame cf = null; try { cf = Network.getCaseFrame(caseFrame); @@ -2058,22 +2021,12 @@ public LinkedList drawAreaRelations(String caseFrame){ } return cf.getRelations(); } - - - + //..........END of Drawing the Network Methods.......................... - - - - - - - - - + //..........Traditional Menu Methods................................... - //Update Semantic Type Lists - + // Update Semantic Type Lists + public void updateSemanticLists() { Hashtable sems = SemanticHierarchy.getSemantics(); baseNodeSemType.getItems().clear(); @@ -2082,7 +2035,7 @@ public void updateSemanticLists() { resultSemType.getItems().clear(); cableSem.getItems().clear(); baseNodeSemTyPop.getItems().clear(); - for(Entry entry : sems.entrySet()) { + for (Entry entry : sems.entrySet()) { String semantic = entry.getKey(); MenuItem mi1 = new MenuItem(semantic); mi1.setOnAction(new EventHandler() { @@ -2091,9 +2044,9 @@ public void updateSemanticLists() { public void handle(ActionEvent event) { baseNodeSemType.setText(mi1.getText()); } - + }); - + MenuItem mi2 = new MenuItem(semantic); mi2.setOnAction(new EventHandler() { @@ -2101,9 +2054,9 @@ public void handle(ActionEvent event) { public void handle(ActionEvent event) { newRT.setText(mi2.getText()); } - + }); - + MenuItem mi3 = new MenuItem(semantic); mi3.setOnAction(new EventHandler() { @@ -2111,9 +2064,9 @@ public void handle(ActionEvent event) { public void handle(ActionEvent event) { rrcfSem.setText(mi3.getText()); } - + }); - + MenuItem mi4 = new MenuItem(semantic); mi4.setOnAction(new EventHandler() { @@ -2121,9 +2074,9 @@ public void handle(ActionEvent event) { public void handle(ActionEvent event) { resultSemType.setText(mi4.getText()); } - + }); - + MenuItem mi5 = new MenuItem(semantic); mi5.setOnAction(new EventHandler() { @@ -2131,9 +2084,9 @@ public void handle(ActionEvent event) { public void handle(ActionEvent event) { cableSem.setText(mi5.getText()); } - + }); - + MenuItem mi6 = new MenuItem(semantic); mi6.setOnAction(new EventHandler() { @@ -2141,10 +2094,9 @@ public void handle(ActionEvent event) { public void handle(ActionEvent event) { baseNodeSemTyPop.setText(mi6.getText()); } - + }); - - + baseNodeSemType.getItems().add(mi1); newRT.getItems().add(mi2); rrcfSem.getItems().add(mi3); @@ -2153,8 +2105,8 @@ public void handle(ActionEvent event) { baseNodeSemTyPop.getItems().add(mi6); } } - - //Parent Semantics + + // Parent Semantics public void parentSemantics() { MenuItem individual = new MenuItem(Semantic.individual.getSemanticType()); MenuItem infimum = new MenuItem(Semantic.infimum.getSemanticType()); @@ -2162,34 +2114,35 @@ public void parentSemantics() { @Override public void handle(ActionEvent arg0) { - parentSemChoice.setText(individual.getText()); + parentSemChoice.setText(individual.getText()); } - + }); - + infimum.setOnAction(new EventHandler() { @Override public void handle(ActionEvent arg0) { - parentSemChoice.setText(infimum.getText()); + parentSemChoice.setText(infimum.getText()); } - + }); - + parentSemChoice.getItems().add(individual); parentSemChoice.getItems().add(infimum); - + } - - //Create new semantic type + + // Create new semantic type public void createSemanticType() { String semName = semanticName.getText(); SemanticHierarchy.createSemanticType(semName); updateSemanticLists(); - popUpNotification("Create Semantic Type", "Semantic Created Successfully", "Semantic: " + semName + " Created Successfully", 2); + popUpNotification("Create Semantic Type", "Semantic Created Successfully", + "Semantic: " + semName + " Created Successfully", 2); } - - //Adjusts + + // Adjusts public void createAdjusts() { MenuItem none = new MenuItem("None"); none.setOnAction(new EventHandler() { @@ -2197,67 +2150,66 @@ public void createAdjusts() { @Override public void handle(ActionEvent arg0) { newRA.setText("None"); - //System.out.println("None"); + // System.out.println("None"); } - + }); - + MenuItem expand = new MenuItem("Expand"); expand.setOnAction(new EventHandler() { @Override public void handle(ActionEvent arg0) { newRA.setText("Expand"); - //System.out.println("Expand"); + // System.out.println("Expand"); } - + }); - + MenuItem reduce = new MenuItem("Reduce"); reduce.setOnAction(new EventHandler() { @Override public void handle(ActionEvent arg0) { newRA.setText("Reduce"); - //System.out.println("Reduce"); + // System.out.println("Reduce"); } - + }); - + MenuItem none1 = new MenuItem("None"); none1.setOnAction(new EventHandler() { @Override public void handle(ActionEvent arg0) { overrideAdjust.setText("None"); - //System.out.println("None"); + // System.out.println("None"); } - + }); - + MenuItem expand1 = new MenuItem("Expand"); expand1.setOnAction(new EventHandler() { @Override public void handle(ActionEvent arg0) { overrideAdjust.setText("Expand"); - //System.out.println("Expand"); + // System.out.println("Expand"); } - + }); - + MenuItem reduce1 = new MenuItem("Reduce"); reduce1.setOnAction(new EventHandler() { @Override public void handle(ActionEvent arg0) { overrideAdjust.setText("Reduce"); - //System.out.println("Reduce"); + // System.out.println("Reduce"); } - + }); - - + newRA.getItems().add(none); newRA.getItems().add(expand); newRA.getItems().add(reduce); @@ -2265,38 +2217,38 @@ public void handle(ActionEvent arg0) { overrideAdjust.getItems().add(expand1); overrideAdjust.getItems().add(reduce1); } - - //Define relation menu-based + + // Define relation menu-based public void defineRelation() { String name = newRN.getText(); String type = newRT.getText(); String adjust = newRA.getText(); int limit = Integer.parseInt(newRL.getText()); - if(limit > 0) { + if (limit > 0) { Network.defineRelation(name, type, adjust, limit); Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Relation created"); alert.setHeaderText("Relation is created successfully"); alert.setContentText("The relation " + name + " is created successfully!"); alert.showAndWait(); - }else { + } else { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Relation NOT created"); alert.setHeaderText("Relation is NOT created successfully"); alert.setContentText("Limit should be greater than 0!"); alert.showAndWait(); } - + newRN.setText(""); newRT.setText(""); newRA.setText(""); newRL.setText(""); - + updateRelationSetList(); - + } - - //Undefine relation menu-based + + // Undefine relation menu-based public void undefineRelation() { String selectedRelation = relationSetList.getSelectionModel().getSelectedItem(); try { @@ -2315,7 +2267,7 @@ public void undefineRelation() { } } - //Updates all relations list + // Updates all relations list public void updateRelationSetList() { Hashtable relations = Network.getRelations(); ArrayList sortedRelations = new ArrayList(); @@ -2324,11 +2276,11 @@ public void updateRelationSetList() { pathRelations.getItems().clear(); definePathRelations.getItems().clear(); for (Entry entry : relations.entrySet()) { - String key = entry.getKey(); - sortedRelations.add(key); + String key = entry.getKey(); + sortedRelations.add(key); } Collections.sort(sortedRelations); - for(int i = 0; i caseFrameList = new LinkedList(); - for(int i=0; i< cfRS.getItems().size(); i++){ + for (int i = 0; i < cfRS.getItems().size(); i++) { String rName = cfRS.getItems().get(i); try { Relation r = Network.getRelation(rName); @@ -2377,7 +2330,7 @@ public void submitCaseFrame() { e.printStackTrace(); } } - + CaseFrame cf = Network.defineCaseFrame(semanticType, caseFrameList); String name = cf.getId(); Alert a = new Alert(AlertType.INFORMATION); @@ -2391,7 +2344,7 @@ public void submitCaseFrame() { cfRS.getItems().clear(); } - //Update all list of case frames + // Update all list of case frames public void updateCaseFramesList() { caseFramesList.getItems().clear(); caseFrameChoice.getItems().clear(); @@ -2402,21 +2355,21 @@ public void updateCaseFramesList() { Hashtable caseFrames = Network.getCaseFrames(); ArrayList sortedCFs = new ArrayList(); for (Entry entry : caseFrames.entrySet()) { - String key = entry.getKey(); - sortedCFs.add(key); + String key = entry.getKey(); + sortedCFs.add(key); } Collections.sort(sortedCFs); - - for(int i = 0; i() { + caseFramesList.getItems().add(key); + caseFramesDrawList.getItems().add(key); + selectCFForSign.getItems().add(key); + cfListForSign.getItems().add(key); + item.setOnAction(new EventHandler() { @Override public void handle(ActionEvent arg0) { @@ -2426,18 +2379,18 @@ public void handle(ActionEvent arg0) { curRRCF = (RelationsRestrictedCaseFrame) cf; LinkedList relations = cf.getRelations(); caseFrameRelationList.getItems().clear(); - for(Relation r : relations) { + for (Relation r : relations) { caseFrameRelationList.getItems().add(r.getName()); } - + } catch (CaseFrameWithSetOfRelationsNotFoundException e) { e.printStackTrace(); } } - - }); - caseFrameChoice.getItems().add(item); - item2.setOnAction(new EventHandler() { + + }); + caseFrameChoice.getItems().add(item); + item2.setOnAction(new EventHandler() { @Override public void handle(ActionEvent arg0) { @@ -2449,22 +2402,22 @@ public void handle(ActionEvent arg0) { curRRCF = (RelationsRestrictedCaseFrame) cf; LinkedList relations = cf.getRelations(); caseFrameRelationList.getItems().clear(); - for(Relation r : relations) { + for (Relation r : relations) { pathRelations.getItems().add(r.getName()); } - + } catch (CaseFrameWithSetOfRelationsNotFoundException e) { e.printStackTrace(); } pathRelations.setDisable(false); createPathBTN.setDisable(false); } - - }); - pathCF.getItems().add(item2); + + }); + pathCF.getItems().add(item2); } } - + public void addRelsToListSign() { selectCFForSign.setOnMouseClicked(new EventHandler() { @@ -2481,21 +2434,21 @@ public void handle(MouseEvent arg0) { RelationsRestrictedCaseFrame rrcf = (RelationsRestrictedCaseFrame) cf; LinkedList relations = rrcf.getRelations(); selectCFRelForSign.getItems().clear(); - for(Relation r : relations) { + for (Relation r : relations) { selectCFRelForSign.getItems().add(r.getName()); } - + } - + }); } - //Undefine case frames - menu-based + // Undefine case frames - menu-based public void undefineCaseFrame() { String caseFrame = caseFramesList.getSelectionModel().getSelectedItem(); Hashtable cframes = Network.getCaseFrames(); CaseFrame cf = cframes.get(caseFrame); - + ButtonType yes = new ButtonType("Yes"); ButtonType cancel = new ButtonType("Cancel"); Alert a = new Alert(AlertType.NONE, "Promote pawn to:", yes, cancel); @@ -2504,26 +2457,27 @@ public void undefineCaseFrame() { a.setResizable(false); a.setContentText("Are you sure you want to delete this case frame: " + cf.getId() + "?"); a.showAndWait().ifPresent(response -> { - if (response == yes) { - try { + if (response == yes) { + try { Network.undefineCaseFrame(cf.getId()); } catch (CaseFrameCannotBeRemovedException e) { Alert alert = new Alert(AlertType.ERROR); alert.setTitle("Delete Case Frame"); alert.setHeaderText("Error Deleting Case Frame"); alert.setResizable(false); - alert.setContentText("Case frame can not be removed, remove the nodes implementing this case frame first"); + alert.setContentText( + "Case frame can not be removed, remove the nodes implementing this case frame first"); alert.showAndWait(); } updateCaseFramesList(); - } else if (response == cancel) { - - } + } else if (response == cancel) { + + } }); - + } - - //Creates a base node + + // Creates a base node public void buildBaseNode() { String nodeName = baseNodeID.getText(); String semType = baseNodeSemType.getText(); @@ -2541,13 +2495,13 @@ public void buildBaseNode() { // TODO Auto-generated catch block e.printStackTrace(); } - if(node == null) { + if (node == null) { Alert alert = new Alert(AlertType.ERROR); alert.setTitle("ERROR"); alert.setHeaderText("Node was NOT created successfully!"); alert.setContentText("ERROR: Acts cannot be base nodes!!!"); alert.showAndWait(); - }else { + } else { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Node created!"); alert.setHeaderText("Node was created successfully!"); @@ -2557,10 +2511,10 @@ public void buildBaseNode() { baseNodeID.setText(""); baseNodeSemType.setText(""); } - + } - - //Updates the nodes list + + // Updates the nodes list public void updateNodesList() { Hashtable nodes = Network.getNodes(); ArrayList sorted = new ArrayList(); @@ -2571,12 +2525,12 @@ public void updateNodesList() { pathNodes1.getItems().clear(); pathNodes2.getItems().clear(); for (Entry entry : nodes.entrySet()) { - String key = entry.getKey(); - sorted.add(key); + String key = entry.getKey(); + sorted.add(key); } - + Collections.sort(sorted); - for(int i = 0; i() { @@ -2584,45 +2538,45 @@ public void updateNodesList() { @Override public void handle(ActionEvent arg0) { pathNodes1.setText(mi.getText()); - + } - + }); pathNodes1.getItems().add(mi); - + MenuItem mi1 = new MenuItem(key); mi1.setOnAction(new EventHandler() { @Override public void handle(ActionEvent arg0) { pathNodes2.setText(mi1.getText()); - + } - + }); pathNodes2.getItems().add(mi1); Node n = nodes.get(key); - nodesList.getItems().add(key); - if(n.getTerm() instanceof Variable) { - variableNodesList.getItems().add(key); - }else if(n.getTerm() instanceof Base) { + nodesList.getItems().add(key); + if (n.getTerm() instanceof Variable) { + variableNodesList.getItems().add(key); + } else if (n.getTerm() instanceof Base) { baseNodesList.getItems().add(key); - String semantic = n.getSemantic().getSemanticType(); - if(semantic.equalsIgnoreCase("proposition")) { + String semantic = n.getSemantic().getSemanticType(); + if (semantic.equalsIgnoreCase("proposition")) { propoNodesList.getItems().add(key); } - }else if(n.getTerm() instanceof Molecular) { - String semantic = n.getSemantic().getSemanticType(); - if(semantic.equalsIgnoreCase("proposition")) { + } else if (n.getTerm() instanceof Molecular) { + String semantic = n.getSemantic().getSemanticType(); + if (semantic.equalsIgnoreCase("proposition")) { propoNodesList.getItems().add(key); } - } + } } } - - //Creates a wire + + // Creates a wire public void createWire() { - + String rName = caseFrameRelationList.getSelectionModel().getSelectedItem(); Relation r = null; try { @@ -2630,7 +2584,7 @@ public void createWire() { } catch (RelationDoesntExistException e) { e.printStackTrace(); } - + String nodeName = nodesList.getSelectionModel().getSelectedItem(); Node node = null; try { @@ -2638,7 +2592,7 @@ public void createWire() { } catch (NodeNotFoundInNetworkException e1) { e1.printStackTrace(); } - + Wire w = new Wire(r, node); wiresList.getItems().add(r.getName() + " " + nodeName); wires.add(w); @@ -2649,10 +2603,10 @@ public void createWire() { a.setResizable(false); a.setContentText("Wire name is: " + r.getName() + " " + nodeName); a.showAndWait(); - + } - - //Delete a wire() + + // Delete a wire() public void deleteWire() { String wireName = wiresList.getSelectionModel().getSelectedItem(); Wire w = wiresTable.get(wireName); @@ -2660,8 +2614,8 @@ public void deleteWire() { wiresList.getItems().remove(wireName); wiresTable.remove(wireName, w); } - - //Builds a variable node in the network + + // Builds a variable node in the network public void buildVN() { VariableNode n = Network.buildVariableNode(); String name = n.getIdentifier(); @@ -2673,8 +2627,8 @@ public void buildVN() { a.showAndWait(); updateNodesList(); } - - //Builds the molecular node in the network + + // Builds the molecular node in the network public void buildMolecularNode() { try { Node n = Network.buildMolecularNode(wires, curRRCF); @@ -2697,8 +2651,8 @@ public void buildMolecularNode() { a.showAndWait(); } } - - //Displays the details of a selected node + + // Displays the details of a selected node public void nodeDetails(String identifier) { Node n = null; try { @@ -2706,20 +2660,21 @@ public void nodeDetails(String identifier) { } catch (NodeNotFoundInNetworkException e) { e.printStackTrace(); } - if(n.getTerm() instanceof Variable) { + if (n.getTerm() instanceof Variable) { String syntactic = n.getSyntacticType(); int id = n.getId(); - nodeDetails.setText("Node Identifier: " + identifier + "\n" + "Syntactic Type: " + syntactic + "\n" + "ID: " + id); - }else { + nodeDetails.setText( + "Node Identifier: " + identifier + "\n" + "Syntactic Type: " + syntactic + "\n" + "ID: " + id); + } else { String semantic = n.getSemantic().getSemanticType(); String syntactic = n.getSyntacticType(); int id = n.getId(); - nodeDetails.setText("Node Identifier: " + identifier + "\n" + "Semantic Type: " - + semantic + "\n" + "Syntactic Type: " + syntactic + "\n" + "ID: " + id); + nodeDetails.setText("Node Identifier: " + identifier + "\n" + "Semantic Type: " + semantic + "\n" + + "Syntactic Type: " + syntactic + "\n" + "ID: " + id); } } - - //Displays the details of a selected relation + + // Displays the details of a selected relation public void relationDetails(String rname) { Relation r = null; try { @@ -2731,37 +2686,36 @@ public void relationDetails(String rname) { String adjust = r.getAdjust(); int limit = r.getLimit(); boolean quantifier = r.isQuantifier(); - relationDetails.setText("Relation Name: " + rname + "\n" + "Type: " + type - + "\n" + "Adjust: " + adjust + "\n" + "Limit: " + limit + "\t" + "Quantifier: " - + quantifier); + relationDetails.setText("Relation Name: " + rname + "\n" + "Type: " + type + "\n" + "Adjust: " + adjust + "\n" + + "Limit: " + limit + "\t" + "Quantifier: " + quantifier); } - //Adds an overridden a relation to rr case frame + // Adds an overridden a relation to rr case frame public void addOverriddenRelationToCaseFrame() { String selectedRelation = relationSetList1.getSelectionModel().getSelectedItem(); - if(selectedRelation != null) { + if (selectedRelation != null) { String adjust = overrideAdjust.getText(); String limitS = overrideLimit.getText(); - - if(limitS.length() == 0) { + + if (limitS.length() == 0) { Relation r = null; try { r = Network.getRelation(selectedRelation); - + } catch (RelationDoesntExistException e) { e.printStackTrace(); } - + String ra = r.getAdjust(); int rl = r.getLimit(); - RCFP rcfp = new RCFP(r,ra,rl); + RCFP rcfp = new RCFP(r, ra, rl); rrcflist.add(rcfp); cfRS.getItems().add(selectedRelation); relationSetList1.getItems().remove(selectedRelation); overrideAdjust.setText(""); overrideLimit.setText(""); - - }else { + + } else { int limit = Integer.parseInt(overrideLimit.getText()); Relation r = null; try { @@ -2769,7 +2723,7 @@ public void addOverriddenRelationToCaseFrame() { } catch (RelationDoesntExistException e) { e.printStackTrace(); } - RCFP rcfp = new RCFP(r,adjust,limit); + RCFP rcfp = new RCFP(r, adjust, limit); rrcflist.add(rcfp); cfRS.getItems().add(selectedRelation); relationSetList1.getItems().remove(selectedRelation); @@ -2778,24 +2732,24 @@ public void addOverriddenRelationToCaseFrame() { } } } - - //Removes an overridden relation from rr case frame + + // Removes an overridden relation from rr case frame public void removeOverridenRelation() { String selectedRelation = rrcfrslist.getSelectionModel().getSelectedItem(); - if(selectedRelation != null) { - for(RCFP rcfp: rrcflist) { - Relation r = rcfp.getRelation(); - if(r.getName() == selectedRelation) { - rrcflist.remove(rcfp); - relationSetList1.getItems().add(selectedRelation); - cfRS.getItems().remove(selectedRelation); - } - } + if (selectedRelation != null) { + for (RCFP rcfp : rrcflist) { + Relation r = rcfp.getRelation(); + if (r.getName() == selectedRelation) { + rrcflist.remove(rcfp); + relationSetList1.getItems().add(selectedRelation); + cfRS.getItems().remove(selectedRelation); + } + } } } - - //Creates rrcf + + // Creates rrcf public void submitRRCF() { String semType = rrcfSem.getText(); CaseFrame cf = Network.defineCaseFrameWithConstraints(semType, rrcflist); @@ -2812,7 +2766,7 @@ public void submitRRCF() { cfRS.getItems().clear(); rrcfSem.setText(""); } - + public void deleteNode() { String identifier = nodesList.getSelectionModel().getSelectedItem().toString(); ButtonType yes = new ButtonType("Yes"); @@ -2823,16 +2777,16 @@ public void deleteNode() { a.setResizable(false); a.setContentText("Are you sure you want to delete this node: " + identifier + "?"); a.showAndWait().ifPresent(response -> { - if (response == yes) { - Node n = null; - try { + if (response == yes) { + Node n = null; + try { n = Network.getNode(identifier); } catch (NodeNotFoundInNetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } - try { + try { Network.removeNode(n); updateNodesList(); } catch (NodeCannotBeRemovedException e) { @@ -2846,12 +2800,12 @@ public void deleteNode() { e.printStackTrace(); } } else if (response == cancel) { - - } + + } }); - + } - + public void createCableTypeConst() { String semantic = cableSem.getText(); Integer min = Integer.parseInt(cableMinNodes.getText()); @@ -2868,12 +2822,12 @@ public void createCableTypeConst() { cableMinNodes.clear(); cableMaxNodes.clear(); } - + public void deleteCTC() { String ctcID = cablesList.getSelectionModel().getSelectedItem(); - for(int i = 0; i cf.getSignatureIDs().size()) { + } else if (priority > cf.getSignatureIDs().size()) { priority = cf.getSignatureIDs().size(); } - + network.addSignatureToCaseFrame(rule, priority, cf); - popUpNotification("Case Frame Signature", "Case frame signature has been added successfully", "Case frame signature has been added successfully", 2); + popUpNotification("Case Frame Signature", "Case frame signature has been added successfully", + "Case frame signature has been added successfully", 2); } - + public void addNodeToPropSet() { String identifier = propoNodesList.getSelectionModel().getSelectedItem(); propSet.getItems().add(identifier); propoNodesList.getItems().remove(identifier); } - + public void removeNodeFromPropSet() { String identifier = propSet.getSelectionModel().getSelectedItem(); propoNodesList.getItems().add(identifier); propSet.getItems().remove(identifier); } - + public void createContext() { String name = contextName.getText(); int size = propSet.getItems().size(); int[] prop = new int[size]; - for(int i = 0; i sortedPaths = new ArrayList(); for (Entry entry : paths.entrySet()) { - String pname = entry.getKey(); - sortedPaths.add(pname); + String pname = entry.getKey(); + sortedPaths.add(pname); } Collections.sort(sortedPaths); - + pathsList.getItems().clear(); - for(int i = 0; i tempPaths = new LinkedList(); ObservableList selectedIndices = pathsList.getSelectionModel().getSelectedItems(); String name = ""; - for(Object o : selectedIndices){ - tempPaths.add(paths.get(o)); - name += o + " "; - } + for (Object o : selectedIndices) { + tempPaths.add(paths.get(o)); + name += o + " "; + } AndPath p = new AndPath(tempPaths); String pname = "And Path " + name; paths.put(pname, p); updatePathsList(); popUpNotification("And Path", "And Path Created Successfully", "Path: " + pname, 1); } - + public void createOrPath() { LinkedList tempPaths = new LinkedList(); ObservableList selectedIndices = pathsList.getSelectionModel().getSelectedItems(); String name = ""; - for(Object o : selectedIndices){ - tempPaths.add(paths.get(o)); - name += o + " "; - } + for (Object o : selectedIndices) { + tempPaths.add(paths.get(o)); + name += o + " "; + } OrPath p = new OrPath(tempPaths); String pname = "Or Path " + name; paths.put(pname, p); updatePathsList(); popUpNotification("Or Path", "Or Path Created Successfully", "Path: " + pname, 1); } - + public void createComposePath() { LinkedList tempPaths = new LinkedList(); ObservableList selectedIndices = composeList.getItems(); String name = ""; - for(String o : selectedIndices){ - tempPaths.add(paths.get(o)); - name += o + " "; - } + for (String o : selectedIndices) { + tempPaths.add(paths.get(o)); + name += o + " "; + } ComposePath p = new ComposePath(tempPaths); String pname = "Compose Path " + name; paths.put(pname, p); @@ -3262,39 +3220,39 @@ public void createComposePath() { clearComposeList(); popUpNotification("Compose Path", "Compose Path Created Successfully", "Path: " + pname, 1); } - + public void addPQPath() { - if(ppath.getText().equalsIgnoreCase("...")) { + if (ppath.getText().equalsIgnoreCase("...")) { String pname = pathsList.getSelectionModel().getSelectedItem(); ppath.setText(pname); - }else if(qpath.getText().equalsIgnoreCase("...")) { + } else if (qpath.getText().equalsIgnoreCase("...")) { String pname = pathsList.getSelectionModel().getSelectedItem(); qpath.setText(pname); } } - + public void clearPQ1Path() { ppath1.setText("..."); qpath1.setText("..."); pathNodes2.setText("Select a node"); } - + public void addPQ1Path() { - if(ppath1.getText().equalsIgnoreCase("...")) { + if (ppath1.getText().equalsIgnoreCase("...")) { String pname = pathsList.getSelectionModel().getSelectedItem(); ppath1.setText(pname); - }else if(qpath1.getText().equalsIgnoreCase("...")) { + } else if (qpath1.getText().equalsIgnoreCase("...")) { String pname = pathsList.getSelectionModel().getSelectedItem(); qpath1.setText(pname); } } - + public void clearPQPath() { ppath.setText("..."); qpath.setText("..."); pathNodes1.setText("Select a node"); } - + public void createDomainRestrictPath() { String identifier = pathNodes1.getText(); Node n = null; @@ -3308,7 +3266,7 @@ public void createDomainRestrictPath() { String qPathName = qpath.getText(); sneps.network.paths.Path pPath = paths.get(pPathName); sneps.network.paths.Path qPath = paths.get(qPathName); - + String name = "{ " + qPathName + " } { " + n.getIdentifier() + " } { " + pPathName + " }"; DomainRestrictPath p = new DomainRestrictPath(qPath, n, pPath); String pname = "Domain Restrict Path " + name; @@ -3317,7 +3275,7 @@ public void createDomainRestrictPath() { popUpNotification("Domain Restrict Path", "Domain Restrict Path Created Successfully", "Path: " + pname, 1); clearPQPath(); } - + public void createRangeRestrictPath() { String identifier = pathNodes2.getText(); Node n = null; @@ -3331,9 +3289,9 @@ public void createRangeRestrictPath() { String qPathName = qpath1.getText(); sneps.network.paths.Path pPath = paths.get(pPathName); sneps.network.paths.Path qPath = paths.get(qPathName); - + String name = "{ " + qPathName + " } { " + n.getIdentifier() + " } { " + pPathName + " }"; - + RangeRestrictPath p = new RangeRestrictPath(pPath, qPath, n); String pname = "Range Restrict Path " + name; paths.put(pname, p); @@ -3341,7 +3299,7 @@ public void createRangeRestrictPath() { popUpNotification("Range Restrict Path", "Range Restrict Path Created Successfully", "Path: " + pname, 1); clearPQ1Path(); } - + public void createBangPath() { BangPath bp = new BangPath(); String pname = "Bang Path " + bpcounter++; @@ -3349,7 +3307,7 @@ public void createBangPath() { updatePathsList(); popUpNotification("Bang Path", "Bang Path Created Successfully", "Path: " + pname, 1); } - + public void definePath() { Relation r = null; try { @@ -3361,13 +3319,14 @@ public void definePath() { String pname = pathsList.getSelectionModel().getSelectedItem(); sneps.network.paths.Path p = (sneps.network.paths.Path) paths.get(pname); Network.definePath(r, p); - popUpNotification("Define Path", "Path Defined Successfully", "Path: " + pname + " Relation: " + r.getName(), 1); + popUpNotification("Define Path", "Path Defined Successfully", "Path: " + pname + " Relation: " + r.getName(), + 1); } - + public void updateListOfContexts() { Set contexts = Controller.getAllNamesOfContexts(); ArrayList sorted = new ArrayList(); - for(String s : contexts) { + for (String s : contexts) { sorted.add(s); } Collections.sort(sorted); @@ -3397,7 +3356,7 @@ public void handle(ActionEvent arg0) { // TODO Auto-generated catch block e.printStackTrace(); } - for(int i : a) { + for (int i : a) { Node n = null; try { n = Network.getNodeById(i); @@ -3408,23 +3367,23 @@ public void handle(ActionEvent arg0) { propsOfCxt.put(n.getIdentifier(), n); } Hashtable nodes = Network.getNodes(); - for(Entry entry : nodes.entrySet()) { + for (Entry entry : nodes.entrySet()) { Node x = propsOfCxt.get(entry.getKey()); - if(x == null) { - if(!(entry.getValue().getTerm() instanceof Variable)) { - if(entry.getValue().getSemantic().getSemanticType().equalsIgnoreCase("proposition")) { + if (x == null) { + if (!(entry.getValue().getTerm() instanceof Variable)) { + if (entry.getValue().getSemantic().getSemanticType().equalsIgnoreCase("proposition")) { sorted.add(entry.getKey()); } } } } - + Collections.sort(sorted); - for(String x : sorted) { + for (String x : sorted) { propoNodesList1.getItems().add(x); } } - + }); mi1.setOnAction(new EventHandler() { @@ -3445,7 +3404,7 @@ public void handle(ActionEvent arg0) { // TODO Auto-generated catch block e.printStackTrace(); } - for(int i : a) { + for (int i : a) { Node n = null; try { n = Network.getNodeById(i); @@ -3456,25 +3415,25 @@ public void handle(ActionEvent arg0) { sorted.add(n.getIdentifier()); } Collections.sort(sorted); - for(String x : sorted) { + for (String x : sorted) { propNodesListOfSelCont.getItems().add(x); } } - + }); contextList.getItems().add(s); chooseContext.getItems().add(mi); chooseContext1.getItems().add(mi1); } } - + public void deleteContext() { String cname = contextList.getSelectionModel().getSelectedItem(); Controller.removeContext(cname); popUpNotification("Context", "Context Deleted", "Context: " + cname + " Deleted Successfully", 1); updateListOfContexts(); } - + public void setCurrentContext() { String cname = contextList.getSelectionModel().getSelectedItem(); try { @@ -3488,24 +3447,24 @@ public void setCurrentContext() { e.printStackTrace(); } } - + public void addNodeToPropSet1() { String identifier = propoNodesList1.getSelectionModel().getSelectedItem(); propSet1.getItems().add(identifier); propoNodesList1.getItems().remove(identifier); } - + public void removeNodeFromPropSet1() { String identifier = propSet1.getSelectionModel().getSelectedItem(); propoNodesList1.getItems().add(identifier); propSet1.getItems().remove(identifier); } - + public void addPropsToContext() { String name = chooseContext.getText(); int size = propSet1.getItems().size(); int[] prop = new int[size]; - for(int i = 0; i() { @Override public void handle(KeyEvent arg0) { - if(arg0.getCode() != KeyCode.CAPS) { + if (arg0.getCode() != KeyCode.CAPS) { Hashtable nodes = Network.getNodes(); ArrayList sorted = new ArrayList(); ArrayList keys = new ArrayList(); @@ -3594,22 +3554,22 @@ public void handle(KeyEvent arg0) { keys.add(key); } String nodename = searchNodes.getText(); - for(int i = 0; i= nodename.length()) { - if(nodeKey.substring(0, nodename.length()).equalsIgnoreCase(nodename)){ + if (nodeKey.length() >= nodename.length()) { + if (nodeKey.substring(0, nodename.length()).equalsIgnoreCase(nodename)) { sorted.add(nodeKey); } } } - + Collections.sort(sorted); - for(String x : sorted) { + for (String x : sorted) { nodesList.getItems().add(x); } } } - + }); } @@ -3617,11 +3577,11 @@ public void addToComposePath() { String pname = pathsList.getSelectionModel().getSelectedItem(); composeList.getItems().add(pname); } - + public void clearComposeList() { composeList.getItems().clear(); } - + public void removePropFromContext() { String propname = propNodesListOfSelCont.getSelectionModel().getSelectedItem(); Node n = null; @@ -3631,7 +3591,7 @@ public void removePropFromContext() { // TODO Auto-generated catch block e.printStackTrace(); } - int[] i = {n.getId()}; + int[] i = { n.getId() }; PropositionSet props = null; try { props = new PropositionSet(i); @@ -3644,7 +3604,8 @@ public void removePropFromContext() { } try { Controller.removeHypsFromContext(props, chooseContext1.getText()); - popUpNotification("Remove Proposition From Context", "Proposition Removed Successfully", "Proposition: " + propname + " has been removed from context: " + chooseContext1.getText(), 2); + popUpNotification("Remove Proposition From Context", "Proposition Removed Successfully", + "Proposition: " + propname + " has been removed from context: " + chooseContext1.getText(), 2); } catch (NotAPropositionNodeException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -3665,12 +3626,12 @@ public void deduce() { try { n = (PropositionNode) Network.getNode(identifier); } catch (NodeNotFoundInNetworkException e) { - System.out.println(e); - n = Network.buildTemporaryNode(identifier); + System.out.println(e.getMessage()); +// n = Network.buildTemporaryNode(identifier, ); } n.deduce(); ReportSet rs = n.getKnownInstances(); - for(Report r : rs) { + for (Report r : rs) { res = res + r.toString() + "\n"; } Alert a = new Alert(AlertType.INFORMATION); @@ -3680,22 +3641,11 @@ public void deduce() { a.setContentText(res); a.showAndWait(); } - + //..........END Of Menu Methods........................................ - - - - - - //..........Saving & Loading Methods.................................... - - - - - public void save() { String name = netChoice1.getText(); String relations = name + "relations"; @@ -3712,7 +3662,7 @@ public void save() { String udvs = name + "udvs"; String semList = name + "semList"; String contexts = name + "contexts"; - + ButtonType yes = new ButtonType("Yes"); ButtonType cancel = new ButtonType("Cancel"); Alert a = new Alert(AlertType.NONE, "Promote pawn to:", yes, cancel); @@ -3721,8 +3671,8 @@ public void save() { a.setResizable(false); a.setContentText("If you didn't load the network file that you want to save to, data WILL BE LOST!"); a.showAndWait().ifPresent(response -> { - if (response == yes) { - try { + if (response == yes) { + try { Network.save(relations, caseFrames, nodes, molnodes, mc, pc, vc, pn, ni, udms, udps, udvs); SemanticHierarchy.save(semList); Controller.save(contexts); @@ -3730,12 +3680,12 @@ public void save() { } catch (IOException e) { e.printStackTrace(); } - } else if (response == cancel) { - - } + } else if (response == cancel) { + + } }); } - + public void save(String name) { String relations = name + "relations"; String caseFrames = name + "caseFrames"; @@ -3751,8 +3701,8 @@ public void save(String name) { String udvs = name + "udvs"; String semList = name + "semList"; String contexts = name + "contexts"; - - try { + + try { Network.save(relations, caseFrames, nodes, molnodes, mc, pc, vc, pn, ni, udms, udps, udvs); SemanticHierarchy.save(semList); Controller.save(contexts); @@ -3761,6 +3711,7 @@ public void save(String name) { e.printStackTrace(); } } + public void load() { String name = netChoice2.getText(); String relations = name + "relations"; @@ -3777,10 +3728,10 @@ public void load() { String udvs = name + "udvs"; String semList = name + "semList"; String contexts = name + "contexts"; - + try { Network.clearNetwork(); - Network.load(relations , caseFrames, nodes, molnodes, mc, pc, vc, pn, ni, udms, udps, udvs); + Network.load(relations, caseFrames, nodes, molnodes, mc, pc, vc, pn, ni, udms, udps, udvs); SemanticHierarchy.load(semList); Controller.load(contexts); updateNodesList(); @@ -3801,10 +3752,11 @@ public void load() { e.printStackTrace(); } } + public void submitNewNet() throws IOException { String name = newNetName.getText(); boolean r = Network.addToSavedNetworks(name); - if(r == true) { + if (r == true) { System.out.println("Network Created Successfully!"); Network.saveNetworks(); createDefaults(); @@ -3822,7 +3774,7 @@ public void submitNewNet() throws IOException { a.setResizable(false); a.setContentText("Network: " + name + " has been created successfully!"); a.showAndWait(); - }else { + } else { System.out.println("Network Already Exists, Please Type Another Name."); Alert a = new Alert(AlertType.ERROR); a.setTitle("New Network"); @@ -3850,7 +3802,7 @@ public void deleteNetwork() { String udvs = name + "udvs"; String semList = name + "semList"; String contexts = name + "contexts"; - + ButtonType yes = new ButtonType("Yes"); ButtonType cancel = new ButtonType("Cancel"); Alert a = new Alert(AlertType.NONE, "", yes, cancel); @@ -3859,21 +3811,21 @@ public void deleteNetwork() { a.setResizable(false); a.setContentText("You CANNOT undo this action, Network data will be LOST!"); a.showAndWait().ifPresent(response -> { - if (response == yes) { - Path filePath1 = Paths.get(relations); - Path filePath2 = Paths.get(caseFrames); - Path filePath3 = Paths.get(nodes); - Path filePath4 = Paths.get(molnodes); - Path filePath5 = Paths.get(mc); - Path filePath6 = Paths.get(pc); - Path filePath7 = Paths.get(ni); - Path filePath8 = Paths.get(udms); - Path filePath9 = Paths.get(udps); - Path filePath10 = Paths.get(udvs); - Path filePath11 = Paths.get(vc); - Path filePath12 = Paths.get(pn); - Path filePath13 = Paths.get(semList); - Path filePath14 = Paths.get(contexts); + if (response == yes) { + Path filePath1 = Paths.get(relations); + Path filePath2 = Paths.get(caseFrames); + Path filePath3 = Paths.get(nodes); + Path filePath4 = Paths.get(molnodes); + Path filePath5 = Paths.get(mc); + Path filePath6 = Paths.get(pc); + Path filePath7 = Paths.get(ni); + Path filePath8 = Paths.get(udms); + Path filePath9 = Paths.get(udps); + Path filePath10 = Paths.get(udvs); + Path filePath11 = Paths.get(vc); + Path filePath12 = Paths.get(pn); + Path filePath13 = Paths.get(semList); + Path filePath14 = Paths.get(contexts); try { Network.deleteFromSavedNetworks(name); updateNetLists(); @@ -3891,20 +3843,22 @@ public void deleteNetwork() { Files.delete(filePath12); Files.delete(filePath13); Files.delete(filePath14); - popUpNotification("Delete network", "Network Deleted!", "The Network: " + name + " is deleted successfully", 2); - } catch(IOException e) { + popUpNotification("Delete network", "Network Deleted!", + "The Network: " + name + " is deleted successfully", 2); + } catch (IOException e) { e.printStackTrace(); } - } else if (response == cancel) { - - } + } else if (response == cancel) { + + } }); } + public void updateNetList1() { netChoice1.getItems().clear(); ArrayList temp = Network.getSavedNetworks(); - for(int i = 0; i() { @@ -3912,16 +3866,16 @@ public void updateNetList1() { public void handle(ActionEvent event) { netChoice1.setText(mi.getText()); } - + }); netChoice1.getItems().add(mi); } } - + public void updateNetList2() { netChoice2.getItems().clear(); ArrayList temp = Network.getSavedNetworks(); - for(int i = 0; i() { @@ -3929,15 +3883,16 @@ public void updateNetList2() { public void handle(ActionEvent event) { netChoice2.setText(mi.getText()); } - + }); netChoice2.getItems().add(mi); } } + public void updateNetList3() { netChoice3.getItems().clear(); ArrayList temp = Network.getSavedNetworks(); - for(int i = 0; i() { @@ -3945,100 +3900,89 @@ public void updateNetList3() { public void handle(ActionEvent event) { netChoice3.setText(mi.getText()); } - + }); netChoice3.getItems().add(mi); } } - + public void updateNetLists() { updateNetList1(); updateNetList2(); updateNetList3(); } - //..........End of saving and loading methods........................... - - - - - + //..........Displaying the network method............................... - - - public void generateNetwork() throws IOException { String data = null; - if(Main.isDark()) { + if (Main.isDark()) { data = "document.body.innerHTML += Viz('digraph { nodesep=0.5; ranksep=2.5; bgcolor=gray20;"; - }else { + } else { data = "document.body.innerHTML += Viz('digraph { nodesep=0.5; ranksep=2.5; bgcolor=none;"; } File f = new File("bin/sneps/gui/displayData.html"); - BufferedWriter bw = new BufferedWriter(new FileWriter(f)); - bw.write(""); - bw.write(""); - bw.write(""); - bw.write("Test"); - if(Main.isDark()) { - bw.write(""); - }else { - bw.write(""); - } - bw.write(""); - bw.write(""); - bw.write(""); - bw.write(""); + bw.write(""); + bw.write(""); + bw.write(""); bw.close(); - //System.out.println("Generating Network.."); + // System.out.println("Generating Network.."); } - public void displayNetwork() { try { generateNetwork(); @@ -4049,14 +3993,13 @@ public void displayNetwork() { String url = this.getClass().getResource("displayData.html").toExternalForm(); webView.getEngine().load(url); } - public void createDefaults() { Network.defineDefaults(); updateRelationSetList(); updateCaseFramesList(); } - + public void testVisualize() { ArrayList nodes = new ArrayList(); Node n1 = null; @@ -4079,7 +4022,7 @@ public void testVisualize() { nodes.add(n3); nodes.add(n4); nodes.add(n5); - + try { Main.visualizeNodes(nodes); } catch (IOException e) { diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java index 8a75d3b9..b4d1b4a3 100644 --- a/src/sneps/network/Node.java +++ b/src/sneps/network/Node.java @@ -159,12 +159,12 @@ public boolean equals(Object obj) { public void receiveRequest(Channel newChannel) { // TODO Auto-generated method stub - install channel - + Runner.addToLowQueue(this); } public void receiveReport(Channel newChannel) { // TODO Auto-generated method stub - + Runner.addToHighQueue(this); } public void processReports() { @@ -215,12 +215,6 @@ public NodeSet getDominatingRules() { public boolean isWhQuestion(Substitutions filterSubs) { VariableNodeStats currentNodeStats = computeNodeStats(filterSubs); return !currentNodeStats.areAllVariablesBound(); - /* - * if (!(this instanceof VariableNode)) return false; VariableNode node = - * (VariableNode) this; VariableSet variables = node.getFreeVariables(); int - * variablesCardn = variables.size(); int filterCardn = - * filterSubs.cardinality(); return filterCardn < variablesCardn; - */ } /*** diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 4dcdc0ac..15501f64 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -62,68 +62,67 @@ public PropositionNode(Term trm) { } /*** - * Adding a report to all outgoing channels + * Trying to send a report to all outgoing channels * * @param report */ public void broadcastReport(Report report) { - for (Channel outChannel : outgoingChannels) { - try { - if (outChannel.testReportToSend(report)) { - // System.out.println("SENDING REPORT " + this); - } - } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + for (Channel outChannel : outgoingChannels) + sendReport(report, outChannel); } + /*** + * Used to send a report over a channel through calling Channel.testReportToSend + * + * @param report + * @param channel + * @return + */ public boolean sendReport(Report report, Channel channel) { try { if (channel.testReportToSend(report)) { - // System.out.println("SENDING REPORT " + this); - return true; + System.out.println("Report instance (" + report + ") was successfuly sent over (" + channel + ")"); } } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { - // TODO Auto-generated catch block + System.out.println("Report instance (" + report + ") could not be sent."); e.printStackTrace(); } return false; } - private void sendReports(NodeSet isAntecedentTo, ReportSet reports, ChannelTypes channelType, + protected void sendReports(NodeSet isAntecedentTo, ReportSet reports, ChannelTypes channelType, Channel currentChannel) { - for (Node node : isAntecedentTo) { - for (Report report : reports) { - Substitutions reportSubs = report.getSubstitutions(); - Collection reportSuppSet = report.getSupports(); - boolean reportSign = report.getSign(); - String currentChannelContextName = currentChannel.getContextName(); - Channel newChannel = establishChannel(channelType, node, null, reportSubs, currentChannelContextName, - InferenceTypes.FORWARD, -1); - outgoingChannels.addChannel(newChannel); - node.receiveReport(newChannel); + if (isAntecedentTo != null) + for (Node node : isAntecedentTo) { + for (Report report : reports) { + Substitutions reportSubs = report.getSubstitutions(); + Support reportSupp = report.getSupport(); + boolean reportSign = report.getSign(); + String currentChannelContextName = currentChannel.getContextName(); + Channel newChannel = establishChannel(channelType, node, null, reportSubs, + currentChannelContextName, -1); + outgoingChannels.addChannel(newChannel); + node.receiveReport(newChannel); + } } - } - } - private void sendReports(List list, ReportSet reports, Channel currentChannel) { - for (Match match : list) { - for (Report report : reports) { - Substitutions reportSubs = report.getSubstitutions(); - Collection reportSuppSet = report.getSupports(); - Node sentTo = match.getNode(); - boolean reportSign = report.getSign(); - String currentChannelContextName = currentChannel.getContextName(); - int matchType = match.getMatchType(); - Channel newChannel = establishChannel(ChannelTypes.MATCHED, sentTo, null, reportSubs, - currentChannelContextName, InferenceTypes.FORWARD, matchType); - outgoingChannels.addChannel(newChannel); - sentTo.receiveReport(newChannel); + protected void sendReports(List list, ReportSet reports, Channel currentChannel) { + if (list != null) + for (Match match : list) { + for (Report report : reports) { + Substitutions reportSubs = report.getSubstitutions(); +// Collection reportSuppSet = report.getSupports(); + Node sentTo = match.getNode(); +// boolean reportSign = report.getSign(); + String currentChannelContextName = currentChannel.getContextName(); + int matchType = match.getMatchType(); + Channel newChannel = establishChannel(ChannelTypes.MATCHED, sentTo, null, reportSubs, + currentChannelContextName, matchType); + outgoingChannels.addChannel(newChannel); + sentTo.receiveReport(newChannel); + } } - } } /*** @@ -140,8 +139,8 @@ private void sendReports(List list, ReportSet reports, Channel currentCha * node scenario * @return the established type based channel */ - private Channel establishChannel(ChannelTypes type, Object currentElement, Substitutions switchSubs, - Substitutions filterSubs, String contextName, InferenceTypes inferenceType, int matchType) { + protected Channel establishChannel(ChannelTypes type, Object currentElement, Substitutions switchSubs, + Substitutions filterSubs, String contextName, int matchType) { boolean matchTypeEstablishing = currentElement instanceof Match; Node evaluatedReporter = matchTypeEstablishing ? ((Match) currentElement).getNode() : (Node) currentElement; Substitutions switchLinearSubs = switchSubs == null ? new LinearSubstitutions() : switchSubs; @@ -149,14 +148,14 @@ private Channel establishChannel(ChannelTypes type, Object currentElement, Subst switch (type) { case MATCHED: newChannel = new MatchChannel(switchLinearSubs, filterSubs, contextName, this, evaluatedReporter, true, - inferenceType, matchType); + matchType); break; case RuleAnt: newChannel = new AntecedentToRuleChannel(switchLinearSubs, filterSubs, contextName, this, evaluatedReporter, - true, inferenceType); + true); default: newChannel = new RuleToConsequentChannel(switchLinearSubs, filterSubs, contextName, this, evaluatedReporter, - true, inferenceType); + true); } return newChannel; @@ -171,13 +170,13 @@ private Channel establishChannel(ChannelTypes type, Object currentElement, Subst * @param contextId * @param inferenceType */ - protected void sendRequestsToMatches(List list, String contextId, InferenceTypes inferenceType) { + protected void sendRequestsToMatches(List list, String contextId) { for (Match currentMatch : list) { Substitutions switchSubs = currentMatch.getSwitchSubs(); Substitutions filterSubs = currentMatch.getFilterSubs(); int matchType = currentMatch.getMatchType(); Channel newChannel = establishChannel(ChannelTypes.MATCHED, currentMatch, switchSubs, filterSubs, contextId, - inferenceType, matchType); + matchType); incomingChannels.addChannel(newChannel); currentMatch.getNode().receiveRequest(newChannel); } @@ -194,9 +193,9 @@ protected void sendRequestsToMatches(List list, String contextId, Inferen * @param inferenceType */ protected void sendRequestsToNodeSet(NodeSet ns, Substitutions filterSubs, String contextID, - ChannelTypes channelType, InferenceTypes inferenceType) { + ChannelTypes channelType) { for (Node sentTo : ns) { - Channel newChannel = establishChannel(channelType, sentTo, null, filterSubs, contextID, inferenceType, -1); + Channel newChannel = establishChannel(channelType, sentTo, null, filterSubs, contextID, -1); incomingChannels.addChannel(newChannel); sentTo.receiveRequest(newChannel); } @@ -223,20 +222,13 @@ public void processRequests() { */ protected void processSingleRequestsChannel(Channel currentChannel) throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { - // TODO check correctness - int instanceNodeId = getId(); - PropositionSet propSet = new PropositionSet(); - propSet.add(instanceNodeId); - Collection nodeAssumptionBasedSupport = getAssumptionBasedSupport().values(); + Support nodeSupport = getBasicSupport(); String currentContextName = currentChannel.getContextName(); Context desiredContext = Controller.getContextByName(currentContextName); if (assertedInContext(desiredContext)) { // TODO change the subs to hashsubs - Collection support = new ArrayList(); - support.add(propSet); - Report reply = new Report(new LinearSubstitutions(), nodeAssumptionBasedSupport, true); - knownInstances.addReport(reply); - broadcastReport(reply); + Report reply = new Report(new LinearSubstitutions(), nodeSupport, true, InferenceTypes.BACKWARD); + sendReport(reply, currentChannel); } else { boolean sentAtLeastOne = false; for (Report currentReport : knownInstances) @@ -246,17 +238,12 @@ protected void processSingleRequestsChannel(Channel currentChannel) NodeSet dominatingRules = getDominatingRules(); NodeSet toBeSentToDom = removeAlreadyWorkingOn(dominatingRules, currentChannel, false); sendRequestsToNodeSet(toBeSentToDom, new LinearSubstitutions(), currentContextName, - ChannelTypes.RuleAnt, currentChannel.getInferenceType()); + ChannelTypes.RuleAnt); if (!(currentChannel instanceof MatchChannel)) { List matchingNodes = Matcher.match(this); List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel, false); - sendRequestsToMatches(toBeSentToMatch, currentContextName, currentChannel.getInferenceType()); + sendRequestsToMatches(toBeSentToMatch, currentContextName); } - /* - * if (!(currentChannel instanceof MatchChannel)) // was in !alreadyWorking if - * condition getNodesToSendRequests(ChannelTypes.MATCHED, - * currentChannel.getContextName(), null, currentChannel.getInferenceType()); - */ } } } @@ -275,28 +262,28 @@ protected void processSingleReportsChannel(Channel currentChannel) { ReportSet reports = currentChannel.getReportsBuffer(); for (Report currentReport : reports) { Substitutions reportSubs = currentReport.getSubstitutions(); - Collection reportSupportSet = currentReport.getSupports(); + Support reportSupport = currentReport.getSupport(); boolean reportSign = currentReport.isPositive(); - String currentChannelContextName = currentChannel.getContextName(); boolean toBeSentFlag = true; if (currentChannel instanceof MatchChannel) { int channelMatchType = ((MatchChannel) currentChannel).getMatchType(); toBeSentFlag = (channelMatchType == 0) || (channelMatchType == 1 && currentReport.isPositive()) || (channelMatchType == 2 && currentReport.isNegative()); } - Report alteredReport = new Report(reportSubs, reportSupportSet, reportSign); - if (knownInstances.contains(alteredReport)) - continue; - if (toBeSentFlag) - broadcastReport(alteredReport); - } - /* Handling forward inference broadcasting */ - if (currentChannel.getInferenceType() == InferenceTypes.FORWARD) { - List matchesReturned = Matcher.match(this); - if (matchesReturned != null) + Report alteredBReport = new Report(reportSubs, reportSupport, reportSign, InferenceTypes.BACKWARD); + Report alteredFReport = new Report(reportSubs, reportSupport, reportSign, InferenceTypes.FORWARD); + boolean backwardReportFound = knownInstances.contains(alteredBReport); + boolean forwardReportFound = knownInstances.contains(alteredFReport); + if ((!backwardReportFound || !forwardReportFound) && toBeSentFlag) { + broadcastReport(!forwardReportFound ? alteredFReport : alteredBReport); + } + /* Handling forward inference broadcasting */ + if (currentReport.getInferenceType() == InferenceTypes.FORWARD) { + List matchesReturned = Matcher.match(this); sendReports(matchesReturned, reports, currentChannel); - NodeSet isAntecedentTo = getDominatingRules(); - sendReports(isAntecedentTo, reports, ChannelTypes.RuleAnt, currentChannel); + NodeSet isAntecedentTo = getDominatingRules(); + sendReports(isAntecedentTo, reports, ChannelTypes.RuleAnt, currentChannel); + } } currentChannel.clearReportsBuffer(); } @@ -339,6 +326,7 @@ public void receiveRequest(Channel channel) { public void receiveReports(Channel channel) { outgoingChannels.addChannel(channel); Runner.addToHighQueue(this); + channel.setReportProcessed(true); } public void deduce() { @@ -346,7 +334,8 @@ public void deduce() { String currentContextName = Controller.getCurrentContextName(); getNodesToSendRequests(ChannelTypes.RuleCons, currentContextName, null, InferenceTypes.BACKWARD); getNodesToSendRequests(ChannelTypes.MATCHED, currentContextName, null, InferenceTypes.BACKWARD); - Runner.run(); // what to return here ? + // what to return here ? + System.out.println(Runner.run()); } public void add() { @@ -369,13 +358,13 @@ protected void getNodesToSendRequests(ChannelTypes channelType, String currentCo case MATCHED: List matchesReturned = Matcher.match(this); if (matchesReturned != null) - sendRequestsToMatches(matchesReturned, currentContextName, inferenceType); + sendRequestsToMatches(matchesReturned, currentContextName); break; case RuleCons: NodeSet dominatingRules = getDominatingRules(); // TODO Youssef: check if passing a new LinearSubstitutions is correct Substitutions linearSubs = substitutions == null ? new LinearSubstitutions() : substitutions; - sendRequestsToNodeSet(dominatingRules, linearSubs, currentContextName, channelType, inferenceType); + sendRequestsToNodeSet(dominatingRules, linearSubs, currentContextName, channelType); break; default: break; diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index c78b11aa..160eaddd 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -11,6 +11,7 @@ import sneps.exceptions.NodeNotFoundInNetworkException; import sneps.exceptions.NotAPropositionNodeException; import sneps.network.classes.Semantic; +import sneps.network.classes.setClasses.ChannelSet; import sneps.network.classes.setClasses.ContextRuisSet; import sneps.network.classes.setClasses.FlagNodeSet; import sneps.network.classes.setClasses.NodeSet; @@ -25,6 +26,7 @@ import sneps.snebr.Context; import sneps.snebr.Controller; import sneps.snebr.Support; +import sneps.snip.InferenceTypes; import sneps.snip.Report; import sneps.snip.channels.AntecedentToRuleChannel; import sneps.snip.channels.Channel; @@ -32,6 +34,7 @@ import sneps.snip.channels.MatchChannel; import sneps.snip.channels.RuleToConsequentChannel; import sneps.snip.classes.FlagNode; +import sneps.snip.classes.RuleResponse; import sneps.snip.classes.RuleUseInfo; import sneps.snip.classes.SIndex; import sneps.snip.classes.VariableNodeStats; @@ -107,18 +110,18 @@ protected void processNodes(NodeSet antNodes) { sharedVars = getSharedVarsInts(antNodesWithVars); } - public void applyRuleHandler(Report report, Channel currentChannel) { + public RuleResponse applyRuleHandler(Report report, Channel currentChannel) { Node currentChannelReporter = currentChannel.getReporter(); String contextID = currentChannel.getContextName(); // Context context = SNeBR.getContextByID(contextID); RuleUseInfo rui; if (report.isPositive()) { - FlagNode fn = new FlagNode(currentChannelReporter, report.getSupports(), 1); + FlagNode fn = new FlagNode(currentChannelReporter, report.getSupport(), 1); FlagNodeSet fns = new FlagNodeSet(); fns.putIn(fn); rui = new RuleUseInfo(report.getSubstitutions(), 1, 0, fns); } else { - FlagNode fn = new FlagNode(currentChannelReporter, report.getSupports(), 2); + FlagNode fn = new FlagNode(currentChannelReporter, report.getSupport(), 2); FlagNodeSet fns = new FlagNodeSet(); fns.putIn(fn); rui = new RuleUseInfo(report.getSubstitutions(), 0, 1, fns); @@ -135,6 +138,7 @@ public void applyRuleHandler(Report report, Channel currentChannel) { for (RuleUseInfo tRui : res) { sendRui(tRui, contextID); } + return null; } abstract protected void sendRui(RuleUseInfo tRui, String contextID); @@ -269,7 +273,7 @@ protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel) { boolean ruleType = this instanceof ThreshNode || this instanceof AndOrNode; NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentNodeSet, currentChannel, ruleType); sendRequestsToNodeSet(toBeSentTo, currentChannel.getFilter().getSubstitutions(), - currentChannel.getContextName(), ChannelTypes.RuleAnt, currentChannel.getInferenceType()); + currentChannel.getContextName(), ChannelTypes.RuleAnt); } protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel, Report report) { @@ -277,7 +281,7 @@ protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel, Rep boolean ruleType = this instanceof ThreshNode || this instanceof AndOrNode; NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentNodeSet, currentChannel, ruleType); sendRequestsToNodeSet(toBeSentTo, report.getSubstitutions(), currentChannel.getContextName(), - ChannelTypes.RuleAnt, currentChannel.getInferenceType()); + ChannelTypes.RuleAnt); } @@ -292,6 +296,22 @@ protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel, Rep * false; } */ + protected void sendReportToNodeSet(NodeSet nodeSet, Report report, ChannelTypes channelType, + Channel currentChannel) { + if (nodeSet != null) + for (Node node : nodeSet) { + Substitutions reportSubs = report.getSubstitutions(); + Support reportSupp = report.getSupport(); + boolean reportSign = report.getSign(); + String currentChannelContextName = currentChannel.getContextName(); + Channel newChannel = establishChannel(channelType, node, null, reportSubs, currentChannelContextName, + -1); + outgoingChannels.addChannel(newChannel); + node.receiveReport(newChannel); + + } + } + public void processRequests() { for (Channel outChannel : outgoingChannels) try { @@ -368,12 +388,42 @@ public void processReports() { protected void processSingleReportsChannel(Channel currentChannel) { ReportSet channelReports = currentChannel.getReportsBuffer(); + String currentChannelContextName = currentChannel.getContextName(); + Substitutions currentChannelFilterSubs = currentChannel.getFilter().getSubstitutions(); + Substitutions currentChannelSwitchSubs = currentChannel.getSwitch().getSubstitutions(); for (Report currentReport : channelReports) { + Substitutions currentReportSubs = currentReport.getSubstitutions(); if (currentChannel instanceof AntecedentToRuleChannel) { - applyRuleHandler(currentReport, currentChannel); + RuleResponse ruleResponse = applyRuleHandler(currentReport, currentChannel); + if (ruleResponse != null) { + Report toBeSent = ruleResponse.getReport(); + broadcastReport(toBeSent); + if (toBeSent.getInferenceType() == InferenceTypes.FORWARD) { + NodeSet consequents = ruleResponse.getConsequents(); + NodeSet filteredNodeSet = removeExistingNodesOutgoingChannels(consequents); + sendReportToNodeSet(filteredNodeSet, toBeSent, ChannelTypes.RuleCons, currentChannel); + } + } else if (currentReport.getInferenceType() == InferenceTypes.FORWARD) { + NodeSet antecedents = getDownAntNodeSet(); + antecedents.removeNode(this); + sendRequestsToNodeSet(antecedents, currentChannelFilterSubs, currentChannelContextName, + ChannelTypes.RuleAnt); + } + } } currentChannel.clearReportsBuffer(); } + private NodeSet removeExistingNodesOutgoingChannels(NodeSet nodeSet) { + ChannelSet outgoingChannels = getOutgoingChannels(); + Set channels = outgoingChannels.getChannels(); + for (Node node : nodeSet) + for (Channel channel : channels) { + Node channelRequester = channel.getRequester(); + if (node.equals(channelRequester)) + nodeSet.removeNode(node); + } + return nodeSet; + } } diff --git a/src/sneps/network/classes/setClasses/ChannelSet.java b/src/sneps/network/classes/setClasses/ChannelSet.java index a381b188..419e47ef 100644 --- a/src/sneps/network/classes/setClasses/ChannelSet.java +++ b/src/sneps/network/classes/setClasses/ChannelSet.java @@ -1,42 +1,44 @@ -package sneps.network.classes.setClasses; - -import java.util.Iterator; - -import sneps.snip.channels.Channel; - -import java.io.Serializable; -import java.util.HashSet; - -public class ChannelSet implements Iterable, Serializable { - private HashSet channels; - - public ChannelSet() { - channels = new HashSet(); - } - - @Override - public Iterator iterator() { - return channels.iterator(); - } - - public void addChannel(Channel newChannel) { - channels.add(newChannel); - } - - /*** - * 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(); - for (Channel channel : channels) { - if (channel.isRequestProcessed() == processedRequest) - processedRequestsChannels.addChannel(channel); - } - return processedRequestsChannels; - } - -} +package sneps.network.classes.setClasses; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import sneps.snip.channels.Channel; + +public class ChannelSet implements Iterable { + private Set channels; + + public ChannelSet() { + channels = new HashSet(); + } + + public void addChannel(Channel channel) { + channels.add(channel); + } + + @Override + public Iterator iterator() { + return channels.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(); + for (Channel channel : channels) { + if (channel.isRequestProcessed() == processedRequest) + processedRequestsChannels.addChannel(channel); + } + return processedRequestsChannels; + } + + public Set getChannels() { + return channels; + } +} diff --git a/src/sneps/snip/Report.java b/src/sneps/snip/Report.java index 56ebdd4b..71af0363 100644 --- a/src/sneps/snip/Report.java +++ b/src/sneps/snip/Report.java @@ -13,18 +13,20 @@ public class Report { private Substitutions substitution; - private Collection supports; + private Support support; private boolean sign; + private InferenceTypes inferenceType; - public Report(Substitutions substitution, Collection set, boolean sign) { + public Report(Substitutions substitution, Support suppt, boolean sign, InferenceTypes inference) { this.substitution = substitution; - this.supports = set; + this.support = suppt; this.sign = sign; + this.inferenceType = inference; } public boolean anySupportAssertedInContext(Context reportContext) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - Collection reportSupportsSet = getSupports(); + Collection reportSupportsSet = support.getAssumptionBasedSupport().values(); PropositionSet contextHypothesisSet = reportContext.getHypothesisSet(); for (PropositionSet assumptionHyps : reportSupportsSet) if (assumptionHyps.isSubSet(contextHypothesisSet)) @@ -36,8 +38,8 @@ public Substitutions getSubstitutions() { return substitution; } - public Collection getSupports() { - return supports; + public Support getSupport() { + return support; } @Override @@ -63,7 +65,15 @@ public void toggleSign() { } public String toString() { - return "Sign: " + sign + "\nSubstitution: " + substitution + "\nSupport: " + supports; + return "Sign: " + sign + "\nSubstitution: " + substitution + "\nSupport: " + support; + } + + public InferenceTypes getInferenceType() { + return inferenceType; + } + + public void setInferenceType(InferenceTypes inferenceType) { + this.inferenceType = inferenceType; } } diff --git a/src/sneps/snip/channels/AntecedentToRuleChannel.java b/src/sneps/snip/channels/AntecedentToRuleChannel.java index d32583b5..bf007c8c 100644 --- a/src/sneps/snip/channels/AntecedentToRuleChannel.java +++ b/src/sneps/snip/channels/AntecedentToRuleChannel.java @@ -7,7 +7,7 @@ public class AntecedentToRuleChannel extends Channel { public AntecedentToRuleChannel(Substitutions switchSubstitution, Substitutions filterSubstitutions, - String contextID, Node requester, Node reporter, boolean v, InferenceTypes inferenceType) { - super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v, inferenceType); + String contextID, Node requester, Node reporter, boolean v) { + super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v); } } diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index 112142b7..34456cec 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -26,7 +26,6 @@ public abstract class Channel { private ReportSet reportsBuffer; private boolean requestProcessed = false; private boolean reportProcessed = false; - private InferenceTypes inferenceType; public Channel() { filter = new Filter(); @@ -35,7 +34,7 @@ public Channel() { } public Channel(Substitutions switcherSubstitution, Substitutions filterSubstitutions, String contextID, - Node requester, Node reporter, boolean v, InferenceTypes inferenceType) { + Node requester, Node reporter, boolean v) { this.filter = new Filter(filterSubstitutions); this.switcher = new Switch(switcherSubstitution); this.contextName = contextID; @@ -44,7 +43,6 @@ public Channel(Substitutions switcherSubstitution, Substitutions filterSubstitut this.valve = v; this.reporter = reporter; reportsBuffer = new ReportSet(); - this.inferenceType = inferenceType; } public boolean testReportToSend(Report report) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { @@ -106,14 +104,6 @@ public void setReportProcessed(boolean reportProcessed) { this.reportProcessed = reportProcessed; } - public InferenceTypes getInferenceType() { - return inferenceType; - } - - public void setInferenceType(InferenceTypes inferenceType) { - this.inferenceType = inferenceType; - } - public void setValve(boolean valve) { this.valve = valve; } diff --git a/src/sneps/snip/channels/ChannelSet.java b/src/sneps/snip/channels/ChannelSet.java deleted file mode 100644 index 2789a194..00000000 --- a/src/sneps/snip/channels/ChannelSet.java +++ /dev/null @@ -1,22 +0,0 @@ -package sneps.snip.channels; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -public class ChannelSet implements Iterable { - private Set channels; - - public ChannelSet() { - channels = new HashSet(); - } - - public void addChannel(Channel channel) { - channels.add(channel); - } - - @Override - public Iterator iterator() { - return channels.iterator(); - } -} diff --git a/src/sneps/snip/channels/MatchChannel.java b/src/sneps/snip/channels/MatchChannel.java index ea8c6ba9..2e0706c9 100644 --- a/src/sneps/snip/channels/MatchChannel.java +++ b/src/sneps/snip/channels/MatchChannel.java @@ -12,8 +12,8 @@ public MatchChannel() { } public MatchChannel(Substitutions switchSubstitution, Substitutions filterSubstitutions, String contextID, - Node requester, Node reporter, boolean v, InferenceTypes inferenceType, int matchType) { - super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v, inferenceType); + Node requester, Node reporter, boolean v, int matchType) { + super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v); this.setMatchType(matchType); } diff --git a/src/sneps/snip/channels/RuleToConsequentChannel.java b/src/sneps/snip/channels/RuleToConsequentChannel.java index 46f242a9..252c091e 100644 --- a/src/sneps/snip/channels/RuleToConsequentChannel.java +++ b/src/sneps/snip/channels/RuleToConsequentChannel.java @@ -7,8 +7,8 @@ public class RuleToConsequentChannel extends Channel { public RuleToConsequentChannel(Substitutions switchSubstitution, Substitutions filterSubstitutions, - String contextID, Node requester, Node reporter, boolean v, InferenceTypes inferenceType) { - super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v, inferenceType); + String contextID, Node requester, Node reporter, boolean v) { + super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v); } } diff --git a/src/sneps/snip/classes/FlagNode.java b/src/sneps/snip/classes/FlagNode.java index 23bf76d7..f009788c 100644 --- a/src/sneps/snip/classes/FlagNode.java +++ b/src/sneps/snip/classes/FlagNode.java @@ -11,19 +11,19 @@ public class FlagNode { private Node node; - private Collection supports; + private Support supports; private int flag; /** * Create a new flag node * - * @param n node - * @param collection support - * @param f true or false + * @param n node + * @param support support + * @param f true or false */ - public FlagNode(Node n, Collection collection, int f) { + public FlagNode(Node n, Support support, int f) { node = n; - supports = collection; + supports = support; flag = f; } @@ -41,7 +41,7 @@ public Node getNode() { * * @return support */ - public Collection getSupports() { + public Support getSupports() { return supports; } diff --git a/src/sneps/snip/classes/RuleResponse.java b/src/sneps/snip/classes/RuleResponse.java new file mode 100644 index 00000000..532ed6d0 --- /dev/null +++ b/src/sneps/snip/classes/RuleResponse.java @@ -0,0 +1,35 @@ +package sneps.snip.classes; + +import sneps.network.classes.setClasses.NodeSet; +import sneps.snip.Report; + +public class RuleResponse { + + private Report report; + private NodeSet consequents; + + public RuleResponse() { + + } + + public RuleResponse(Report report, NodeSet consequents) { + this.report = report; + this.consequents = consequents; + } + + public Report getReport() { + return report; + } + + public void setReport(Report report) { + this.report = report; + } + + public NodeSet getConsequents() { + return consequents; + } + + public void setConsequents(NodeSet consequents) { + this.consequents = consequents; + } +} \ No newline at end of file diff --git a/src/sneps/snip/matching/LinearSubstitutions.java b/src/sneps/snip/matching/LinearSubstitutions.java index 51ce0038..f9816397 100644 --- a/src/sneps/snip/matching/LinearSubstitutions.java +++ b/src/sneps/snip/matching/LinearSubstitutions.java @@ -466,10 +466,9 @@ public VariableNodeStats extractBoundStatus(VariableSet freeVariables) { for (Binding binding : sub) { VariableNode bindingVariableNode = binding.getVariableNode(); boolean bindingFound = false; - for (Variable variable : freeVariables) { - Variable bindingVariable = (Variable) bindingVariableNode.getTerm(); + Variable bindingVariable = (Variable) bindingVariableNode.getTerm(); + for (Variable variable : freeVariables) bindingFound |= variable.equals(bindingVariable); - } if (bindingFound) extractedFilterRelevantToVariables.add(binding); forAllCondition &= bindingFound; diff --git a/src/sneps/snip/matching/Match.java b/src/sneps/snip/matching/Match.java index 77b7df4d..a57f4d7d 100644 --- a/src/sneps/snip/matching/Match.java +++ b/src/sneps/snip/matching/Match.java @@ -5,10 +5,12 @@ public class Match { private Substitutions filterSubs; // whquestion atleastone free not bound // no filter on match channel - // target (switch el heya variables to variables) <- source (filter el heya variables to constants) + // target (switch el heya variables to variables) <- source (filter el heya + // variables to constants) private Substitutions switchSubs; private Node node; private int matchType; + // add propset as support public Match(Substitutions filterSubs, Substitutions switchSubs, Node n, int type) { this.filterSubs = filterSubs; diff --git a/src/sneps/snip/rules/OrNode.java b/src/sneps/snip/rules/OrNode.java index 7e13575e..a095098c 100644 --- a/src/sneps/snip/rules/OrNode.java +++ b/src/sneps/snip/rules/OrNode.java @@ -6,6 +6,8 @@ import java.util.Hashtable; import java.util.Set; +import sneps.exceptions.NodeNotFoundInNetworkException; +import sneps.exceptions.NotAPropositionNodeException; import sneps.network.Node; import sneps.network.RuleNode; import sneps.network.classes.Semantic; @@ -32,11 +34,16 @@ public void applyRuleHandler(Report report, Node node) { if (report.isPositive()) { Support originSupports = this.getBasicSupport(); Collection originSupportsSet = originSupports.getAssumptionBasedSupport().values(); - Collection sup = new ArrayList(); - sup.add(originSupports); - Report reply = new Report(report.getSubstitutions(), sup, true); + Support sup = new Support(this); + // sup.add(originSupports); + Report reply = new Report(report.getSubstitutions(), sup, true, null); for (Channel outChannel : outgoingChannels) - outChannel.testReportToSend(reply); + try { + outChannel.testReportToSend(reply); + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } } diff --git a/tests/InferenceTest.java b/tests/InferenceTest.java new file mode 100644 index 00000000..927625ec --- /dev/null +++ b/tests/InferenceTest.java @@ -0,0 +1,12 @@ +import static org.junit.Assert.*; + +import org.junit.Test; + +public class InferenceTest { + + @Test + public void test() { + fail("Not yet implemented"); + } + +} diff --git a/tests/PropositionSetTest.java b/tests/PropositionSetTest.java index 553cf146..912ded43 100644 --- a/tests/PropositionSetTest.java +++ b/tests/PropositionSetTest.java @@ -14,128 +14,129 @@ public class PropositionSetTest { - private static final Semantic semantic = new Semantic("Proposition"); - - @BeforeClass - public static void setUp() throws NotAPropositionNodeException, NodeNotFoundInNetworkException, IllegalIdentifierException { - for (int i = 0; i < 8889; i++) - Network.buildBaseNode("n"+i, semantic); - } - - @AfterClass - public static void tearDown() { - Network.clearNetwork(); - Controller.clearSNeBR(); - } - - @Test - public void testAdd() throws NotAPropositionNodeException, CustomException, DuplicatePropositionException, NodeNotFoundInNetworkException { - int prop = 800; - int [] props = new int[]{324,423,523,4200,7332,8888}; - PropositionSet set = new PropositionSet(props); - int [] testProps = new int[props.length + 1]; - for (int i = 0, j = 0 ; i < props.length; i++, j++) { - if (j== 3) { - testProps[j++] = prop; - testProps[j] = props[i]; - } else { - testProps[j] = props[i]; - } - } - PropositionSet testSet = new PropositionSet(testProps); - assertTrue(testSet.equals(set.add(prop))); - } - - @Test - public void testRemoveDuplicates() { - int [] testArr = new int [] {1,2,3,3,3,4,5,6,7,7}; - assertArrayEquals(PropositionSet.removeDuplicates(testArr), new int[]{1,2,3,4,5,6,7}); - } - - @Test - public void testConstructorWithDuplicateThrowsException() { - int prop = 523; - int [] props = new int[]{324,423,523,4200,7332,8888}; - try { - PropositionSet set = new PropositionSet(props); - set.add(prop); - fail("should throw exception"); - } catch (DuplicatePropositionException e) { - - } catch (NotAPropositionNodeException e) { - e.printStackTrace(); - } catch (NodeNotFoundInNetworkException e) { - e.printStackTrace(); - } - } - - @Test - public void isSubSet() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - int [] props1 = new int[]{324,423,523,4200,7332,8888}; - int [] props2 = new int[]{324,4200,8888}; - PropositionSet superSet = new PropositionSet(props1); - PropositionSet subSet = new PropositionSet(props2); - assertTrue(subSet.isSubSet(superSet)); - assertFalse(superSet.isSubSet(subSet)); - - } - - @Test - public void union() throws NotAPropositionNodeException, CustomException, NodeNotFoundInNetworkException { - PropositionSet first = new PropositionSet(new int[] {1,2,3,4,5,6}); - PropositionSet second = new PropositionSet(new int[] {2,4,7,9,10}); - PropositionSet expected = new PropositionSet(new int[] {1,2,3,4,5,6,7,9,10}); - - assertArrayEquals(PropositionSet.getPropsSafely(expected), PropositionSet.getPropsSafely(first.union(second))); - } - - @Test - public void remove() throws NodeNotFoundInPropSetException, NotAPropositionNodeException, NodeNotFoundInNetworkException { - PropositionSet set = new PropositionSet(new int[] {1,2,3,4,5,6}); - PropositionSet actual = set.remove(3); - PropositionSet expected = new PropositionSet(new int[] {1,2,4,5,6}); - - assertArrayEquals(PropositionSet.getPropsSafely(expected), PropositionSet.getPropsSafely(actual)); - } - - @Test - public void removeThrowsNotFoundException() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - PropositionSet set = new PropositionSet(new int[] {1,2,3,4,5,6}); - try { - set.remove(9); - fail("Exception not thrown!"); - } catch (NodeNotFoundInPropSetException e) { - - } - } - - @Test - public void removePropsTest() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - PropositionSet set = new PropositionSet(new int[] {1,2,3,4,5,6}); - PropositionSet newSet = set.removeProps(new PropositionSet(new int[] {3,4,5})); - assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int [] {1,2,6}); - - newSet = set.removeProps(new PropositionSet(new int[] {3})); - assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int [] {1,2,4,5,6}); - - newSet = set.removeProps(new PropositionSet(new int[] {6})); - assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int [] {1,2,3,4,5}); - - newSet = set.removeProps(new PropositionSet(new int[] {0})); - assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int [] {1,2,3,4,5,6}); - - newSet = set.removeProps(new PropositionSet(new int[] {1})); - assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int [] {2,3,4,5,6}); - - newSet = set.removeProps(new PropositionSet(new int[] {7})); - assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int [] {1,2,3,4,5,6}); - - newSet = set.removeProps(new PropositionSet(new int[] {1,2,3,4,5,7,8,9,10,11})); - assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int [] {6}); - - newSet = set.removeProps(new PropositionSet(new int[] {1,2,3,4,5,6})); - assertEquals(PropositionSet.getPropsSafely(newSet).length, 0); - - - } + private static final Semantic semantic = new Semantic("Proposition"); + + @BeforeClass + public static void setUp() + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, IllegalIdentifierException { + for (int i = 0; i < 8889; i++) + Network.buildBaseNode("n" + i, semantic); + } + + @AfterClass + public static void tearDown() { + Network.clearNetwork(); + Controller.clearSNeBR(); + } + + @Test + public void testAdd() throws NotAPropositionNodeException, CustomException, DuplicatePropositionException, + NodeNotFoundInNetworkException { + int prop = 800; + int[] props = new int[] { 324, 423, 523, 4200, 7332, 8888 }; + PropositionSet set = new PropositionSet(props); + int[] testProps = new int[props.length + 1]; + for (int i = 0, j = 0; i < props.length; i++, j++) { + if (j == 3) { + testProps[j++] = prop; + testProps[j] = props[i]; + } else { + testProps[j] = props[i]; + } + } + PropositionSet testSet = new PropositionSet(testProps); + assertTrue(testSet.equals(set.add(prop))); + } + + @Test + public void testRemoveDuplicates() { + int[] testArr = new int[] { 1, 2, 3, 3, 3, 4, 5, 6, 7, 7 }; + assertArrayEquals(PropositionSet.removeDuplicates(testArr), new int[] { 1, 2, 3, 4, 5, 6, 7 }); + } + + @Test + public void testConstructorWithDuplicateThrowsException() { + int prop = 523; + int[] props = new int[] { 324, 423, 523, 4200, 7332, 8888 }; + try { + PropositionSet set = new PropositionSet(props); + set.add(prop); + fail("should throw exception"); + } catch (DuplicatePropositionException e) { + + } catch (NotAPropositionNodeException e) { + e.printStackTrace(); + } catch (NodeNotFoundInNetworkException e) { + e.printStackTrace(); + } + } + + @Test + public void isSubSet() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + int[] props1 = new int[] { 324, 423, 523, 4200, 7332, 8888 }; + int[] props2 = new int[] { 324, 4200, 8888 }; + PropositionSet superSet = new PropositionSet(props1); + PropositionSet subSet = new PropositionSet(props2); + assertTrue(subSet.isSubSet(superSet)); + assertFalse(superSet.isSubSet(subSet)); + } + + @Test + public void union() throws NotAPropositionNodeException, CustomException, NodeNotFoundInNetworkException { + PropositionSet first = new PropositionSet(new int[] { 1, 2, 3, 4, 5, 6 }); + PropositionSet second = new PropositionSet(new int[] { 2, 4, 7, 9, 10 }); + PropositionSet expected = new PropositionSet(new int[] { 1, 2, 3, 4, 5, 6, 7, 9, 10 }); + + assertArrayEquals(PropositionSet.getPropsSafely(expected), PropositionSet.getPropsSafely(first.union(second))); + } + + @Test + public void remove() + throws NodeNotFoundInPropSetException, NotAPropositionNodeException, NodeNotFoundInNetworkException { + PropositionSet set = new PropositionSet(new int[] { 1, 2, 3, 4, 5, 6 }); + PropositionSet actual = set.remove(3); + PropositionSet expected = new PropositionSet(new int[] { 1, 2, 4, 5, 6 }); + + assertArrayEquals(PropositionSet.getPropsSafely(expected), PropositionSet.getPropsSafely(actual)); + } + + @Test + public void removeThrowsNotFoundException() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + PropositionSet set = new PropositionSet(new int[] { 1, 2, 3, 4, 5, 6 }); + try { + set.remove(9); + fail("Exception not thrown!"); + } catch (NodeNotFoundInPropSetException e) { + + } + } + + @Test + public void removePropsTest() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + PropositionSet set = new PropositionSet(new int[] { 1, 2, 3, 4, 5, 6 }); + PropositionSet newSet = set.removeProps(new PropositionSet(new int[] { 3, 4, 5 })); + assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int[] { 1, 2, 6 }); + + newSet = set.removeProps(new PropositionSet(new int[] { 3 })); + assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int[] { 1, 2, 4, 5, 6 }); + + newSet = set.removeProps(new PropositionSet(new int[] { 6 })); + assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int[] { 1, 2, 3, 4, 5 }); + + newSet = set.removeProps(new PropositionSet(new int[] { 0 })); + assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int[] { 1, 2, 3, 4, 5, 6 }); + + newSet = set.removeProps(new PropositionSet(new int[] { 1 })); + assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int[] { 2, 3, 4, 5, 6 }); + + newSet = set.removeProps(new PropositionSet(new int[] { 7 })); + assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int[] { 1, 2, 3, 4, 5, 6 }); + + newSet = set.removeProps(new PropositionSet(new int[] { 1, 2, 3, 4, 5, 7, 8, 9, 10, 11 })); + assertArrayEquals(PropositionSet.getPropsSafely(newSet), new int[] { 6 }); + + newSet = set.removeProps(new PropositionSet(new int[] { 1, 2, 3, 4, 5, 6 })); + assertEquals(PropositionSet.getPropsSafely(newSet).length, 0); + + } } diff --git a/tests/SupportTest.java b/tests/SupportTest.java index 30d48a0b..b7fbd4dc 100644 --- a/tests/SupportTest.java +++ b/tests/SupportTest.java @@ -1,4 +1,5 @@ package tests; + //Asssert, set of set of set, Cycles{Assumption, Tree}, Removing hwa el by update the structure import static org.junit.Assert.*; @@ -23,13 +24,14 @@ import sneps.network.PropositionNode; import sneps.network.classes.Semantic; import sneps.network.classes.setClasses.PropositionSet; + @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SupportTest { - + Network net; Semantic sem; final static String semanticType = "Proposition"; - + PropositionNode n0; PropositionNode n1; PropositionNode n2; @@ -46,788 +48,752 @@ public class SupportTest { PropositionNode n13; PropositionNode n14; - - @Before - - public void setUp() throws NodeNotFoundInNetworkException, NotAPropositionNodeException, IllegalIdentifierException{ - //Defining Semantic Type as PropositionNode - sem = new Semantic(semanticType); - net = new Network(); - - //Building Network Nodes - //The Network Nodes Labels and Corresponding Ids - net.buildBaseNode("s", sem);// 0 - net.buildBaseNode("p", sem);// 1 - net.buildBaseNode("q", sem);// 2 - net.buildBaseNode("r", sem);// 3 - net.buildBaseNode("m", sem);// 4 - net.buildBaseNode("n", sem);// 5 - net.buildBaseNode("v", sem);// 6 - net.buildBaseNode("z", sem);// 7 - net.buildBaseNode("a", sem);// 8 - net.buildBaseNode("b", sem);// 9 - net.buildBaseNode("c", sem);// 10 - net.buildBaseNode("d", sem);// 11 - net.buildBaseNode("e", sem);// 12 - net.buildBaseNode("f", sem);// 13 - net.buildBaseNode("g", sem);// 14 - - - //Getting the Network PropositionNodes - n0 = (PropositionNode) net.getNode("s"); - n1 = (PropositionNode) net.getNode("p"); - n2 = (PropositionNode) net.getNode("q"); - n3 = (PropositionNode) net.getNode("r"); - n4 = (PropositionNode) net.getNode("m"); - n5 = (PropositionNode) net.getNode("n"); - n6 = (PropositionNode) net.getNode("v"); - n7 = (PropositionNode) net.getNode("z"); - n8 = (PropositionNode) net.getNode("a"); - n9 = (PropositionNode) net.getNode("b"); - n10 = (PropositionNode) net.getNode("c"); - n11 = (PropositionNode) net.getNode("d"); - n12 = (PropositionNode) net.getNode("e"); - n13 = (PropositionNode) net.getNode("f"); - n14 = (PropositionNode) net.getNode("g"); - - //Setting Specific Nodes to be Hyps. So that no support are needed for this node. - //If node is not set, it is considers as Derived node. - n2.setHyp(true); - n4.setHyp(true); - n5.setHyp(true); - n6.setHyp(true); - n7.setHyp(true); - n9.setHyp(true); - n10.setHyp(true); - n11.setHyp(true); - n12.setHyp(true); - n13.setHyp(true); - n14.setHyp(true); - - } - - - /* - * Checking The Assumptions of a Node when it is initially Created. - * The Hyp Node once created must contain itself as Assumption Support. - * Expected The Hashtable "assumptions" is equal to the set{{2}}. - */ - @Test - - public void AInitialAssumptionBasedSupports() throws NotAPropositionNodeException, NodeNotFoundInNetworkException{ - Hashtable assumptions = new Hashtable(); - assumptions.put("2", new PropositionSet(n2.getId())); - assertEquals(n2.getAssumptionBasedSupport(), assumptions); - - assumptions = new Hashtable(); - assumptions.put("11", new PropositionSet(n11.getId())); - assertEquals(n11.getAssumptionBasedSupport(), assumptions); - - } - - /* - *When the node is initially created. The Supports Tree must only contain this node id only. - *Expected "mySupportsTree" structure is equal to the{{<0>}} - */ - @Test - public void BInitialSupportsTree() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - //Checking the supports tree structure of node "0". - ArrayList>> mySupportsTree = new ArrayList>>(); - ArrayList> branch = new ArrayList>(); - ArrayList intialTree = new ArrayList(); - intialTree.add(0); - branch.add(intialTree); - mySupportsTree.add(branch); - assertEquals(n0.getMySupportsTree(), mySupportsTree); - - } - - /* - * Checking The Justification of a Node when we insert some amount of sets as it's JustificationSupports - * - * 0 - * / \ - * / \-> 13 | 14 - * 1 |2 | 3 - * /\ \ - * / \ \ - * 4|5 6|7 8|9 - * / - * / - * 10 | 11 | 12 - * - * - * Expected to Have the following set as the JustificationBased Support of Node 0 <<{1,2,3}, {13,14}>> - * Expected to Have the following set as the JustificationBased Support of Node 1 <<{4,5}, {6,7}>> - */ - @Test - public void CStructuredJustificationBasedSupports() throws NotAPropositionNodeException, NodeNotFoundInNetworkException, NodeNotFoundInPropSetException, DuplicatePropositionException, CannotInsertJustificationSupportException{ - //The Set of Justifications We will use - int[] pqr = new int[3]; - pqr[0] = 1; - pqr[1] = 2; - pqr[2] = 3; - - int[] mn = new int[2]; - mn[0] = 5; - mn[1] = 4; - - int[] vz = new int[2]; - vz[0] = 6; - vz[1] = 7; - - int[] ab = new int[2]; - ab[0] = 9; - ab[1] = 8; - - int[] cde = new int[3]; - cde[0] = 10; - cde[1] = 11; - cde[2] = 12; - - int[] fg = new int[2]; - fg[0] = 14; - fg[1] = 13; - - //Creating Proposition Sets by the previous Arrays of int - PropositionSet s1 = new PropositionSet(pqr); - PropositionSet s2 = new PropositionSet(mn); - PropositionSet s3 = new PropositionSet(vz); - PropositionSet s4 = new PropositionSet(ab); - PropositionSet s5 = new PropositionSet(cde); - PropositionSet s6 = new PropositionSet(fg); - - //Construct the tree "Bottum-Up" See the Graph above the method to imagine the Support Structure! - n1.addJustificationBasedSupport(s2); - n1.addJustificationBasedSupport(s3); - n8.addJustificationBasedSupport(s5); - n3.addJustificationBasedSupport(s4); - n0.addJustificationBasedSupport(s6); - n0.addJustificationBasedSupport(s1); - - //Retrieving the justification supports of node 0. - Hashtable justifications = new Hashtable(); - justifications.put("1,2,3,", new PropositionSet(pqr)); - justifications.put("13,14,", new PropositionSet(fg)); - assertEquals(n0.getJustificationSupport(), justifications); - - //Retrieving the justification supports of node 1. - justifications = new Hashtable(); - justifications.put("4,5,", new PropositionSet(mn)); - justifications.put("6,7,", new PropositionSet(vz)); - assertEquals(n1.getJustificationSupport(), justifications); - - } - - /* - * Checking The Assumptions of a Node when we insert some amount of sets as it's JustificationSupports - * - * 0 - * / \ - * / \-> 13 | 14 - * 1 |2 | 3 - * /\ \ - * / \ \ - * 4|5 6|7 8|9 - * / - * / - * 10 | 11 | 12 * - * - * - * Expected to Have the following set as the AssumptionBased Support <<{2,4,5,9,10,11,12} , {2,6,7,9,10,11,12} , {13,14}>> - */ - @Test - public void DStructuredAssumptionBasedSupports() throws NotAPropositionNodeException, NodeNotFoundInNetworkException{ - //Checking the assumption supports of node 0. - Hashtable assumptions = new Hashtable(); - int[] firstAssumption = new int[7]; - firstAssumption[0] = 2; - firstAssumption[1] = 4; - firstAssumption[2] = 5; - firstAssumption[3] = 10; - firstAssumption[4] = 9; - firstAssumption[5] = 11; - firstAssumption[6] = 12; - - int[] secondAssumption = new int[7]; - secondAssumption[0] = 2; - secondAssumption[1] = 6; - secondAssumption[2] = 7; - secondAssumption[3] = 10; - secondAssumption[4] = 9; - secondAssumption[5] = 11; - secondAssumption[6] = 12; - - int[] thirdAssumption = new int[2]; - thirdAssumption[0] = 13; - thirdAssumption[1] = 14; - - assumptions.put("2,4,5,9,10,11,12,", new PropositionSet(firstAssumption)); - assumptions.put("2,6,7,9,10,11,12,", new PropositionSet(secondAssumption)); - assumptions.put("13,14,", new PropositionSet(thirdAssumption)); - assertEquals(n0.getAssumptionBasedSupport(), assumptions); - - } - /* - * Checking The Supports Tree Hierarchy of a Node when we insert some amount of sets as it's JustificationSupports - * - * 0 - * / \ - * / \-> 13 | 14 - * 1 |2 | 3 - * /\ \ - * / \ \ - * 4|5 6|7 8|9 - * / - * / - * 10 | 11 | 12 * - * - * - * Expected to Have the following set as the Support Tree Structure "mySupportsTree" - * {{<2,0>,<4,1,0>,<5,1,0>,<9,3,0>,<10,8,3,0>,<11,8,3,0>,<12,8,3,0>},{<2,0>,<6,1,0>,<7,1,0>,<9,3,0>,<10,8,3,0>,<11,8,3,0>,<12,8,3,0>},{<13,0>,<14,0>}}. - */ - @Test - public void EStructuredSupportsTree() throws NotAPropositionNodeException, NodeNotFoundInNetworkException{ - ArrayList>> mySupportsTree = new ArrayList>>(); - - - //Constructing the List {<2,0>,<6,1,0>,<7,1,0>,<9,3,0>,<10,8,3,0>,<11,8,3,0>,<12,8,3,0>}. - ArrayList> branch = new ArrayList>(); - ArrayList intialTree = new ArrayList(); - intialTree.add(2);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(6);intialTree.add(1);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(7);intialTree.add(1);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(9);intialTree.add(3);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(10);intialTree.add(8);intialTree.add(3);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(11);intialTree.add(8);intialTree.add(3);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(12);intialTree.add(8);intialTree.add(3);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - mySupportsTree.add(branch); - branch = new ArrayList>(); - - //Constructing the List {<2,0>,<4,1,0>,<5,1,0>,<9,3,0>,<10,8,3,0>,<11,8,3,0>,<12,8,3,0>}. - branch = new ArrayList>(); - intialTree = new ArrayList(); - intialTree.add(2);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(4);intialTree.add(1);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(5);intialTree.add(1);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(9);intialTree.add(3);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(10);intialTree.add(8);intialTree.add(3);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(11);intialTree.add(8);intialTree.add(3);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(12);intialTree.add(8);intialTree.add(3);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - mySupportsTree.add(branch); - branch = new ArrayList>(); - - - //Constructing the List {<13,0>,<14,0>}. - branch = new ArrayList>(); - intialTree = new ArrayList(); - intialTree.add(13);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(14);intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - mySupportsTree.add(branch); - branch = new ArrayList>(); - - assertEquals(n0.getMySupportsTree(), mySupportsTree); - - } - - /* - * Consider We need To delete the node 1 from the Network (IntermidateNode) - * - * 0 - * / \ - * / \-> 13 | 14 - * 1 |2 | 3 - * /\ \ - * / \ \ - * 4|5 6|7 8|9 - * / - * / - * 10 | 11 | 12 - * - *Expected to remove the whole support 1| 2| 3 From the structure. So the Justification Support of the Node 0 will be <{13, 14}> Only - */ - @Test - public void FremoveIntermidateNodeJustification() throws NotAPropositionNodeException, NodeNotFoundInNetworkException{ - //Because the removal of any node only reflects on it's parent supports. - //Therefore the removal of n1 will only reflect on the supports structures of n0. - - //Getting parent supports of n1. - ArrayList parents = n1.getParentSupports(); - - //Loop over parent supports and delete n1 from them. - for (int i : parents) { - PropositionNode nx = (PropositionNode) Network.getNodeById(i); - //Deleting n1 from the supports of nx "n0 in this example" - nx.removeNodeFromSupports(n1); + @Before + + public void setUp() + throws NodeNotFoundInNetworkException, NotAPropositionNodeException, IllegalIdentifierException { + // Defining Semantic Type as PropositionNode + sem = new Semantic(semanticType); + net = new Network(); + + // Building Network Nodes + // The Network Nodes Labels and Corresponding Ids + net.buildBaseNode("s", sem);// 0 + net.buildBaseNode("p", sem);// 1 + net.buildBaseNode("q", sem);// 2 + net.buildBaseNode("r", sem);// 3 + net.buildBaseNode("m", sem);// 4 + net.buildBaseNode("n", sem);// 5 + net.buildBaseNode("v", sem);// 6 + net.buildBaseNode("z", sem);// 7 + net.buildBaseNode("a", sem);// 8 + net.buildBaseNode("b", sem);// 9 + net.buildBaseNode("c", sem);// 10 + net.buildBaseNode("d", sem);// 11 + net.buildBaseNode("e", sem);// 12 + net.buildBaseNode("f", sem);// 13 + net.buildBaseNode("g", sem);// 14 + + // Getting the Network PropositionNodes + n0 = (PropositionNode) net.getNode("s"); + n1 = (PropositionNode) net.getNode("p"); + n2 = (PropositionNode) net.getNode("q"); + n3 = (PropositionNode) net.getNode("r"); + n4 = (PropositionNode) net.getNode("m"); + n5 = (PropositionNode) net.getNode("n"); + n6 = (PropositionNode) net.getNode("v"); + n7 = (PropositionNode) net.getNode("z"); + n8 = (PropositionNode) net.getNode("a"); + n9 = (PropositionNode) net.getNode("b"); + n10 = (PropositionNode) net.getNode("c"); + n11 = (PropositionNode) net.getNode("d"); + n12 = (PropositionNode) net.getNode("e"); + n13 = (PropositionNode) net.getNode("f"); + n14 = (PropositionNode) net.getNode("g"); + + // Setting Specific Nodes to be Hyps. So that no support are needed for this + // node. + // If node is not set, it is considers as Derived node. + n2.setHyp(true); + n4.setHyp(true); + n5.setHyp(true); + n6.setHyp(true); + n7.setHyp(true); + n9.setHyp(true); + n10.setHyp(true); + n11.setHyp(true); + n12.setHyp(true); + n13.setHyp(true); + n14.setHyp(true); + + } + + /* + * Checking The Assumptions of a Node when it is initially Created. The Hyp Node + * once created must contain itself as Assumption Support. Expected The + * Hashtable "assumptions" is equal to the set{{2}}. + */ + @Test + + public void AInitialAssumptionBasedSupports() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + Hashtable assumptions = new Hashtable(); + assumptions.put("2", new PropositionSet(n2.getId())); + assertEquals(n2.getAssumptionBasedSupport(), assumptions); + + assumptions = new Hashtable(); + assumptions.put("11", new PropositionSet(n11.getId())); + assertEquals(n11.getAssumptionBasedSupport(), assumptions); + + } + + /* + * When the node is initially created. The Supports Tree must only contain this + * node id only. Expected "mySupportsTree" structure is equal to the{{<0>}} + */ + @Test + public void BInitialSupportsTree() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + // Checking the supports tree structure of node "0". + ArrayList>> mySupportsTree = new ArrayList>>(); + ArrayList> branch = new ArrayList>(); + ArrayList intialTree = new ArrayList(); + intialTree.add(0); + branch.add(intialTree); + mySupportsTree.add(branch); + assertEquals(n0.getMySupportsTree(), mySupportsTree); + + } + + /* + * Checking The Justification of a Node when we insert some amount of sets as + * it's JustificationSupports + * + * 0 / \ / \-> 13 | 14 1 |2 | 3 /\ \ / \ \ 4|5 6|7 8|9 / / 10 | 11 | 12 + * + * + * Expected to Have the following set as the JustificationBased Support of Node + * 0 <<{1,2,3}, {13,14}>> Expected to Have the following set as the + * JustificationBased Support of Node 1 <<{4,5}, {6,7}>> + */ + @Test + public void CStructuredJustificationBasedSupports() + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, NodeNotFoundInPropSetException, + DuplicatePropositionException, CannotInsertJustificationSupportException { + // The Set of Justifications We will use + int[] pqr = new int[3]; + pqr[0] = 1; + pqr[1] = 2; + pqr[2] = 3; + + int[] mn = new int[2]; + mn[0] = 5; + mn[1] = 4; + + int[] vz = new int[2]; + vz[0] = 6; + vz[1] = 7; + + int[] ab = new int[2]; + ab[0] = 9; + ab[1] = 8; + + int[] cde = new int[3]; + cde[0] = 10; + cde[1] = 11; + cde[2] = 12; + + int[] fg = new int[2]; + fg[0] = 14; + fg[1] = 13; + + // Creating Proposition Sets by the previous Arrays of int + PropositionSet s1 = new PropositionSet(pqr); + PropositionSet s2 = new PropositionSet(mn); + PropositionSet s3 = new PropositionSet(vz); + PropositionSet s4 = new PropositionSet(ab); + PropositionSet s5 = new PropositionSet(cde); + PropositionSet s6 = new PropositionSet(fg); + + // Construct the tree "Bottum-Up" See the Graph above the method to imagine the + // Support Structure! + n1.addJustificationBasedSupport(s2); + n1.addJustificationBasedSupport(s3); + n8.addJustificationBasedSupport(s5); + n3.addJustificationBasedSupport(s4); + n0.addJustificationBasedSupport(s6); + n0.addJustificationBasedSupport(s1); + + // Retrieving the justification supports of node 0. + Hashtable justifications = new Hashtable(); + justifications.put("1,2,3,", new PropositionSet(pqr)); + justifications.put("13,14,", new PropositionSet(fg)); + assertEquals(n0.getJustificationSupport(), justifications); + + // Retrieving the justification supports of node 1. + justifications = new Hashtable(); + justifications.put("4,5,", new PropositionSet(mn)); + justifications.put("6,7,", new PropositionSet(vz)); + assertEquals(n1.getJustificationSupport(), justifications); + + } + + /* + * Checking The Assumptions of a Node when we insert some amount of sets as it's + * JustificationSupports + * + * 0 / \ / \-> 13 | 14 1 |2 | 3 /\ \ / \ \ 4|5 6|7 8|9 / / 10 | 11 | 12 * + * + * + * Expected to Have the following set as the AssumptionBased Support + * <<{2,4,5,9,10,11,12} , {2,6,7,9,10,11,12} , {13,14}>> + */ + @Test + public void DStructuredAssumptionBasedSupports() + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + // Checking the assumption supports of node 0. + Hashtable assumptions = new Hashtable(); + int[] firstAssumption = new int[7]; + firstAssumption[0] = 2; + firstAssumption[1] = 4; + firstAssumption[2] = 5; + firstAssumption[3] = 10; + firstAssumption[4] = 9; + firstAssumption[5] = 11; + firstAssumption[6] = 12; + + int[] secondAssumption = new int[7]; + secondAssumption[0] = 2; + secondAssumption[1] = 6; + secondAssumption[2] = 7; + secondAssumption[3] = 10; + secondAssumption[4] = 9; + secondAssumption[5] = 11; + secondAssumption[6] = 12; + + int[] thirdAssumption = new int[2]; + thirdAssumption[0] = 13; + thirdAssumption[1] = 14; + + assumptions.put("2,4,5,9,10,11,12,", new PropositionSet(firstAssumption)); + assumptions.put("2,6,7,9,10,11,12,", new PropositionSet(secondAssumption)); + assumptions.put("13,14,", new PropositionSet(thirdAssumption)); + assertEquals(n0.getAssumptionBasedSupport(), assumptions); + + } + + /* + * Checking The Supports Tree Hierarchy of a Node when we insert some amount of + * sets as it's JustificationSupports + * + * 0 / \ / \-> 13 | 14 1 |2 | 3 /\ \ / \ \ 4|5 6|7 8|9 / / 10 | 11 | 12 * + * + * + * Expected to Have the following set as the Support Tree Structure + * "mySupportsTree" + * {{<2,0>,<4,1,0>,<5,1,0>,<9,3,0>,<10,8,3,0>,<11,8,3,0>,<12,8,3,0>},{<2,0>,<6,1 + * ,0>,<7,1,0>,<9,3,0>,<10,8,3,0>,<11,8,3,0>,<12,8,3,0>},{<13,0>,<14,0>}}. + */ + @Test + public void EStructuredSupportsTree() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + ArrayList>> mySupportsTree = new ArrayList>>(); + + // Constructing the List + // {<2,0>,<6,1,0>,<7,1,0>,<9,3,0>,<10,8,3,0>,<11,8,3,0>,<12,8,3,0>}. + ArrayList> branch = new ArrayList>(); + ArrayList intialTree = new ArrayList(); + intialTree.add(2); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(6); + intialTree.add(1); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(7); + intialTree.add(1); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(9); + intialTree.add(3); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(10); + intialTree.add(8); + intialTree.add(3); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(11); + intialTree.add(8); + intialTree.add(3); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(12); + intialTree.add(8); + intialTree.add(3); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + mySupportsTree.add(branch); + branch = new ArrayList>(); + + // Constructing the List + // {<2,0>,<4,1,0>,<5,1,0>,<9,3,0>,<10,8,3,0>,<11,8,3,0>,<12,8,3,0>}. + branch = new ArrayList>(); + intialTree = new ArrayList(); + intialTree.add(2); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(4); + intialTree.add(1); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(5); + intialTree.add(1); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(9); + intialTree.add(3); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(10); + intialTree.add(8); + intialTree.add(3); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(11); + intialTree.add(8); + intialTree.add(3); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(12); + intialTree.add(8); + intialTree.add(3); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + mySupportsTree.add(branch); + branch = new ArrayList>(); + + // Constructing the List {<13,0>,<14,0>}. + branch = new ArrayList>(); + intialTree = new ArrayList(); + intialTree.add(13); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(14); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + mySupportsTree.add(branch); + branch = new ArrayList>(); + + assertEquals(n0.getMySupportsTree(), mySupportsTree); + + } + + /* + * Consider We need To delete the node 1 from the Network (IntermidateNode) + * + * 0 / \ / \-> 13 | 14 1 |2 | 3 /\ \ / \ \ 4|5 6|7 8|9 / / 10 | 11 | 12 + * + * Expected to remove the whole support 1| 2| 3 From the structure. So the + * Justification Support of the Node 0 will be <{13, 14}> Only + */ + @Test + public void FremoveIntermidateNodeJustification() + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + // Because the removal of any node only reflects on it's parent supports. + // Therefore the removal of n1 will only reflect on the supports structures of + // n0. + + // Getting parent supports of n1. + ArrayList parents = n1.getParentSupports(); + + // Loop over parent supports and delete n1 from them. + for (int i : parents) { + PropositionNode nx = (PropositionNode) Network.getNodeById(i); + // Deleting n1 from the supports of nx "n0 in this example" + nx.removeNodeFromSupports(n1); } - - Hashtable justifications = new Hashtable(); - int[] res = new int[2]; - res[0] = 13; - res[1] = 14; - justifications.put("13,14,", new PropositionSet(res)); - - assertEquals(n0.getJustificationSupport(), justifications); - } - - /* - * Consider We need To delete the node 1 from the Network (IntermidateNode) - * - * 0 - * / \ - * / \-> 13 | 14 - * 1 |2 | 3 - * /\ \ - * / \ \ - * 4|5 6|7 8|9 - * / - * / - * 10 | 11 | 12 - * - *Expected to remove the whole support 1| 2| 3 From the structure. So the Supports Tree of the Node 0 will be {{<13,0>,<14,0>}} Only - */ - @Test - public void GremoveIntermidateNodeTree() throws NotAPropositionNodeException, NodeNotFoundInNetworkException{ - - //Node is already removed from the previous method. - ArrayList>> mySupportsTree = new ArrayList>>(); - ArrayList> branch = new ArrayList>(); - ArrayList intialTree = new ArrayList(); - intialTree.add(13); - intialTree.add(0); - branch.add(intialTree); - intialTree = new ArrayList(); - intialTree.add(14); - intialTree.add(0); - branch.add(intialTree); - mySupportsTree.add(branch); - assertEquals(n0.getMySupportsTree(), mySupportsTree); - } - /* - * Consider We need To delete the node 12 from the Network (LeafNode) - * - * 0 - * / \ - * / \-> 13 | 14 - * 1 |2 | 3 - * /\ \ - * / \ \ - * 4|5 6|7 8|9 - * / - * / - * 10 | 11 | 12 - * - *Expected to remove the whole support 10| 11| 12 From the structure. - *So the Justification Support of the Node 8 will be Empty. - *And because Node 8 is not a Hyp. Therefore Now it got no supports. the set <8,9> will be removed also. - *And because Node 3 is not a Hyp. Therefore Now it got no supports. the set <1,2,3> will be removed also. - *Therefore the Justification of Node 0 will be the set <13,14> only - */ - @Test - public void HremoveLeafNodeJustification12() throws NodeNotFoundInPropSetException, NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException, CannotInsertJustificationSupportException{ - //Because n1 was removed in the previous method. we need to return the set 1 | 2 | 3 to the hierarchy again.. - int[] pqr = new int[3]; - pqr[0] = 1; - pqr[1] = 2; - pqr[2] = 3; - - n0.addJustificationBasedSupport(new PropositionSet(pqr)); - - //Because the removal of any node only reflects on it's parent supports. - //Therefore the removal of n12 will only reflect on the supports structures of n0, n8, and n3. - - //Getting parent supports of n12. - ArrayList parents = n12.getParentSupports(); - - //Loop over parent supports and delete n12 from them. - for (int i : parents) { - PropositionNode nx = (PropositionNode) Network.getNodeById(i); - //Deleting n1 from the supports of nx "n8 then n3 then n0 in this example" - nx.removeNodeFromSupports(n12); + + Hashtable justifications = new Hashtable(); + int[] res = new int[2]; + res[0] = 13; + res[1] = 14; + justifications.put("13,14,", new PropositionSet(res)); + + assertEquals(n0.getJustificationSupport(), justifications); + } + + /* + * Consider We need To delete the node 1 from the Network (IntermidateNode) + * + * 0 / \ / \-> 13 | 14 1 |2 | 3 /\ \ / \ \ 4|5 6|7 8|9 / / 10 | 11 | 12 + * + * Expected to remove the whole support 1| 2| 3 From the structure. So the + * Supports Tree of the Node 0 will be {{<13,0>,<14,0>}} Only + */ + @Test + public void GremoveIntermidateNodeTree() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + + // Node is already removed from the previous method. + ArrayList>> mySupportsTree = new ArrayList>>(); + ArrayList> branch = new ArrayList>(); + ArrayList intialTree = new ArrayList(); + intialTree.add(13); + intialTree.add(0); + branch.add(intialTree); + intialTree = new ArrayList(); + intialTree.add(14); + intialTree.add(0); + branch.add(intialTree); + mySupportsTree.add(branch); + assertEquals(n0.getMySupportsTree(), mySupportsTree); + } + + /* + * Consider We need To delete the node 12 from the Network (LeafNode) + * + * 0 / \ / \-> 13 | 14 1 |2 | 3 /\ \ / \ \ 4|5 6|7 8|9 / / 10 | 11 | 12 + * + * Expected to remove the whole support 10| 11| 12 From the structure. So the + * Justification Support of the Node 8 will be Empty. And because Node 8 is not + * a Hyp. Therefore Now it got no supports. the set <8,9> will be removed also. + * And because Node 3 is not a Hyp. Therefore Now it got no supports. the set + * <1,2,3> will be removed also. Therefore the Justification of Node 0 will be + * the set <13,14> only + */ + @Test + public void HremoveLeafNodeJustification12() throws NodeNotFoundInPropSetException, NotAPropositionNodeException, + NodeNotFoundInNetworkException, DuplicatePropositionException, CannotInsertJustificationSupportException { + // Because n1 was removed in the previous method. we need to return the set 1 | + // 2 | 3 to the hierarchy again.. + int[] pqr = new int[3]; + pqr[0] = 1; + pqr[1] = 2; + pqr[2] = 3; + + n0.addJustificationBasedSupport(new PropositionSet(pqr)); + + // Because the removal of any node only reflects on it's parent supports. + // Therefore the removal of n12 will only reflect on the supports structures of + // n0, n8, and n3. + + // Getting parent supports of n12. + ArrayList parents = n12.getParentSupports(); + + // Loop over parent supports and delete n12 from them. + for (int i : parents) { + PropositionNode nx = (PropositionNode) Network.getNodeById(i); + // Deleting n1 from the supports of nx "n8 then n3 then n0 in this example" + nx.removeNodeFromSupports(n12); } - - Hashtable justifications = new Hashtable(); - int[] res = new int[2]; - res[0] = 13; - res[1] = 14; - justifications.put("13,14,", new PropositionSet(res)); - - assertEquals(n0.getJustificationSupport(), justifications); - - } - - /* - * Consider We need To delete the node 12 from the Network (LeafNode) - * - * 0 - * / \ - * / \-> 13 | 14 - * 1 |2 | 3 - * /\ \ - * / \ \ - * 4|5 6|7 8|9 - * / - * / - * 10 | 11 | 12 - * - *Expected to remove the whole support 10| 11| 12 From the structure. - *Expected to remove the whole support 8 | 9 From the structure. - *Expected to remove the whole support 1 | 2 | 3 From the structure. - * So the Assumption Support of the Node 0 will be 13 | 14 only - */ - @Test - public void IremoveLeafNodeAssumption12() throws NotAPropositionNodeException, NodeNotFoundInNetworkException{ - //We already removed node 12 in the previous method. - //Working on that to check n0 assumption supports. - - Hashtable assumptions = new Hashtable(); - int[] res = new int[2]; - res[0] = 13; - res[1] = 14; - assumptions.put("13,14,", new PropositionSet(res)); - - assertEquals(n0.getAssumptionBasedSupport(), assumptions); - - } - - /* - * Consider We need To delete the node 6 from the Network (LeafNode) - * - * 0 - * / \ - * / \-> 13 | 14 - * 1 |2 | 3 - * /\ \ - * / \ \ - * 4|5 6|7 8|9 - * / - * / - * 10 | 11 | 12 - * - *Expected to remove the whole support 6 | 7 From the structure. - *Not Expected to remove the whole support 1 | 2 | 3 From the structure. As Node 1 will still be supported by set 4|5 - * So the Justification Support of the Node 0 will be <<1 | 2 | 3>, <13 | 14>> - */ - @Test - public void JremoveLeafNodeJustificationSupport6() throws NodeNotFoundInPropSetException, NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException, CannotInsertJustificationSupportException{ - //Because we have removed node 12 from node 8. - //And we have removed node 8 from node 3. - //And we have removed node 3 from node 0. - //Therefore, we need to return the set <1 | 2 | 3> , <8 | 9> , and <10| 11 | 12> to the hierarchy again.. - - int[] pqr; - - pqr = new int[3]; - pqr[0] = 10; - pqr[1] = 11; - pqr[2] = 12; - - n8.addJustificationBasedSupport(new PropositionSet(pqr)); - - pqr = new int[2]; - pqr[0] = 8; - pqr[1] = 9; - - n3.addJustificationBasedSupport(new PropositionSet(pqr)); - - pqr = new int[3]; - pqr[0] = 1; - pqr[1] = 2; - pqr[2] = 3; - - n0.addJustificationBasedSupport(new PropositionSet(pqr)); - - //Because the removal of any node only reflects on it's parent supports. - //Therefore the removal of n6 will only reflect on the supports structures of n0, and n1. - - //Getting parent supports of n6. - ArrayList parents = n6.getParentSupports(); - - //Loop over parent supports and delete n12 from them. - for (int i : parents) { - PropositionNode nx = (PropositionNode) Network.getNodeById(i); - //Deleting n1 from the supports of nx "n8 then n3 then n0 in this example" - nx.removeNodeFromSupports(n6); - } - Hashtable justifications = new Hashtable(); - int[] res; - res = new int[3]; - res[0] = 1; - res[1] = 2; - res[2] = 3; - - justifications.put("1,2,3,", new PropositionSet(res)); - - res = new int[2]; - res[0] = 13; - res[1] = 14; - - justifications.put("13,14,", new PropositionSet(res)); - - assertEquals(n0.getJustificationSupport(), justifications); - - } - - /* - * Consider We need To delete the node 6 from the Network (LeafNode) - * - * 0 - * / \ - * / \-> 13 | 14 - * 1 |2 | 3 - * /\ \ - * / \ \ - * 4|5 6|7 8|9 - * / - * / - * 10 | 11 | 12 - * - *Expected to remove the whole support 6 | 7 From the structure. - *Not Expected to remove the whole support 1 | 2 | 3 From the structure. As Node 1 will still be supported by set 4|5 - * So the Assumption Support of the Node 0 will be <<2, 4, 5, 9, 10, 11, 12>, <13 | 14>> - */ - @Test - public void KremoveLeafNodeAssumption6() throws NotAPropositionNodeException, NodeNotFoundInNetworkException{ - //We already removed node 6 in the previous method. - //Working on that to check n0 assumption supports. - - Hashtable assumptions = new Hashtable(); - int[] res; - res = new int[7]; - res[0] = 2; - res[1] = 4; - res[2] = 5; - res[3] = 9; - res[4] = 10; - res[5] = 11; - res[6] = 12; - - assumptions.put("2,4,5,9,10,11,12,", new PropositionSet(res)); - - res = new int[2]; - res[0] = 13; - res[1] = 14; - - assumptions.put("13,14,", new PropositionSet(res)); - - assertEquals(n0.getAssumptionBasedSupport(), assumptions); - } - - - /* - * Consider the following 2 Tree Structures below - * - * Direct Cyclic Support: - * 0 - * / \ - * / \-> 13 | 14 - * 0 |1 |2 | 3 - * /\ \ - * / \ \ - * 4|5 6|7 8|9 - * / - * / - * 10 | 11 | 12 - * - *Expected to Have an Exception Says we have a cyclic supports, So that the justification support 0 | 1 | 2 | 3 cannot be support for proposition 0 - *So that the Justification support 0 | 1 | 2 | 3 cannot be added to the justification support of 0 - * - * InDirect Cyclic Support: - * 0 - * / \ - * / \-> 13 | 14 - * 1 |2 | 3 - * /\ \ - * / \ \ - * 0|4|5 6|7 8|9 - * / - * / - * 10 | 11 | 12 - * - * The path containning the cycle 0 |4 |5 will not be included in the supportTree, As it is an invalid path. - * Therefore we cannot also start by Node 1 as it is not a Hyp. So it will be deleted too. And the same goes for Node 3. - * So support Tree will be <<[13,0],[14,0]>> - * N0000: Expected to Have an Exception Says we have a cyclic supports, So that the justification support 0 | 10 | 11 | 12 cannot be support for proposition 0 - * So that the Justification support 1 | 2 | 3 cannot be added to the justification support of 0 - */ - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test - public void LAddDirectCyclicJustificationSupport() throws NotAPropositionNodeException, NodeNotFoundInNetworkException, NodeNotFoundInPropSetException, DuplicatePropositionException, CannotInsertJustificationSupportException, IllegalIdentifierException{ - //Clear all Nodes to implement the new Support Structure Above - setUp(); - //1st: Direct Support - //Build the Direct Support Structure - //The Set of Justifications We will use - int[] pqr = new int[4]; - pqr[0] = 1; - pqr[1] = 2; - pqr[2] = 3; - pqr[3] = 0; - - int[] mn = new int[2]; - mn[0] = 5; - mn[1] = 4; - - int[] vz = new int[2]; - vz[0] = 6; - vz[1] = 7; - - int[] ab = new int[2]; - ab[0] = 9; - ab[1] = 8; - - int[] cde = new int[3]; - cde[0] = 10; - cde[1] = 11; - cde[2] = 12; - - int[] fg = new int[2]; - fg[0] = 14; - fg[1] = 13; - - //Creating Proposition Sets by the previous Arrays of int - PropositionSet s1 = new PropositionSet(pqr); - PropositionSet s2 = new PropositionSet(mn); - PropositionSet s3 = new PropositionSet(vz); - PropositionSet s4 = new PropositionSet(ab); - PropositionSet s5 = new PropositionSet(cde); - PropositionSet s6 = new PropositionSet(fg); - - - - //Construct the tree "Bottum-Up" See the Graph above the method to imagine the Support Structure! - - n1.addJustificationBasedSupport(s2); - n1.addJustificationBasedSupport(s3); - n8.addJustificationBasedSupport(s5); - n3.addJustificationBasedSupport(s4); - n0.addJustificationBasedSupport(s6); - - //We Expect that adding Justification Supports bellow will throw CannotInsertJustificationSupportException - //And The Exception will be thrown when adding the propositionSet [[0, 1, 2, 3]] - thrown.expect(CannotInsertJustificationSupportException.class); - thrown.expectMessage("This PropositionSet contain a Cyclic Supports in the node PropositionSet [props=[0, 1, 2, 3]]"); - - - n0.addJustificationBasedSupport(s1); //This Have to cause the Previous Exception "CannotInsertJustificationSupportException" - - - } - - @Test - public void MAddInDirectCyclicJustificationSupport() throws NotAPropositionNodeException, NodeNotFoundInNetworkException, NodeNotFoundInPropSetException, DuplicatePropositionException, CannotInsertJustificationSupportException, InterruptedException, IllegalIdentifierException{ - //Clear all Nodes to implement the new Support Structure Above - setUp(); - - //2nd: InDirect Support - //Build the InDirect Support Structure - //The Set of Justifications We will use - int[] pqr = new int[3]; - pqr[0] = 1; - pqr[1] = 2; - pqr[2] = 3; - - int[] mn = new int[3]; - mn[0] = 5; - mn[1] = 4; - mn[2] = 0; - - int[] vz = new int[2]; - vz[0] = 6; - vz[1] = 7; - - int[] ab = new int[2]; - ab[0] = 9; - ab[1] = 8; - - int[] cde = new int[3]; - cde[0] = 10; - cde[1] = 11; - cde[2] = 12; - - - - int[] fg = new int[2]; - fg[0] = 14; - fg[1] = 13; - - //Creating Proposition Sets by the previous Arrays of int - PropositionSet s1 = new PropositionSet(pqr); - PropositionSet s2 = new PropositionSet(mn); - PropositionSet s3 = new PropositionSet(vz); - PropositionSet s4 = new PropositionSet(ab); - PropositionSet s5 = new PropositionSet(cde); - PropositionSet s6 = new PropositionSet(fg); - - - - //Construct the tree "Bottum-Up" See the Graph above the method to imagine the Support Structure! - - n1.addJustificationBasedSupport(s2); - - n1.addJustificationBasedSupport(s3); - - n8.addJustificationBasedSupport(s5); - - n3.addJustificationBasedSupport(s4); - - n0.addJustificationBasedSupport(s6); - - n0.addJustificationBasedSupport(s1); - - - - //Getting the justification supports of node 1. - Hashtablen1Justs= n1.getJustificationSupport(); - //Getting the justification supports of node 0. - Hashtablen0Justs= n0.getJustificationSupport(); - //Getting the assumption supports of node 1. - Hashtablen1Assump= n1.getAssumptionBasedSupport(); - //Getting the assumption supports of node 0. - Hashtablen0Assump= n0.getAssumptionBasedSupport(); - //Getting the supports Tree of node 0. - ArrayList>>mySupportsTree=n0.getMySupportsTree(); - - System.out.println(n1Justs.toString()); - System.out.println(n1Assump.toString()); - System.out.println(n0Justs.toString()); - System.out.println(n0Assump.toString()); - System.out.println(mySupportsTree.toString()); - - } + Hashtable justifications = new Hashtable(); + int[] res = new int[2]; + res[0] = 13; + res[1] = 14; + justifications.put("13,14,", new PropositionSet(res)); + + assertEquals(n0.getJustificationSupport(), justifications); + + } + + /* + * Consider We need To delete the node 12 from the Network (LeafNode) + * + * 0 / \ / \-> 13 | 14 1 |2 | 3 /\ \ / \ \ 4|5 6|7 8|9 / / 10 | 11 | 12 + * + * Expected to remove the whole support 10| 11| 12 From the structure. Expected + * to remove the whole support 8 | 9 From the structure. Expected to remove the + * whole support 1 | 2 | 3 From the structure. So the Assumption Support of the + * Node 0 will be 13 | 14 only + */ + @Test + public void IremoveLeafNodeAssumption12() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + // We already removed node 12 in the previous method. + // Working on that to check n0 assumption supports. + + Hashtable assumptions = new Hashtable(); + int[] res = new int[2]; + res[0] = 13; + res[1] = 14; + assumptions.put("13,14,", new PropositionSet(res)); + + assertEquals(n0.getAssumptionBasedSupport(), assumptions); + + } + + /* + * Consider We need To delete the node 6 from the Network (LeafNode) + * + * 0 / \ / \-> 13 | 14 1 |2 | 3 /\ \ / \ \ 4|5 6|7 8|9 / / 10 | 11 | 12 + * + * Expected to remove the whole support 6 | 7 From the structure. Not Expected + * to remove the whole support 1 | 2 | 3 From the structure. As Node 1 will + * still be supported by set 4|5 So the Justification Support of the Node 0 will + * be <<1 | 2 | 3>, <13 | 14>> + */ + @Test + public void JremoveLeafNodeJustificationSupport6() + throws NodeNotFoundInPropSetException, NotAPropositionNodeException, NodeNotFoundInNetworkException, + DuplicatePropositionException, CannotInsertJustificationSupportException { + // Because we have removed node 12 from node 8. + // And we have removed node 8 from node 3. + // And we have removed node 3 from node 0. + // Therefore, we need to return the set <1 | 2 | 3> , <8 | 9> , and <10| 11 | + // 12> to the hierarchy again.. + + int[] pqr; + + pqr = new int[3]; + pqr[0] = 10; + pqr[1] = 11; + pqr[2] = 12; + + n8.addJustificationBasedSupport(new PropositionSet(pqr)); + + pqr = new int[2]; + pqr[0] = 8; + pqr[1] = 9; + + n3.addJustificationBasedSupport(new PropositionSet(pqr)); + + pqr = new int[3]; + pqr[0] = 1; + pqr[1] = 2; + pqr[2] = 3; + + n0.addJustificationBasedSupport(new PropositionSet(pqr)); + + // Because the removal of any node only reflects on it's parent supports. + // Therefore the removal of n6 will only reflect on the supports structures of + // n0, and n1. + + // Getting parent supports of n6. + ArrayList parents = n6.getParentSupports(); + + // Loop over parent supports and delete n12 from them. + for (int i : parents) { + PropositionNode nx = (PropositionNode) Network.getNodeById(i); + // Deleting n1 from the supports of nx "n8 then n3 then n0 in this example" + nx.removeNodeFromSupports(n6); + } + Hashtable justifications = new Hashtable(); + int[] res; + res = new int[3]; + res[0] = 1; + res[1] = 2; + res[2] = 3; + + justifications.put("1,2,3,", new PropositionSet(res)); + + res = new int[2]; + res[0] = 13; + res[1] = 14; + + justifications.put("13,14,", new PropositionSet(res)); + + assertEquals(n0.getJustificationSupport(), justifications); + + } + + /* + * Consider We need To delete the node 6 from the Network (LeafNode) + * + * 0 / \ / \-> 13 | 14 1 |2 | 3 /\ \ / \ \ 4|5 6|7 8|9 / / 10 | 11 | 12 + * + * Expected to remove the whole support 6 | 7 From the structure. Not Expected + * to remove the whole support 1 | 2 | 3 From the structure. As Node 1 will + * still be supported by set 4|5 So the Assumption Support of the Node 0 will be + * <<2, 4, 5, 9, 10, 11, 12>, <13 | 14>> + */ + @Test + public void KremoveLeafNodeAssumption6() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + // We already removed node 6 in the previous method. + // Working on that to check n0 assumption supports. + + Hashtable assumptions = new Hashtable(); + int[] res; + res = new int[7]; + res[0] = 2; + res[1] = 4; + res[2] = 5; + res[3] = 9; + res[4] = 10; + res[5] = 11; + res[6] = 12; + + assumptions.put("2,4,5,9,10,11,12,", new PropositionSet(res)); + + res = new int[2]; + res[0] = 13; + res[1] = 14; + + assumptions.put("13,14,", new PropositionSet(res)); + + assertEquals(n0.getAssumptionBasedSupport(), assumptions); + } + + /* + * Consider the following 2 Tree Structures below + * + * Direct Cyclic Support: 0 / \ / \-> 13 | 14 0 |1 |2 | 3 /\ \ / \ \ 4|5 6|7 8|9 + * / / 10 | 11 | 12 + * + * Expected to Have an Exception Says we have a cyclic supports, So that the + * justification support 0 | 1 | 2 | 3 cannot be support for proposition 0 So + * that the Justification support 0 | 1 | 2 | 3 cannot be added to the + * justification support of 0 + * + * InDirect Cyclic Support: 0 / \ / \-> 13 | 14 1 |2 | 3 /\ \ / \ \ 0|4|5 6|7 + * 8|9 / / 10 | 11 | 12 + * + * The path containning the cycle 0 |4 |5 will not be included in the + * supportTree, As it is an invalid path. Therefore we cannot also start by Node + * 1 as it is not a Hyp. So it will be deleted too. And the same goes for Node + * 3. So support Tree will be <<[13,0],[14,0]>> N0000: Expected to Have an + * Exception Says we have a cyclic supports, So that the justification support 0 + * | 10 | 11 | 12 cannot be support for proposition 0 So that the Justification + * support 1 | 2 | 3 cannot be added to the justification support of 0 + */ + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void LAddDirectCyclicJustificationSupport() + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, NodeNotFoundInPropSetException, + DuplicatePropositionException, CannotInsertJustificationSupportException, IllegalIdentifierException { + // Clear all Nodes to implement the new Support Structure Above + setUp(); + // 1st: Direct Support + // Build the Direct Support Structure + // The Set of Justifications We will use + int[] pqr = new int[4]; + pqr[0] = 1; + pqr[1] = 2; + pqr[2] = 3; + pqr[3] = 0; + + int[] mn = new int[2]; + mn[0] = 5; + mn[1] = 4; + + int[] vz = new int[2]; + vz[0] = 6; + vz[1] = 7; + + int[] ab = new int[2]; + ab[0] = 9; + ab[1] = 8; + + int[] cde = new int[3]; + cde[0] = 10; + cde[1] = 11; + cde[2] = 12; + + int[] fg = new int[2]; + fg[0] = 14; + fg[1] = 13; + + // Creating Proposition Sets by the previous Arrays of int + PropositionSet s1 = new PropositionSet(pqr); + PropositionSet s2 = new PropositionSet(mn); + PropositionSet s3 = new PropositionSet(vz); + PropositionSet s4 = new PropositionSet(ab); + PropositionSet s5 = new PropositionSet(cde); + PropositionSet s6 = new PropositionSet(fg); + + // Construct the tree "Bottum-Up" See the Graph above the method to imagine the + // Support Structure! + + n1.addJustificationBasedSupport(s2); + n1.addJustificationBasedSupport(s3); + n8.addJustificationBasedSupport(s5); + n3.addJustificationBasedSupport(s4); + n0.addJustificationBasedSupport(s6); + + // We Expect that adding Justification Supports bellow will throw + // CannotInsertJustificationSupportException + // And The Exception will be thrown when adding the propositionSet [[0, 1, 2, + // 3]] + thrown.expect(CannotInsertJustificationSupportException.class); + thrown.expectMessage( + "This PropositionSet contain a Cyclic Supports in the node PropositionSet [props=[0, 1, 2, 3]]"); + + n0.addJustificationBasedSupport(s1); // This Have to cause the Previous Exception + // "CannotInsertJustificationSupportException" + + } + + @Test + public void MAddInDirectCyclicJustificationSupport() throws NotAPropositionNodeException, + NodeNotFoundInNetworkException, NodeNotFoundInPropSetException, DuplicatePropositionException, + CannotInsertJustificationSupportException, InterruptedException, IllegalIdentifierException { + // Clear all Nodes to implement the new Support Structure Above + setUp(); + + // 2nd: InDirect Support + // Build the InDirect Support Structure + // The Set of Justifications We will use + int[] pqr = new int[3]; + pqr[0] = 1; + pqr[1] = 2; + pqr[2] = 3; + + int[] mn = new int[3]; + mn[0] = 5; + mn[1] = 4; + mn[2] = 0; + + int[] vz = new int[2]; + vz[0] = 6; + vz[1] = 7; + + int[] ab = new int[2]; + ab[0] = 9; + ab[1] = 8; + + int[] cde = new int[3]; + cde[0] = 10; + cde[1] = 11; + cde[2] = 12; + + int[] fg = new int[2]; + fg[0] = 14; + fg[1] = 13; + + // Creating Proposition Sets by the previous Arrays of int + PropositionSet s1 = new PropositionSet(pqr); + PropositionSet s2 = new PropositionSet(mn); + PropositionSet s3 = new PropositionSet(vz); + PropositionSet s4 = new PropositionSet(ab); + PropositionSet s5 = new PropositionSet(cde); + PropositionSet s6 = new PropositionSet(fg); + + // Construct the tree "Bottum-Up" See the Graph above the method to imagine the + // Support Structure! + + n1.addJustificationBasedSupport(s2); + + n1.addJustificationBasedSupport(s3); + + n8.addJustificationBasedSupport(s5); + + n3.addJustificationBasedSupport(s4); + + n0.addJustificationBasedSupport(s6); + + n0.addJustificationBasedSupport(s1); + + // Getting the justification supports of node 1. + Hashtable n1Justs = n1.getJustificationSupport(); + // Getting the justification supports of node 0. + Hashtable n0Justs = n0.getJustificationSupport(); + // Getting the assumption supports of node 1. + Hashtable n1Assump = n1.getAssumptionBasedSupport(); + // Getting the assumption supports of node 0. + Hashtable n0Assump = n0.getAssumptionBasedSupport(); + // Getting the supports Tree of node 0. + ArrayList>> mySupportsTree = n0.getMySupportsTree(); + + System.out.println(n1Justs.toString()); + System.out.println(n1Assump.toString()); + System.out.println(n0Justs.toString()); + System.out.println(n0Assump.toString()); + System.out.println(mySupportsTree.toString()); + + } } \ No newline at end of file From a281555311fc41c6d9f9f33087a4a52a9fe87bb2 Mon Sep 17 00:00:00 2001 From: Youssef Date: Sun, 12 May 2019 01:13:27 +0200 Subject: [PATCH 14/22] latest checkpoint on 12/5, report support changed to propset, modified testReportToSend to accomodate match channels check and new support check and separating the channels to a hashtable hashed by channel types --- src/sneps/network/Node.java | 2 + src/sneps/network/PropositionNode.java | 496 ++++-- src/sneps/network/RuleNode.java | 155 +- .../classes/setClasses/ChannelSet.java | 50 +- .../classes/setClasses/PropositionSet.java | 2 +- .../network/classes/setClasses/ReportSet.java | 13 +- src/sneps/snebr/Controller.java | 1349 +++++++++-------- src/sneps/snip/Report.java | 38 +- src/sneps/snip/Runner.java | 31 +- .../channels/AntecedentToRuleChannel.java | 8 + src/sneps/snip/channels/Channel.java | 18 +- src/sneps/snip/channels/MatchChannel.java | 34 + .../channels/RuleToConsequentChannel.java | 8 + src/sneps/snip/classes/FlagNode.java | 10 +- src/sneps/snip/classes/VariableNodeStats.java | 15 +- .../snip/matching/HashSubstitutions.java | 192 +++ .../snip/matching/LinearSubstitutions.java | 7 +- src/sneps/snip/rules/OrNode.java | 7 +- 18 files changed, 1535 insertions(+), 900 deletions(-) create mode 100644 src/sneps/snip/matching/HashSubstitutions.java diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java index b4d1b4a3..1d91090e 100644 --- a/src/sneps/network/Node.java +++ b/src/sneps/network/Node.java @@ -5,6 +5,7 @@ import java.util.LinkedList; import java.util.List; +import sneps.network.cables.DownCableSet; import sneps.network.cables.UpCable; import sneps.network.cables.UpCableSet; import sneps.network.classes.Semantic; @@ -119,6 +120,7 @@ public String getIdentifier() { public UpCableSet getUpCableSet() { return this.term.getUpCableSet(); } + /** * diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 15501f64..c48a66a3 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -11,6 +11,7 @@ import sneps.exceptions.NodeNotFoundInNetworkException; import sneps.exceptions.NodeNotFoundInPropSetException; import sneps.exceptions.NotAPropositionNodeException; +import sneps.network.cables.UpCable; import sneps.network.classes.Semantic; import sneps.network.classes.setClasses.ChannelSet; import sneps.network.classes.setClasses.NodeSet; @@ -61,70 +62,6 @@ public PropositionNode(Term trm) { setTerm(trm); } - /*** - * Trying to send a report to all outgoing channels - * - * @param report - */ - public void broadcastReport(Report report) { - for (Channel outChannel : outgoingChannels) - sendReport(report, outChannel); - } - - /*** - * Used to send a report over a channel through calling Channel.testReportToSend - * - * @param report - * @param channel - * @return - */ - public boolean sendReport(Report report, Channel channel) { - try { - if (channel.testReportToSend(report)) { - System.out.println("Report instance (" + report + ") was successfuly sent over (" + channel + ")"); - } - } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { - System.out.println("Report instance (" + report + ") could not be sent."); - e.printStackTrace(); - } - return false; - } - - protected void sendReports(NodeSet isAntecedentTo, ReportSet reports, ChannelTypes channelType, - Channel currentChannel) { - if (isAntecedentTo != null) - for (Node node : isAntecedentTo) { - for (Report report : reports) { - Substitutions reportSubs = report.getSubstitutions(); - Support reportSupp = report.getSupport(); - boolean reportSign = report.getSign(); - String currentChannelContextName = currentChannel.getContextName(); - Channel newChannel = establishChannel(channelType, node, null, reportSubs, - currentChannelContextName, -1); - outgoingChannels.addChannel(newChannel); - node.receiveReport(newChannel); - } - } - } - - protected void sendReports(List list, ReportSet reports, Channel currentChannel) { - if (list != null) - for (Match match : list) { - for (Report report : reports) { - Substitutions reportSubs = report.getSubstitutions(); -// Collection reportSuppSet = report.getSupports(); - Node sentTo = match.getNode(); -// boolean reportSign = report.getSign(); - String currentChannelContextName = currentChannel.getContextName(); - int matchType = match.getMatchType(); - Channel newChannel = establishChannel(ChannelTypes.MATCHED, sentTo, null, reportSubs, - currentChannelContextName, matchType); - outgoingChannels.addChannel(newChannel); - sentTo.receiveReport(newChannel); - } - } - } - /*** * Method handling all types of Channels establishment according to different * channel types passed through the matching. @@ -161,6 +98,92 @@ protected Channel establishChannel(ChannelTypes type, Object currentElement, Sub } + /*** + * Used to send a report over a channel through calling Channel.testReportToSend + * + * @param report + * @param channel + * @return + */ + public boolean sendReport(Report report, Channel channel) { + try { + if (channel.testReportToSend(report)) { + System.out.println("Report instance (" + report + ") was successfuly sent over (" + channel + ")"); + } + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { + System.out.println("Report instance (" + report + ") could not be sent."); + e.printStackTrace(); + } + return false; + } + + /*** + * Trying to send a report to all outgoing channels + * + * @param report + */ + public void broadcastReport(Report report) { + for (Channel outChannel : outgoingChannels) + sendReport(report, outChannel); + } + + /*** + * Helper method responsible for establishing channels between this current node + * and each of the NodeSet to further request instances with the given inputs + * + * @param ns NodeSet to be sent to + * @param toBeSent Substitutions to be passed + * @param contextID latest channel context + * @param channelType + * @param inferenceType + */ + protected void sendReportToNodeSet(NodeSet ns, Report toBeSent, String contextID, ChannelTypes channelType) { + for (Node sentTo : ns) { + Substitutions reportSubs = toBeSent.getSubstitutions(); + Channel newChannel = establishChannel(channelType, sentTo, null, reportSubs, contextID, -1); + ReportSet channelReportBuffer = newChannel.getReportsBuffer(); + channelReportBuffer.addReport(toBeSent); + outgoingChannels.addChannel(newChannel); + sentTo.receiveReport(newChannel); + } + } + + protected void sendReportsToNodeSet(NodeSet ns, ReportSet reports, String contextID, ChannelTypes channelType) { + for (Report report : reports) { + sendReportToNodeSet(ns, report, contextID, channelType); + } + + } + + /*** + * Helper method responsible for establishing channels between this current node + * and each of the List to further request instances with the given + * inputs + * + * @param list + * @param toBeSent + * @param contextId + * @param inferenceType + */ + protected void sendReportToMatches(List list, Report toBeSent, String contextId) { + for (Match currentMatch : list) { + Substitutions reportSubs = toBeSent.getSubstitutions(); + int matchType = currentMatch.getMatchType(); + Channel newChannel = establishChannel(ChannelTypes.MATCHED, currentMatch, null, reportSubs, contextId, + matchType); + ReportSet channelReportBuffer = newChannel.getReportsBuffer(); + channelReportBuffer.addReport(toBeSent); + outgoingChannels.addChannel(newChannel); + currentMatch.getNode().receiveReport(newChannel); + } + } + + protected void sendReportsToMatches(List list, ReportSet reports, String contextId) { + for (Report report : reports) { + sendReportToMatches(list, report, contextId); + } + } + /*** * Helper method responsible for establishing channels between this current node * and each of the List to further request instances with the given @@ -201,97 +224,6 @@ protected void sendRequestsToNodeSet(NodeSet ns, Substitutions filterSubs, Strin } } - public void processRequests() { - for (Channel outChannel : outgoingChannels) - try { - processSingleRequestsChannel(outChannel); - } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { - e.printStackTrace(); - } catch (DuplicatePropositionException e) { - e.printStackTrace(); - } - } - - /*** - * Request handling in Non-Rule proposition nodes. - * - * @param currentChannel - * @throws NodeNotFoundInNetworkException - * @throws NotAPropositionNodeException - * @throws DuplicatePropositionException - */ - protected void processSingleRequestsChannel(Channel currentChannel) - throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { - Support nodeSupport = getBasicSupport(); - String currentContextName = currentChannel.getContextName(); - Context desiredContext = Controller.getContextByName(currentContextName); - if (assertedInContext(desiredContext)) { - // TODO change the subs to hashsubs - Report reply = new Report(new LinearSubstitutions(), nodeSupport, true, InferenceTypes.BACKWARD); - sendReport(reply, currentChannel); - } else { - boolean sentAtLeastOne = false; - for (Report currentReport : knownInstances) - sentAtLeastOne |= sendReport(currentReport, currentChannel); - Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); - if (!sentAtLeastOne || isWhQuestion(filterSubs)) { - NodeSet dominatingRules = getDominatingRules(); - NodeSet toBeSentToDom = removeAlreadyWorkingOn(dominatingRules, currentChannel, false); - sendRequestsToNodeSet(toBeSentToDom, new LinearSubstitutions(), currentContextName, - ChannelTypes.RuleAnt); - if (!(currentChannel instanceof MatchChannel)) { - List matchingNodes = Matcher.match(this); - List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel, false); - sendRequestsToMatches(toBeSentToMatch, currentContextName); - } - } - } - } - - public void processReports() { - for (Channel inChannel : incomingChannels) - processSingleReportsChannel(inChannel); - } - - /*** - * Report handling in Non-Rule proposition nodes. - * - * @param currentChannel - */ - protected void processSingleReportsChannel(Channel currentChannel) { - ReportSet reports = currentChannel.getReportsBuffer(); - for (Report currentReport : reports) { - Substitutions reportSubs = currentReport.getSubstitutions(); - Support reportSupport = currentReport.getSupport(); - boolean reportSign = currentReport.isPositive(); - boolean toBeSentFlag = true; - if (currentChannel instanceof MatchChannel) { - int channelMatchType = ((MatchChannel) currentChannel).getMatchType(); - toBeSentFlag = (channelMatchType == 0) || (channelMatchType == 1 && currentReport.isPositive()) - || (channelMatchType == 2 && currentReport.isNegative()); - } - Report alteredBReport = new Report(reportSubs, reportSupport, reportSign, InferenceTypes.BACKWARD); - Report alteredFReport = new Report(reportSubs, reportSupport, reportSign, InferenceTypes.FORWARD); - boolean backwardReportFound = knownInstances.contains(alteredBReport); - boolean forwardReportFound = knownInstances.contains(alteredFReport); - if ((!backwardReportFound || !forwardReportFound) && toBeSentFlag) { - broadcastReport(!forwardReportFound ? alteredFReport : alteredBReport); - } - /* Handling forward inference broadcasting */ - if (currentReport.getInferenceType() == InferenceTypes.FORWARD) { - List matchesReturned = Matcher.match(this); - sendReports(matchesReturned, reports, currentChannel); - NodeSet isAntecedentTo = getDominatingRules(); - sendReports(isAntecedentTo, reports, ChannelTypes.RuleAnt, currentChannel); - } - } - currentChannel.clearReportsBuffer(); - } - - // PROCESS REPORT : 3adi -> , forward - // -> same as 3adi , plus matching to send and get the nodes el howa lihom - // antecedents we send reports - /*** * * @param desiredContext @@ -332,13 +264,46 @@ public void receiveReports(Channel channel) { public void deduce() { Runner.initiate(); String currentContextName = Controller.getCurrentContextName(); - getNodesToSendRequests(ChannelTypes.RuleCons, currentContextName, null, InferenceTypes.BACKWARD); - getNodesToSendRequests(ChannelTypes.MATCHED, currentContextName, null, InferenceTypes.BACKWARD); + getNodesToSendRequest(ChannelTypes.RuleCons, currentContextName, null, InferenceTypes.BACKWARD); + getNodesToSendRequest(ChannelTypes.MATCHED, currentContextName, null, InferenceTypes.BACKWARD); // what to return here ? System.out.println(Runner.run()); } public void add() { + Runner.initiate(); + String currentContextName = Controller.getCurrentContextName(); + boolean reportSign = Controller.isNegated(this); + getNodesToSendReport(ChannelTypes.RuleAnt, currentContextName, null, reportSign, InferenceTypes.FORWARD); + getNodesToSendReport(ChannelTypes.MATCHED, currentContextName, null, reportSign, InferenceTypes.FORWARD); + System.out.println(Runner.run()); + } + + protected void getNodesToSendReport(ChannelTypes channelType, String currentContextName, + Substitutions substitutions, boolean reportSign, InferenceTypes inferenceType) { + try { + PropositionSet supportPropSet = new PropositionSet(); + supportPropSet.add(getId()); + Report toBeSent = new Report(substitutions, supportPropSet, reportSign, inferenceType); + switch (channelType) { + case MATCHED: + List matchesReturned = Matcher.match(this); + if (matchesReturned != null) + sendReportToMatches(matchesReturned, toBeSent, currentContextName); + break; + case RuleAnt: + if (this instanceof RuleNode) { + NodeSet antecedentsNodes = ((RuleNode) this).getDownAntNodeSet(); + sendReportToNodeSet(antecedentsNodes, toBeSent, currentContextName, channelType); + break; + } + + default: + break; + } + } catch (Exception e) { + e.printStackTrace(); + } } @@ -351,7 +316,7 @@ public void add() { * @param substitutions channel substitutions applied over the channel * @param inferenceType inference type used for this process */ - protected void getNodesToSendRequests(ChannelTypes channelType, String currentContextName, + protected void getNodesToSendRequest(ChannelTypes channelType, String currentContextName, Substitutions substitutions, InferenceTypes inferenceType) { try { switch (channelType) { @@ -361,7 +326,7 @@ protected void getNodesToSendRequests(ChannelTypes channelType, String currentCo sendRequestsToMatches(matchesReturned, currentContextName); break; case RuleCons: - NodeSet dominatingRules = getDominatingRules(); + NodeSet dominatingRules = getUpConsNodeSet(); // TODO Youssef: check if passing a new LinearSubstitutions is correct Substitutions linearSubs = substitutions == null ? new LinearSubstitutions() : substitutions; sendRequestsToNodeSet(dominatingRules, linearSubs, currentContextName, channelType); @@ -416,24 +381,25 @@ protected List removeAlreadyWorkingOn(List matchingNodes, Channel * not to re-send redundant requests -- ruleType gets applied on Andor or Thresh * part. * - * @param node set on which we will check existing request - * @param channel current channel handling the current request + * @param node set on which we will check existing request + * @param channel current channel handling the current request + * @param toBeCompared subs to be compared over each node * @return NodeSet containing all nodes that has not previously requested the * subset of the specified channel request */ - protected static NodeSet removeAlreadyWorkingOn(NodeSet nodes, Channel channel, boolean ruleType) { + protected static NodeSet removeAlreadyWorkingOn(NodeSet nodes, Channel channel, Substitutions toBeCompared, + boolean ruleType) { NodeSet nodesToConsider = new NodeSet(); for (Node sourceNode : nodes) if (sourceNode instanceof PropositionNode) { boolean conditionMet = ruleType && sourceNode == channel.getRequester(); if (!conditionMet) { conditionMet = true; - Substitutions currentChannelFilterSubs = channel.getFilter().getSubstitutions(); ChannelSet outgoingChannels = ((PropositionNode) sourceNode).getOutgoingChannels(); ChannelSet filteredChannelsSet = outgoingChannels.getFilteredRequestChannels(true); for (Channel outgoingChannel : filteredChannelsSet) { Substitutions processedChannelFilterSubs = outgoingChannel.getFilter().getSubstitutions(); - conditionMet &= !processedChannelFilterSubs.isSubSet(currentChannelFilterSubs) + conditionMet &= !processedChannelFilterSubs.isSubSet(toBeCompared) && outgoingChannel.getRequester() == channel.getReporter(); } if (conditionMet) @@ -507,6 +473,82 @@ public ArrayList getParentSupports() { return basicSupport.getParentSupports(); } + /*** + * Method getting the NodeSet that this current node is considered a consequent + * to + * + * @return + */ + public NodeSet getUpConsNodeSet() { + NodeSet ret = new NodeSet(); + UpCable consequentCable = this.getUpCableSet().getUpCable("cq"); + UpCable argsCable = this.getUpCableSet().getUpCable("arg"); + if (argsCable != null) { + ret.addAll(argsCable.getNodeSet()); + } + if (consequentCable != null) { + ret.addAll(consequentCable.getNodeSet()); + } + + return ret; + } + + /*** + * Method getting the NodeSet for nodes that are consequents to this node + * + * @return + */ + /* + * public NodeSet getDownConsNodeSet() { NodeSet ret = new NodeSet(); UpCable + * consequentCable = this.getDownCableSet().getUpCable("cq"); UpCable argsCable + * = this.getDownCableSet().getUpCable("arg"); if (argsCable != null) { + * ret.addAll(argsCable.getNodeSet()); } if (consequentCable != null) { + * ret.addAll(consequentCable.getNodeSet()); } + * + * return ret; } + */ + + /*** + * Method getting the NodeSet that this current node is considered an antecedent + * to + * + * @return + */ + public NodeSet getUpAntNodeSet() { + NodeSet ret = new NodeSet(); + UpCable argsCable = this.getUpCableSet().getUpCable("arg"); + UpCable andAntCable = this.getUpCableSet().getUpCable("&ant"); + UpCable antCable = this.getUpCableSet().getUpCable("ant"); + if (argsCable != null) { + ret.addAll(argsCable.getNodeSet()); + } + if (antCable != null) { + ret.addAll(antCable.getNodeSet()); + } + if (andAntCable != null) { + ret.addAll(andAntCable.getNodeSet()); + } + + return ret; + } + + /*** + * Method getting the NodeSet of the antecedents for this current node + * + * @return + */ + /* + * public NodeSet getDownAntNodeSet() { NodeSet ret = new NodeSet(); UpCable + * argsCable = this.getDownCableSet().getUpCable("arg"); UpCable andAntCable = + * this.getDownCableSet().getUpCable("&ant"); UpCable antCable = + * this.getDownCableSet().getUpCable("ant"); if (argsCable != null) { + * ret.addAll(argsCable.getNodeSet()); } if (antCable != null) { + * ret.addAll(antCable.getNodeSet()); } if (andAntCable != null) { + * ret.addAll(andAntCable.getNodeSet()); } + * + * return ret; } + */ + public boolean HasChildren() { return basicSupport.HasChildren(); } @@ -523,4 +565,130 @@ public boolean reStructureJustifications() throws NotAPropositionNodeException, public void setHyp(boolean isHyp) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { basicSupport.setHyp(isHyp); } + + 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 void processRequests() { + for (Channel outChannel : outgoingChannels) + try { + processSingleRequestsChannel(outChannel); + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { + e.printStackTrace(); + } catch (DuplicatePropositionException e) { + e.printStackTrace(); + } + } + + /*** + * Request handling in Non-Rule proposition nodes. + * + * @param currentChannel + * @throws NodeNotFoundInNetworkException + * @throws NotAPropositionNodeException + * @throws DuplicatePropositionException + */ + protected void processSingleRequestsChannel(Channel currentChannel) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { + Support nodeSupport = getBasicSupport(); + + String currentContextName = currentChannel.getContextName(); + Context desiredContext = Controller.getContextByName(currentContextName); + if (assertedInContext(desiredContext)) { + // TODO change the subs to hashsubs + int propNodeId = getId(); + PropositionSet supportPropSet = new PropositionSet(); + supportPropSet.add(propNodeId); + Report reply = new Report(new LinearSubstitutions(), supportPropSet, true, InferenceTypes.BACKWARD); + sendReport(reply, currentChannel); + } else { + boolean sentAtLeastOne = false; + for (Report currentReport : knownInstances) + sentAtLeastOne |= sendReport(currentReport, currentChannel); + Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); + if (!sentAtLeastOne || isWhQuestion(filterSubs)) { + NodeSet dominatingRules = getDominatingRules(); + NodeSet toBeSentToDom = removeAlreadyWorkingOn(dominatingRules, currentChannel, filterSubs, false); + sendRequestsToNodeSet(toBeSentToDom, new LinearSubstitutions(), currentContextName, + ChannelTypes.RuleAnt); + if (!(currentChannel instanceof MatchChannel)) { + List matchingNodes = Matcher.match(this); + List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel, false); + sendRequestsToMatches(toBeSentToMatch, currentContextName); + } + } + } + } + + public void processReports() { + for (Channel inChannel : incomingChannels) + try { + processSingleReportsChannel(inChannel); + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException | DuplicatePropositionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /*** + * Report handling in Non-Rule proposition nodes. + * + * @param currentChannel + * @throws NodeNotFoundInNetworkException + * @throws NotAPropositionNodeException + * @throws DuplicatePropositionException + */ + protected void processSingleReportsChannel(Channel currentChannel) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { + ReportSet reports = currentChannel.getReportsBuffer(); + String currentChannelContextName = currentChannel.getContextName(); + for (Report currentReport : reports) { + Substitutions reportSubs = currentReport.getSubstitutions(); + PropositionSet reportSupport = currentReport.getSupport(); + boolean reportSign = currentReport.isPositive(); + boolean toBeSentFlag = true; + /* to be removed and handled in testReportToSend */ + Report alteredBReport = new Report(reportSubs, reportSupport, reportSign, InferenceTypes.BACKWARD); + Report alteredFReport = new Report(reportSubs, reportSupport, reportSign, InferenceTypes.FORWARD); + boolean backwardReportFound = knownInstances.contains(alteredBReport); + boolean forwardReportFound = knownInstances.contains(alteredFReport); + if ((!backwardReportFound || !forwardReportFound) && toBeSentFlag) { + broadcastReport(!forwardReportFound ? alteredFReport : alteredBReport); + } + /* Handling forward inference broadcasting */ + if (currentReport.getInferenceType() == InferenceTypes.FORWARD) { + List matchesReturned = Matcher.match(this); + sendReportToMatches(matchesReturned, currentReport, currentChannelContextName); + NodeSet isAntecedentTo = getUpAntNodeSet(); + sendReportToNodeSet(isAntecedentTo, currentReport, currentChannelContextName, ChannelTypes.RuleAnt); + } + } + currentChannel.clearReportsBuffer(); + } + + // PROCESS REPORT : 3adi -> , forward + // -> same as 3adi , plus matching to send and get the nodes el howa lihom + // antecedents we send reports + } \ No newline at end of file diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index 160eaddd..ce54c303 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -26,8 +26,10 @@ import sneps.snebr.Context; import sneps.snebr.Controller; import sneps.snebr.Support; +import sneps.snip.Filter; import sneps.snip.InferenceTypes; import sneps.snip.Report; +import sneps.snip.Runner; import sneps.snip.channels.AntecedentToRuleChannel; import sneps.snip.channels.Channel; import sneps.snip.channels.ChannelTypes; @@ -271,18 +273,27 @@ public static boolean isConstantNode(Node n) { protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel) { NodeSet antecedentNodeSet = getDownAntNodeSet(); boolean ruleType = this instanceof ThreshNode || this instanceof AndOrNode; - NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentNodeSet, currentChannel, ruleType); + Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); + NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentNodeSet, currentChannel, filterSubs, ruleType); sendRequestsToNodeSet(toBeSentTo, currentChannel.getFilter().getSubstitutions(), currentChannel.getContextName(), ChannelTypes.RuleAnt); } + /*** + * Sending requests with a union substitutions between the original request and + * the report to all Antecedents not already working on that type of request. + * + * @param currentChannel + * @param report + */ protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel, Report report) { NodeSet antecedentNodeSet = getDownAntNodeSet(); boolean ruleType = this instanceof ThreshNode || this instanceof AndOrNode; - NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentNodeSet, currentChannel, ruleType); - sendRequestsToNodeSet(toBeSentTo, report.getSubstitutions(), currentChannel.getContextName(), - ChannelTypes.RuleAnt); - + Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); + Substitutions reportSubs = report.getSubstitutions(); + Substitutions unionSubs = filterSubs.union(reportSubs); + NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentNodeSet, currentChannel, unionSubs, ruleType); + sendRequestsToNodeSet(toBeSentTo, unionSubs, currentChannel.getContextName(), ChannelTypes.RuleAnt); } /* @@ -296,20 +307,37 @@ protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel, Rep * false; } */ - protected void sendReportToNodeSet(NodeSet nodeSet, Report report, ChannelTypes channelType, + public void handleResponseOfApplyRuleHandler(RuleResponse ruleResponse, Report currentReport, Channel currentChannel) { - if (nodeSet != null) - for (Node node : nodeSet) { - Substitutions reportSubs = report.getSubstitutions(); - Support reportSupp = report.getSupport(); - boolean reportSign = report.getSign(); - String currentChannelContextName = currentChannel.getContextName(); - Channel newChannel = establishChannel(channelType, node, null, reportSubs, currentChannelContextName, - -1); - outgoingChannels.addChannel(newChannel); - node.receiveReport(newChannel); + String currentChannelContextName = currentChannel.getContextName(); + if (ruleResponse != null) { + Report toBeSent = ruleResponse.getReport(); + broadcastReport(toBeSent); + if (toBeSent.getInferenceType() == InferenceTypes.FORWARD) { + NodeSet consequents = ruleResponse.getConsequents(); + NodeSet filteredNodeSet = removeExistingNodesOutgoingChannels(consequents); + sendReportToNodeSet(filteredNodeSet, toBeSent, currentChannelContextName, ChannelTypes.RuleCons); + } + } else if (currentReport.getInferenceType() == InferenceTypes.FORWARD) { + + Substitutions currentChannelFilterSubs = currentChannel.getFilter().getSubstitutions(); + NodeSet antecedents = getDownAntNodeSet(); + antecedents.removeNode(currentChannel.getReporter()); + sendRequestsToNodeSet(antecedents, currentChannelFilterSubs, currentChannelContextName, + ChannelTypes.RuleAnt); + } + } + private NodeSet removeExistingNodesOutgoingChannels(NodeSet nodeSet) { + ChannelSet outgoingChannels = getOutgoingChannels(); + Collection channels = outgoingChannels.getChannels(); + for (Node node : nodeSet) + for (Channel channel : channels) { + Node channelRequester = channel.getRequester(); + if (node.equals(channelRequester)) + nodeSet.removeNode(node); } + return nodeSet; } public void processRequests() { @@ -349,17 +377,13 @@ protected void processSingleRequestsChannel(Channel currentChannel) } else { VariableNodeStats ruleNodeStats = computeNodeStats(filterSubs); boolean ruleNodeAllVariablesBound = ruleNodeStats.areAllVariablesBound(); - Vector ruleNodeExtractedSubs = ruleNodeStats.getVariableNodeSubs(); + Substitutions ruleNodeExtractedSubs = ruleNodeStats.getVariableNodeSubs(); /* Case 2 & 3 */ ReportSet knownReportSet = knownInstances; for (Report report : knownReportSet) { Substitutions reportSubstitutions = report.getSubstitutions(); - VariableNodeStats reportNodeStats = computeNodeStats(reportSubstitutions); - Vector reportNodeExtractedSubs = reportNodeStats.getVariableNodeSubs(); - boolean caseCondition = ruleNodeAllVariablesBound - ? reportNodeExtractedSubs.size() == ruleNodeExtractedSubs.size() - : reportNodeExtractedSubs.size() < ruleNodeExtractedSubs.size(); - if (caseCondition && report.anySupportAssertedInContext(currentContext)) { + boolean subSetCheck = ruleNodeExtractedSubs.isSubSet(reportSubstitutions); + if (subSetCheck && report.anySupportAssertedInContext(currentContext)) { if (ruleNodeAllVariablesBound) { requestAntecedentsNotAlreadyWorkingOn(currentChannel); return; @@ -368,6 +392,10 @@ protected void processSingleRequestsChannel(Channel currentChannel) } } + /* + * balash delwa2ty: badal el super i just need the isWhQuestion mel superto be + * executed bas + */ super.processSingleRequestsChannel(currentChannel); return; } @@ -383,47 +411,70 @@ protected void processSingleRequestsChannel(Channel currentChannel) */ public void processReports() { for (Channel currentChannel : incomingChannels) - processSingleReportsChannel(currentChannel); + try { + processSingleReportsChannel(currentChannel); + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException | DuplicatePropositionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } - protected void processSingleReportsChannel(Channel currentChannel) { + protected void processSingleReportsChannel(Channel currentChannel) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { ReportSet channelReports = currentChannel.getReportsBuffer(); String currentChannelContextName = currentChannel.getContextName(); - Substitutions currentChannelFilterSubs = currentChannel.getFilter().getSubstitutions(); - Substitutions currentChannelSwitchSubs = currentChannel.getSwitch().getSubstitutions(); + boolean assertedInContext = assertedInContext(currentChannelContextName); + boolean closedTypeTerm = term instanceof Closed; + ReportSet currentChannelReportBuffer = currentChannel.getReportsBuffer(); for (Report currentReport : channelReports) { + boolean forwardReportType = currentReport.getInferenceType() == InferenceTypes.FORWARD; Substitutions currentReportSubs = currentReport.getSubstitutions(); if (currentChannel instanceof AntecedentToRuleChannel) { - RuleResponse ruleResponse = applyRuleHandler(currentReport, currentChannel); - if (ruleResponse != null) { - Report toBeSent = ruleResponse.getReport(); - broadcastReport(toBeSent); - if (toBeSent.getInferenceType() == InferenceTypes.FORWARD) { - NodeSet consequents = ruleResponse.getConsequents(); - NodeSet filteredNodeSet = removeExistingNodesOutgoingChannels(consequents); - sendReportToNodeSet(filteredNodeSet, toBeSent, ChannelTypes.RuleCons, currentChannel); + if (forwardReportType) { + if (closedTypeTerm) { + /* Check ana asserted ezay */ + } else if (assertedInContext) { + RuleResponse ruleResponse = applyRuleHandler(currentReport, currentChannel); + handleResponseOfApplyRuleHandler(ruleResponse, currentReport, currentChannel); + /* DONE: remove the report 3ashan khalas i asserted myself */ + currentChannelReportBuffer.removeReport(currentReport); + } else { + Channel newChannel = ((AntecedentToRuleChannel) currentChannel).clone(); + Filter newChannelSubs = new Filter(currentReportSubs); + newChannel.setFilter(newChannelSubs); + super.processSingleRequestsChannel(newChannel); } - } else if (currentReport.getInferenceType() == InferenceTypes.FORWARD) { - NodeSet antecedents = getDownAntNodeSet(); - antecedents.removeNode(this); - sendRequestsToNodeSet(antecedents, currentChannelFilterSubs, currentChannelContextName, - ChannelTypes.RuleAnt); + /* add report to buffer */ + } else { + /* keda keda asserted, fa remove the report from the buffer */ + RuleResponse ruleResponse = applyRuleHandler(currentReport, currentChannel); + handleResponseOfApplyRuleHandler(ruleResponse, currentReport, currentChannel); + /* DONE: remove the report 3ashan khalas i asserted myself */ + currentChannelReportBuffer.removeReport(currentReport); } + } else { + Set ruleConsChannels = getOutgoingRuleConsequentChannels(); + if (forwardReportType) { + } else { + if (ruleConsChannels.isEmpty()) { + Runner.addToLowQueue(this); + } else { + + } + } + /* + * backward: if existing outgoing channels (ruletoconsequent) to handle request, + * put on the low queue + * + * else same as super but add filters over outgoing channels to send on to send + * over antecedent to rule and match types + * + * + * forward: send requests to the antecedents with the report subs + */ } } - currentChannel.clearReportsBuffer(); } - private NodeSet removeExistingNodesOutgoingChannels(NodeSet nodeSet) { - ChannelSet outgoingChannels = getOutgoingChannels(); - Set channels = outgoingChannels.getChannels(); - for (Node node : nodeSet) - for (Channel channel : channels) { - Node channelRequester = channel.getRequester(); - if (node.equals(channelRequester)) - nodeSet.removeNode(node); - } - return nodeSet; - } } diff --git a/src/sneps/network/classes/setClasses/ChannelSet.java b/src/sneps/network/classes/setClasses/ChannelSet.java index 419e47ef..d2538c49 100644 --- a/src/sneps/network/classes/setClasses/ChannelSet.java +++ b/src/sneps/network/classes/setClasses/ChannelSet.java @@ -1,25 +1,43 @@ 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; public class ChannelSet implements Iterable { - private Set channels; + private Hashtable> channels; public ChannelSet() { - channels = new HashSet(); + channels = new Hashtable>(); } public void addChannel(Channel channel) { - channels.add(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(); } /*** @@ -31,7 +49,11 @@ public Iterator iterator() { */ public ChannelSet getFilteredRequestChannels(boolean processedRequest) { ChannelSet processedRequestsChannels = new ChannelSet(); - for (Channel channel : channels) { + 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); } @@ -39,6 +61,22 @@ public ChannelSet getFilteredRequestChannels(boolean processedRequest) { } public Set getChannels() { - return channels; + Set allMergedChannels = new HashSet(); + Collection> collectionOfSets = channels.values(); + for (Set set : collectionOfSets) + allMergedChannels.addAll(set); + return allMergedChannels; + } + + 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/PropositionSet.java b/src/sneps/network/classes/setClasses/PropositionSet.java index 42a20c67..b84506a6 100644 --- a/src/sneps/network/classes/setClasses/PropositionSet.java +++ b/src/sneps/network/classes/setClasses/PropositionSet.java @@ -91,7 +91,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 a2407eed..2dcd415b 100644 --- a/src/sneps/network/classes/setClasses/ReportSet.java +++ b/src/sneps/network/classes/setClasses/ReportSet.java @@ -6,20 +6,19 @@ import sneps.snip.Report; - public class ReportSet implements Iterable, Serializable { private HashSet reports; 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(); } @@ -31,6 +30,8 @@ public void clear() { reports = new HashSet(); } - + public boolean removeReport(Report report) { + return reports.remove(report); + } } diff --git a/src/sneps/snebr/Controller.java b/src/sneps/snebr/Controller.java index 01dd45c5..3b1eda82 100644 --- a/src/sneps/snebr/Controller.java +++ b/src/sneps/snebr/Controller.java @@ -23,651 +23,730 @@ import java.util.*; public class Controller { - private static String currContext = "default"; - private static ContextSet contextSet = new ContextSet(currContext); - private static ArrayList minimalNoGoods = new ArrayList<>(); - private static String conflictingContext = null; - private static PropositionSet conflictingHyps; - private static boolean automaticBR = false; - - public static boolean isAutomaticBR() { - return automaticBR; - } - - public static void setAutomaticBR(boolean automaticBR) { - Controller.automaticBR = automaticBR; - } - - /** - * Creates a new Context given its name and adds it to SNeBR's ContextSet. - * - * @param contextName the name of the Context to be created - * @return the newly Created Context object - * @throws DuplicateContextNameException If a context with the same name exists in SNeBR's ContextSet - */ - public static Context createContext(String contextName) throws DuplicateContextNameException{ - if (contextSet.getContext(contextName) != null) - throw new DuplicateContextNameException(contextName); - - Context c = new Context(contextName); - return contextSet.add(c); - } - - /** - * Creates a new empty Context - * - * @return new Context object - */ - public static Context createContext() { - return new Context(); - } - - - /** - * Creates a new dummy Context - * - * @return new Context object - */ - public static Context createDummyContext(String contextName, PropositionSet hyps) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - return new Context(contextName, hyps); - } - - /** - * Clears the global data strctures of SNeBR - */ - public static void clearSNeBR() { - contextSet.clear(); - minimalNoGoods.clear(); - currContext = "default"; - contextSet.add(new Context(currContext)); - } - - /** - * Removes a context from SNeBR's ContextSet. - * - * @param contextName name of the context desired to be removed - * @return true if a context with this name exists, false otherwise - */ - public static boolean removeContext(String contextName) { - Context c = contextSet.getContext(contextName); - if (c == null) - return false; - - boolean bool = c.removeName(contextName); - return contextSet.remove(contextName) && bool; - } - - /** - * Creates a new Context given its name and a set of hyps, and adds it to SNeBR's ContextSet. - * - * @param contextName name of the Context to be created - * @param hyps the set of hyps to be asserted in this Context - * @return the created Context - * @throws DuplicateContextNameException if a Context with this name exists in SNeBr's ContextSet - */ - public static Context createContext(String contextName, PropositionSet hyps) throws DuplicateContextNameException, ContradictionFoundException, NotAPropositionNodeException, NodeNotFoundInNetworkException, ContextNameDoesntExistException, DuplicatePropositionException, NodeNotFoundInPropSetException { - if (contextSet.getContext(contextName) != null) { - throw new DuplicateContextNameException(contextName); - } - - Context newContext = new Context(contextName); - contextSet.add(newContext); - - return addPropsToContext(contextName, hyps); - } - - /** - * Asserts a hyp in an existing Context - * - * @param contextName the name of the context to assert the hyp in - * @param hyp the hyp to be asserted - * @return a new Context object containing the old Context with the hyp asserted in it - * @throws ContextNameDoesntExistException if no Context with this name exists in SNeBr's ContextSet - * @throws DuplicatePropositionException if the hyp to be asserted in the Context is already asserted - * @throws NodeNotFoundInNetworkException - */ - public static Context addPropToContext(String contextName, int hyp) throws ContextNameDoesntExistException, NotAPropositionNodeException, DuplicatePropositionException, NodeNotFoundInNetworkException, ContradictionFoundException { - Context oldContext = contextSet.getContext(contextName); - - if (oldContext == null) - throw new ContextNameDoesntExistException(contextName); - - oldContext.removeName(contextName); - - Context temp = new Context(contextName, new PropositionSet(PropositionSet.getPropsSafely(oldContext.getHypothesisSet()))); - - ArrayList contradictions = checkForContradiction((PropositionNode) Network.getNodeById(hyp), temp, false); - - if (contradictions != null) { - conflictingContext = contextName; - conflictingHyps = new PropositionSet(new int[] {hyp}); - throw new ContradictionFoundException(contradictions); - } - - PropositionNode node = (PropositionNode) Network.getNodeById(hyp); - node.setHyp(true); - PropositionSet hypSet = oldContext.getHypothesisSet().add(hyp); - - Context newContext = new Context(contextName, hypSet); - - return contextSet.add(newContext); - } - - /** - * Asserts a set of hyps in an existing Context - * - * @param contextName the name of the context to assert the hyp in - * @param hyps the set of hyps to be asserted - * @return a new Context object containing the old Context with the set of hyps asserted in it - * @throws ContextNameDoesntExistException if no Context with this name exists in SNeBr's ContextSet - * @throws NodeNotFoundInNetworkException - * @throws CustomException - */ - public static Context addPropsToContext(String contextName, PropositionSet hyps) throws ContextNameDoesntExistException, NotAPropositionNodeException, NodeNotFoundInNetworkException, ContradictionFoundException, DuplicatePropositionException, NodeNotFoundInPropSetException { - Context oldContext = contextSet.getContext(contextName); - - if (oldContext == null) - throw new ContextNameDoesntExistException(contextName); - - oldContext.removeName(contextName); - Context temp = new Context(contextName, new PropositionSet(PropositionSet.getPropsSafely(oldContext.getHypothesisSet()))); - ArrayList contradictions; - int[] hypsArr = PropositionSet.getPropsSafely(hyps); - for (int i = 0; i < hypsArr.length; i++) { - checkForContradiction((PropositionNode) Network.getNodeById(hypsArr[i]), temp, true); - temp = new Context(contextName, temp.getHypothesisSet().add(hypsArr[i])); - } - - temp = new Context(contextName, temp.getHypothesisSet().remove(hypsArr[hypsArr.length - 1])); - contradictions = checkForContradiction((PropositionNode) Network.getNodeById(hypsArr[hypsArr.length - 1]), temp, false); - - if (contradictions != null) { - conflictingContext = contextName; - conflictingHyps = hyps; - throw new ContradictionFoundException(contradictions); - } - - hypsArr = PropositionSet.getPropsSafely(hyps); - for (int i = 0; i < hypsArr.length; i++) { - PropositionNode node = (PropositionNode) Network.getNodeById(hypsArr[i]); - node.setHyp(true); + private static String currContext = "default"; + private static ContextSet contextSet = new ContextSet(currContext); + private static ArrayList minimalNoGoods = new ArrayList<>(); + private static String conflictingContext = null; + private static PropositionSet conflictingHyps; + private static boolean automaticBR = false; + + public static boolean isAutomaticBR() { + return automaticBR; + } + + public static void setAutomaticBR(boolean automaticBR) { + Controller.automaticBR = automaticBR; + } + + /** + * Creates a new Context given its name and adds it to SNeBR's ContextSet. + * + * @param contextName the name of the Context to be created + * @return the newly Created Context object + * @throws DuplicateContextNameException If a context with the same name exists + * in SNeBR's ContextSet + */ + public static Context createContext(String contextName) throws DuplicateContextNameException { + if (contextSet.getContext(contextName) != null) + throw new DuplicateContextNameException(contextName); + + Context c = new Context(contextName); + return contextSet.add(c); + } + + /** + * Creates a new empty Context + * + * @return new Context object + */ + public static Context createContext() { + return new Context(); + } + + /** + * Creates a new dummy Context + * + * @return new Context object + */ + public static Context createDummyContext(String contextName, PropositionSet hyps) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + return new Context(contextName, hyps); + } + + /** + * Clears the global data strctures of SNeBR + */ + public static void clearSNeBR() { + contextSet.clear(); + minimalNoGoods.clear(); + currContext = "default"; + contextSet.add(new Context(currContext)); + } + + /** + * Removes a context from SNeBR's ContextSet. + * + * @param contextName name of the context desired to be removed + * @return true if a context with this name exists, + * false otherwise + */ + public static boolean removeContext(String contextName) { + Context c = contextSet.getContext(contextName); + if (c == null) + return false; + + boolean bool = c.removeName(contextName); + return contextSet.remove(contextName) && bool; + } + + /** + * Creates a new Context given its name and a set of hyps, and adds it to + * SNeBR's ContextSet. + * + * @param contextName name of the Context to be created + * @param hyps the set of hyps to be asserted in this Context + * @return the created Context + * @throws DuplicateContextNameException if a Context with this name exists in + * SNeBr's ContextSet + */ + public static Context createContext(String contextName, PropositionSet hyps) throws DuplicateContextNameException, + ContradictionFoundException, NotAPropositionNodeException, NodeNotFoundInNetworkException, + ContextNameDoesntExistException, DuplicatePropositionException, NodeNotFoundInPropSetException { + if (contextSet.getContext(contextName) != null) { + throw new DuplicateContextNameException(contextName); } - temp = new Context(contextName, oldContext.getHypothesisSet().union(hyps)); - contextSet.add(temp); - return temp; - } - - public static ArrayList getMinimalNoGoods() { - return minimalNoGoods; - } - - /** - * Asserts a hyp in the current Context - * - * @param hyp the hyp to be asserted in the current Context - * @return a new Context object containing the asserted hyp - * @throws ContextNameDoesntExistException if no Context with this name exists in SNeBr's ContextSet - * @throws DuplicatePropositionException if the hyp to be asserted in the Context is already asserted - * @throws NodeNotFoundInNetworkException - */ - public static Context addPropToCurrentContext(int hyp) throws ContextNameDoesntExistException, DuplicatePropositionException, NotAPropositionNodeException, NodeNotFoundInNetworkException, ContradictionFoundException { - return addPropToContext(currContext, hyp); - } - - public static String getCurrentContextName() { - return currContext; - } - - /** - * Asserts a set of hyps in the current Context - * - * @param hyps the set of hyps to be asserted - * @return a new Context object containing the old Context with the set of hyps asserted in it - * @throws ContextNameDoesntExistException if no Context with this name exists in SNeBr's ContextSet - * @throws NodeNotFoundInNetworkException - * @throws CustomException - */ - public static Context addPropsToCurrentContext(PropositionSet hyps) throws ContextNameDoesntExistException, NotAPropositionNodeException, NodeNotFoundInNetworkException, ContradictionFoundException, DuplicatePropositionException, NodeNotFoundInPropSetException { - return addPropsToContext(currContext, hyps); - } - - /** - * Sets the current context to some Context by the Context's name - * - * @param contextName the name of the Context to be set as the current Context - * @return Context object containing the current Context - */ - public static Context setCurrentContext(String contextName) throws ContradictionFoundException, ContextNameDoesntExistException { - Context context = contextSet.getContext(contextName); - if (context == null) { - throw new ContextNameDoesntExistException(contextName); - } - currContext = contextName; - - return context; - } - - /** - * Returns the current Context object - * - * @return Context object of the current Context - */ - public static Context getCurrentContext() { - return contextSet.getContext(currContext); - } - - /** - * Return a string representation of a context - * @param contextName - * @return A string representing the context. - */ - public static String contextToString(String contextName) { - return "Context: " + contextName + "\n" + contextSet.getContext(contextName).getHypothesisSet().toString(); - } - - /** - * Returns all the propositions that are asserted in the context, either directly (hyps) or indirectly (derived). - * @return A PropositionSet containing the asserted propositions. - */ - public static PropositionSet allAsserted() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - PropositionSet p = new PropositionSet(); - boolean first = true; - for (Context c : contextSet.getContexts()) { - if (first) { - p = new PropositionSet(PropositionSet.getPropsSafely(c.getHypothesisSet())); - first = false; - } else - p = p.union(c.getHypothesisSet()); - } - return p; - } - - /** - * Creates all possible combinations of the supports of two contradictory propositions. - * @return An ArrayList of type PropositionSet containing all the combinations. - */ - public static ArrayList combine(Collection negatingPropSupports, Collection negatedPropSupports) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - ArrayList output = new ArrayList<>(); - - for (PropositionSet negatingPropSupp : negatingPropSupports) { - for (PropositionSet negatedPropSupp : negatedPropSupports) { - output.add(negatingPropSupp.union(negatedPropSupp)); - } - } - return output; - - - } - - /** - * Given an ArrayList of BitSets of propositions it returns an ArrayList of NodeSets of PropositionNodes. - * @return An ArrayList of type NodeSet containing the PropositionNodes of each corresponding BitSet. - */ - public static ArrayList generateNodeSetsFromBitSets(ArrayList conflictingHypsCollection) throws NodeNotFoundInNetworkException, DuplicatePropositionException, NotAPropositionNodeException { - ArrayList nodeSetList = new ArrayList<>(); - for (BitSet b : conflictingHypsCollection) { - NodeSet propSet = new NodeSet(); - for (int i = b.nextSetBit(0); i != -1; i = b.nextSetBit(i + 1)) - propSet.addNode(Network.getNodeById(i)); - nodeSetList.add(propSet); - } - return nodeSetList; - } - - /** - * Checks if a negation exists given min, max, and arg up or down cables of some node. - * This is a helper method for getConflictingHypsCollectionForNegating and getConflictingHypsCollectionForNegated. - * @param min min cable. - * @param max max cable. - * @param arg arg cable. - * @return true if negation exists, false otherwise. - */ - public static boolean negationExists(Cable min, Cable max, Cable arg) { - if ( - min != null && max != null && arg != null && - min.getNodeSet().size() == 1 && min.getNodeSet().getNode(0).getIdentifier().equals("0") && - max.getNodeSet().size() == 1 && max.getNodeSet().getNode(0).getIdentifier().equals("0") && - arg.getNodeSet().size() >= 1 - ) - return true; - else - return false; - } - - /** - * Given a BitSet representation of some context's hyps this method returns all the minimalNoGoods - * that are subsets of this context. - * @param contextBitset The context's hyps BitSet representation. - * @return - */ - public static ArrayList getConflictingHypsFromMinimalNoGoods(BitSet contextBitset) { - ArrayList conflictingHypsInContext = new ArrayList<>(); - for (BitSet bitSet : minimalNoGoods) { - BitSet temp = (BitSet) bitSet.clone(); - temp.and(contextBitset); - if (temp.equals(bitSet)) - conflictingHypsInContext.add(temp); - } - if (conflictingHypsInContext.size() > 0) - return conflictingHypsInContext; - return null; - } - - /** - * Genrate an ArrayList of BitSets from an ArrayList of PropositionSets. - * This is a helper method for getConflictingHypsCollectionForNegating and getConflictingHypsCollectionForNegated. - * @param propositionSetCollection ArrayList of PropositionSets. - * @return ArrayList of BitSets, where each BitSet corresponds to a PropositionSet in propositionSetCollection. - * @throws NotAPropositionNodeException - * @throws NodeNotFoundInNetworkException - */ - public static ArrayList generateBitSetsFromPropositionSets(Collection propositionSetCollection) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - ArrayList bitSets = new ArrayList<>(); - for (PropositionSet propSet : propositionSetCollection) { - int[] props = PropositionSet.getPropsSafely(propSet); - BitSet temp = new BitSet(); - for (int i = 0; i < props.length; i++) - temp.set(props[i]); - bitSets.add(temp); - } - return bitSets; - - } - - /** - * Given a negating node, it's arg downcable, and a BitSet representation of some context's hyps; - * it first updates the minimalNoGoods with the supports of the negating proposition node and the supports of the negated proposition node. - * @param arg Downcable having the negated node. - * @param tempContextBitset a BitSet representation of some context's hyps with a newly asserted hyp added to it to test for contradiction. - * @return An ArrayList of NodeSets, each having a combination of the supports, asserted in some context, of the two conflicting propsositions. - * If not a single such combination exists null is returned. - * @throws NotAPropositionNodeException - * @throws NodeNotFoundInNetworkException - * @throws DuplicatePropositionException - */ - public static ArrayList getConflictingHypsCollectionForNegating(PropositionNode negatingNode, DownCable arg, BitSet tempContextBitset) throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { - Collection negatingPropSupports = negatingNode.getAssumptionBasedSupport().values(); - Collection combinedContradictorySupports = new ArrayList<>(); - - for (Node dominatedNode : arg.getNodeSet()) { - Collection negatedNodeSupports = ((PropositionNode) dominatedNode).getAssumptionBasedSupport().values(); - combinedContradictorySupports.addAll(combine(negatingPropSupports, negatedNodeSupports)); - } - - /* add to minimalNoGoods */ - Collection combinedContradictorySupportsBitSetCollection = generateBitSetsFromPropositionSets(combinedContradictorySupports); + + Context newContext = new Context(contextName); + contextSet.add(newContext); + + return addPropsToContext(contextName, hyps); + } + + /** + * Asserts a hyp in an existing Context + * + * @param contextName the name of the context to assert the hyp in + * @param hyp the hyp to be asserted + * @return a new Context object containing the old Context with the hyp asserted + * in it + * @throws ContextNameDoesntExistException if no Context with this name exists + * in SNeBr's ContextSet + * @throws DuplicatePropositionException if the hyp to be asserted in the + * Context is already asserted + * @throws NodeNotFoundInNetworkException + */ + public static Context addPropToContext(String contextName, int hyp) + throws ContextNameDoesntExistException, NotAPropositionNodeException, DuplicatePropositionException, + NodeNotFoundInNetworkException, ContradictionFoundException { + Context oldContext = contextSet.getContext(contextName); + + if (oldContext == null) + throw new ContextNameDoesntExistException(contextName); + + oldContext.removeName(contextName); + + Context temp = new Context(contextName, + new PropositionSet(PropositionSet.getPropsSafely(oldContext.getHypothesisSet()))); + + ArrayList contradictions = checkForContradiction((PropositionNode) Network.getNodeById(hyp), temp, + false); + + if (contradictions != null) { + conflictingContext = contextName; + conflictingHyps = new PropositionSet(new int[] { hyp }); + throw new ContradictionFoundException(contradictions); + } + + PropositionNode node = (PropositionNode) Network.getNodeById(hyp); + node.setHyp(true); + PropositionSet hypSet = oldContext.getHypothesisSet().add(hyp); + + Context newContext = new Context(contextName, hypSet); + + return contextSet.add(newContext); + } + + /** + * Asserts a set of hyps in an existing Context + * + * @param contextName the name of the context to assert the hyp in + * @param hyps the set of hyps to be asserted + * @return a new Context object containing the old Context with the set of hyps + * asserted in it + * @throws ContextNameDoesntExistException if no Context with this name exists + * in SNeBr's ContextSet + * @throws NodeNotFoundInNetworkException + * @throws CustomException + */ + public static Context addPropsToContext(String contextName, PropositionSet hyps) + throws ContextNameDoesntExistException, NotAPropositionNodeException, NodeNotFoundInNetworkException, + ContradictionFoundException, DuplicatePropositionException, NodeNotFoundInPropSetException { + Context oldContext = contextSet.getContext(contextName); + + if (oldContext == null) + throw new ContextNameDoesntExistException(contextName); + + oldContext.removeName(contextName); + Context temp = new Context(contextName, + new PropositionSet(PropositionSet.getPropsSafely(oldContext.getHypothesisSet()))); + ArrayList contradictions; + int[] hypsArr = PropositionSet.getPropsSafely(hyps); + for (int i = 0; i < hypsArr.length; i++) { + checkForContradiction((PropositionNode) Network.getNodeById(hypsArr[i]), temp, true); + temp = new Context(contextName, temp.getHypothesisSet().add(hypsArr[i])); + } + + temp = new Context(contextName, temp.getHypothesisSet().remove(hypsArr[hypsArr.length - 1])); + contradictions = checkForContradiction((PropositionNode) Network.getNodeById(hypsArr[hypsArr.length - 1]), temp, + false); + + if (contradictions != null) { + conflictingContext = contextName; + conflictingHyps = hyps; + throw new ContradictionFoundException(contradictions); + } + + hypsArr = PropositionSet.getPropsSafely(hyps); + for (int i = 0; i < hypsArr.length; i++) { + PropositionNode node = (PropositionNode) Network.getNodeById(hypsArr[i]); + node.setHyp(true); + } + temp = new Context(contextName, oldContext.getHypothesisSet().union(hyps)); + contextSet.add(temp); + return temp; + } + + public static ArrayList getMinimalNoGoods() { + return minimalNoGoods; + } + + /** + * Asserts a hyp in the current Context + * + * @param hyp the hyp to be asserted in the current Context + * @return a new Context object containing the asserted hyp + * @throws ContextNameDoesntExistException if no Context with this name exists + * in SNeBr's ContextSet + * @throws DuplicatePropositionException if the hyp to be asserted in the + * Context is already asserted + * @throws NodeNotFoundInNetworkException + */ + public static Context addPropToCurrentContext(int hyp) + throws ContextNameDoesntExistException, DuplicatePropositionException, NotAPropositionNodeException, + NodeNotFoundInNetworkException, ContradictionFoundException { + return addPropToContext(currContext, hyp); + } + + public static String getCurrentContextName() { + return currContext; + } + + /** + * Asserts a set of hyps in the current Context + * + * @param hyps the set of hyps to be asserted + * @return a new Context object containing the old Context with the set of hyps + * asserted in it + * @throws ContextNameDoesntExistException if no Context with this name exists + * in SNeBr's ContextSet + * @throws NodeNotFoundInNetworkException + * @throws CustomException + */ + public static Context addPropsToCurrentContext(PropositionSet hyps) + throws ContextNameDoesntExistException, NotAPropositionNodeException, NodeNotFoundInNetworkException, + ContradictionFoundException, DuplicatePropositionException, NodeNotFoundInPropSetException { + return addPropsToContext(currContext, hyps); + } + + /** + * Sets the current context to some Context by the Context's name + * + * @param contextName the name of the Context to be set as the current Context + * @return Context object containing the current Context + */ + public static Context setCurrentContext(String contextName) + throws ContradictionFoundException, ContextNameDoesntExistException { + Context context = contextSet.getContext(contextName); + if (context == null) { + throw new ContextNameDoesntExistException(contextName); + } + currContext = contextName; + + return context; + } + + /** + * Returns the current Context object + * + * @return Context object of the current Context + */ + public static Context getCurrentContext() { + return contextSet.getContext(currContext); + } + + /** + * Return a string representation of a context + * + * @param contextName + * @return A string representing the context. + */ + public static String contextToString(String contextName) { + return "Context: " + contextName + "\n" + contextSet.getContext(contextName).getHypothesisSet().toString(); + } + + /** + * Returns all the propositions that are asserted in the context, either + * directly (hyps) or indirectly (derived). + * + * @return A PropositionSet containing the asserted propositions. + */ + public static PropositionSet allAsserted() throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + PropositionSet p = new PropositionSet(); + boolean first = true; + for (Context c : contextSet.getContexts()) { + if (first) { + p = new PropositionSet(PropositionSet.getPropsSafely(c.getHypothesisSet())); + first = false; + } else + p = p.union(c.getHypothesisSet()); + } + return p; + } + + /** + * Creates all possible combinations of the supports of two contradictory + * propositions. + * + * @return An ArrayList of type PropositionSet containing all the combinations. + */ + public static ArrayList combine(Collection negatingPropSupports, + Collection negatedPropSupports) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + ArrayList output = new ArrayList<>(); + + for (PropositionSet negatingPropSupp : negatingPropSupports) { + for (PropositionSet negatedPropSupp : negatedPropSupports) { + output.add(negatingPropSupp.union(negatedPropSupp)); + } + } + return output; + + } + + /** + * Given an ArrayList of BitSets of propositions it returns an ArrayList of + * NodeSets of PropositionNodes. + * + * @return An ArrayList of type NodeSet containing the PropositionNodes of each + * corresponding BitSet. + */ + public static ArrayList generateNodeSetsFromBitSets(ArrayList conflictingHypsCollection) + throws NodeNotFoundInNetworkException, DuplicatePropositionException, NotAPropositionNodeException { + ArrayList nodeSetList = new ArrayList<>(); + for (BitSet b : conflictingHypsCollection) { + NodeSet propSet = new NodeSet(); + for (int i = b.nextSetBit(0); i != -1; i = b.nextSetBit(i + 1)) + propSet.addNode(Network.getNodeById(i)); + nodeSetList.add(propSet); + } + return nodeSetList; + } + + /** + * Checks if a negation exists given min, max, and arg up or down cables of some + * node. This is a helper method for getConflictingHypsCollectionForNegating and + * getConflictingHypsCollectionForNegated. + * + * @param min min cable. + * @param max max cable. + * @param arg arg cable. + * @return true if negation exists, false otherwise. + */ + public static boolean negationExists(Cable min, Cable max, Cable arg) { + if (min != null && max != null && arg != null && min.getNodeSet().size() == 1 + && min.getNodeSet().getNode(0).getIdentifier().equals("0") && max.getNodeSet().size() == 1 + && max.getNodeSet().getNode(0).getIdentifier().equals("0") && arg.getNodeSet().size() >= 1) + return true; + else + return false; + } + + /** + * Given a BitSet representation of some context's hyps this method returns all + * the minimalNoGoods that are subsets of this context. + * + * @param contextBitset The context's hyps BitSet representation. + * @return + */ + public static ArrayList getConflictingHypsFromMinimalNoGoods(BitSet contextBitset) { + ArrayList conflictingHypsInContext = new ArrayList<>(); + for (BitSet bitSet : minimalNoGoods) { + BitSet temp = (BitSet) bitSet.clone(); + temp.and(contextBitset); + if (temp.equals(bitSet)) + conflictingHypsInContext.add(temp); + } + if (conflictingHypsInContext.size() > 0) + return conflictingHypsInContext; + return null; + } + + /** + * Genrate an ArrayList of BitSets from an ArrayList of PropositionSets. This is + * a helper method for getConflictingHypsCollectionForNegating and + * getConflictingHypsCollectionForNegated. + * + * @param propositionSetCollection ArrayList of PropositionSets. + * @return ArrayList of BitSets, where each BitSet corresponds to a + * PropositionSet in propositionSetCollection. + * @throws NotAPropositionNodeException + * @throws NodeNotFoundInNetworkException + */ + public static ArrayList generateBitSetsFromPropositionSets( + Collection propositionSetCollection) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + ArrayList bitSets = new ArrayList<>(); + for (PropositionSet propSet : propositionSetCollection) { + int[] props = PropositionSet.getPropsSafely(propSet); + BitSet temp = new BitSet(); + for (int i = 0; i < props.length; i++) + temp.set(props[i]); + bitSets.add(temp); + } + return bitSets; + + } + + /** + * Given a negating node, it's arg downcable, and a BitSet representation of + * some context's hyps; it first updates the minimalNoGoods with the supports of + * the negating proposition node and the supports of the negated proposition + * node. + * + * @param arg Downcable having the negated node. + * @param tempContextBitset a BitSet representation of some context's hyps with + * a newly asserted hyp added to it to test for + * contradiction. + * @return An ArrayList of NodeSets, each having a combination of the supports, + * asserted in some context, of the two conflicting propsositions. If + * not a single such combination exists null is returned. + * @throws NotAPropositionNodeException + * @throws NodeNotFoundInNetworkException + * @throws DuplicatePropositionException + */ + public static ArrayList getConflictingHypsCollectionForNegating(PropositionNode negatingNode, + DownCable arg, BitSet tempContextBitset) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { + Collection negatingPropSupports = negatingNode.getAssumptionBasedSupport().values(); + Collection combinedContradictorySupports = new ArrayList<>(); + + for (Node dominatedNode : arg.getNodeSet()) { + Collection negatedNodeSupports = ((PropositionNode) dominatedNode) + .getAssumptionBasedSupport().values(); + combinedContradictorySupports.addAll(combine(negatingPropSupports, negatedNodeSupports)); + } + + /* add to minimalNoGoods */ + Collection combinedContradictorySupportsBitSetCollection = generateBitSetsFromPropositionSets( + combinedContradictorySupports); // to avoid ConcurrentModificationException - ArrayList minimalNoGoodsClone = (ArrayList) minimalNoGoods.clone(); - - for (BitSet bitSet : combinedContradictorySupportsBitSetCollection) { - boolean intersects = false; - for (BitSet bitSet1 : minimalNoGoodsClone) { - BitSet temp = (BitSet) bitSet.clone(); - temp.and(bitSet1); - if (temp.equals(bitSet)) { - int index = minimalNoGoods.indexOf(bitSet1); - if (intersects) - minimalNoGoods.remove(index); - else { - minimalNoGoods.remove(index); - minimalNoGoods.add(index, temp); - intersects = true; - } - - } else if (temp.equals(bitSet1)) { - intersects = true; - break; - } - } - if (!intersects) - minimalNoGoods.add(bitSet); - } - - ArrayList conlifctingHypsInContextCollection = getConflictingHypsFromMinimalNoGoods(tempContextBitset); - if (conlifctingHypsInContextCollection != null) - return generateNodeSetsFromBitSets(conlifctingHypsInContextCollection); - else - return null; - - } - - public static ArrayList getConflictingHypsCollectionForNegated(PropositionNode negatedNode, UpCable arg, BitSet tempContextBitset) throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { - PropositionNode negatingNode = (PropositionNode) arg.getNodeSet().getNode(0); - Collection negatedPropSupports = negatedNode.getAssumptionBasedSupport().values(); - Collection negatingPropSupports = negatingNode.getAssumptionBasedSupport().values(); - - Collection combinedContradictorySupports = combine(negatingPropSupports, negatedPropSupports); - - /* add to minimalNoGoods */ - Collection combinedContradictorySupportsBitSetCollection = generateBitSetsFromPropositionSets(combinedContradictorySupports); + ArrayList minimalNoGoodsClone = (ArrayList) minimalNoGoods.clone(); + + for (BitSet bitSet : combinedContradictorySupportsBitSetCollection) { + boolean intersects = false; + for (BitSet bitSet1 : minimalNoGoodsClone) { + BitSet temp = (BitSet) bitSet.clone(); + temp.and(bitSet1); + if (temp.equals(bitSet)) { + int index = minimalNoGoods.indexOf(bitSet1); + if (intersects) + minimalNoGoods.remove(index); + else { + minimalNoGoods.remove(index); + minimalNoGoods.add(index, temp); + intersects = true; + } + + } else if (temp.equals(bitSet1)) { + intersects = true; + break; + } + } + if (!intersects) + minimalNoGoods.add(bitSet); + } + + ArrayList conlifctingHypsInContextCollection = getConflictingHypsFromMinimalNoGoods(tempContextBitset); + if (conlifctingHypsInContextCollection != null) + return generateNodeSetsFromBitSets(conlifctingHypsInContextCollection); + else + return null; + + } + + public static ArrayList getConflictingHypsCollectionForNegated(PropositionNode negatedNode, UpCable arg, + BitSet tempContextBitset) + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { + PropositionNode negatingNode = (PropositionNode) arg.getNodeSet().getNode(0); + Collection negatedPropSupports = negatedNode.getAssumptionBasedSupport().values(); + Collection negatingPropSupports = negatingNode.getAssumptionBasedSupport().values(); + + Collection combinedContradictorySupports = combine(negatingPropSupports, negatedPropSupports); + + /* add to minimalNoGoods */ + Collection combinedContradictorySupportsBitSetCollection = generateBitSetsFromPropositionSets( + combinedContradictorySupports); // to avoid ConcurrentModificationException - ArrayList minimalNoGoodsClone = (ArrayList) minimalNoGoods.clone(); - - for (BitSet bitSet : combinedContradictorySupportsBitSetCollection) { - boolean intersects = false; - for (BitSet bitSet1 : minimalNoGoodsClone) { - BitSet temp = (BitSet) bitSet.clone(); - temp.and(bitSet1); - if (temp.equals(bitSet)) { - int index = minimalNoGoods.indexOf(bitSet1); - if (intersects) - minimalNoGoods.remove(index); - else { - minimalNoGoods.remove(index); - minimalNoGoods.add(index, temp); - intersects = true; - } - - } - else if (temp.equals(bitSet1)) { - intersects = true; - break; - } - } - if (!intersects) - minimalNoGoods.add(bitSet); - } - - ArrayList conlifctingHypsInContextCollection = getConflictingHypsFromMinimalNoGoods(tempContextBitset); - if (conlifctingHypsInContextCollection != null) - return generateNodeSetsFromBitSets(conlifctingHypsInContextCollection); - else - return null; - } - - /** - * Checks if some node's addition to a context c introduces a contradiction. - * @param node - * @param c - * @param skipCache This is a boolean flag to allow skipping the cache checking stage. It is useful for testing purposes only, for now. - * @return - * @throws NodeNotFoundInNetworkException - * @throws DuplicatePropositionException - * @throws NotAPropositionNodeException - */ - public static ArrayList checkForContradiction(PropositionNode node, Context c, boolean skipCache) throws NodeNotFoundInNetworkException, DuplicatePropositionException, NotAPropositionNodeException { - - if (c.getNames().contains(conflictingContext)) { - checkForContradictionCore(node, c, true); - return checkForContradictionCore(node, c, false); - } - - return checkForContradictionCore(node, c, skipCache); - } - - public static ArrayList checkForContradictionCore(PropositionNode node, Context c, boolean skipCache) throws NodeNotFoundInNetworkException, DuplicatePropositionException, NotAPropositionNodeException { - - // add prop supports to a clone of the context's bitset - BitSet tempContextBitset = (BitSet) c.getHypsBitset().clone(); - - Collection propsCollection = node.getAssumptionBasedSupport().values(); - - for (PropositionSet propSet : propsCollection) { - int[] props = PropositionSet.getPropsSafely(propSet); - for (int i = 0; i < props.length; i++) - tempContextBitset.set(props[i]); - } - - if (!skipCache) { - - /* First check in minimalNoGoods */ - - ArrayList conflictingHypsInContext = getConflictingHypsFromMinimalNoGoods(tempContextBitset); - - if (conflictingHypsInContext != null) - return generateNodeSetsFromBitSets(conflictingHypsInContext); - } + ArrayList minimalNoGoodsClone = (ArrayList) minimalNoGoods.clone(); + + for (BitSet bitSet : combinedContradictorySupportsBitSetCollection) { + boolean intersects = false; + for (BitSet bitSet1 : minimalNoGoodsClone) { + BitSet temp = (BitSet) bitSet.clone(); + temp.and(bitSet1); + if (temp.equals(bitSet)) { + int index = minimalNoGoods.indexOf(bitSet1); + if (intersects) + minimalNoGoods.remove(index); + else { + minimalNoGoods.remove(index); + minimalNoGoods.add(index, temp); + intersects = true; + } + + } else if (temp.equals(bitSet1)) { + intersects = true; + break; + } + } + if (!intersects) + minimalNoGoods.add(bitSet); + } + + ArrayList conlifctingHypsInContextCollection = getConflictingHypsFromMinimalNoGoods(tempContextBitset); + if (conlifctingHypsInContextCollection != null) + return generateNodeSetsFromBitSets(conlifctingHypsInContextCollection); + else + return null; + } + + /** + * Checks if some node's addition to a context c introduces a contradiction. + * + * @param node + * @param c + * @param skipCache This is a boolean flag to allow skipping the cache checking + * stage. It is useful for testing purposes only, for now. + * @return + * @throws NodeNotFoundInNetworkException + * @throws DuplicatePropositionException + * @throws NotAPropositionNodeException + */ + public static ArrayList checkForContradiction(PropositionNode node, Context c, boolean skipCache) + throws NodeNotFoundInNetworkException, DuplicatePropositionException, NotAPropositionNodeException { + + if (c.getNames().contains(conflictingContext)) { + checkForContradictionCore(node, c, true); + return checkForContradictionCore(node, c, false); + } + + return checkForContradictionCore(node, c, skipCache); + } + + public static ArrayList checkForContradictionCore(PropositionNode node, Context c, boolean skipCache) + throws NodeNotFoundInNetworkException, DuplicatePropositionException, NotAPropositionNodeException { + + // add prop supports to a clone of the context's bitset + BitSet tempContextBitset = (BitSet) c.getHypsBitset().clone(); + + Collection propsCollection = node.getAssumptionBasedSupport().values(); + + for (PropositionSet propSet : propsCollection) { + int[] props = PropositionSet.getPropsSafely(propSet); + for (int i = 0; i < props.length; i++) + tempContextBitset.set(props[i]); + } + + if (!skipCache) { + + /* First check in minimalNoGoods */ + + ArrayList conflictingHypsInContext = getConflictingHypsFromMinimalNoGoods(tempContextBitset); + + if (conflictingHypsInContext != null) + return generateNodeSetsFromBitSets(conflictingHypsInContext); + } // else check in down cables and up cables - /* check in downcables */ - if (node.getTerm() instanceof Molecular) { - Hashtable downCables = ((Molecular) node.getTerm()).getDownCableSet().getDownCables(); - DownCable min = downCables.get("min"); - DownCable max = downCables.get("max"); - DownCable arg = downCables.get("arg"); - - if (negationExists(min, max, arg)) { - ArrayList conflictingHypsInContextFromDownCables = getConflictingHypsCollectionForNegating(node, arg, tempContextBitset); - if (conflictingHypsInContextFromDownCables != null) - return conflictingHypsInContextFromDownCables; - } - } - - /* check in upcables */ - UpCableSet up = node.getUpCableSet(); - - if (up.getUpCables().size() > 0) { - UpCable min = up.getUpCable("min"); - UpCable max = up.getUpCable("max"); - UpCable arg = up.getUpCable("arg"); - if (negationExists(min, max, arg)) { - ArrayList conflictingHypsInContextFromUpCables = getConflictingHypsCollectionForNegated(node, arg, tempContextBitset); - if (conflictingHypsInContextFromUpCables != null) - return conflictingHypsInContextFromUpCables; - } - - } - - return null; - } - - /** - * Handles the last found contradiction in the system. - * @param hypsToBeRemoved A PropositionSet having all the hyps to be removed - * from the contraictory context to resolve the contradiction. - * @param ignore Boolean flag to ignore the contradiciton and adds the contradictory proposition anyway. - * @throws NodeNotFoundInNetworkException - * @throws NotAPropositionNodeException - * @throws ContextNameDoesntExistException - * @throws NodeNotFoundInPropSetException - * @throws DuplicatePropositionException - */ - public static void handleContradiction(PropositionSet hypsToBeRemoved, boolean ignore) throws NodeNotFoundInNetworkException, NotAPropositionNodeException, ContextNameDoesntExistException, NodeNotFoundInPropSetException, DuplicatePropositionException { - if (ignore) { - Context inconsistentContext = new Context(conflictingContext, contextSet.getContext(conflictingContext).getHypothesisSet().union(conflictingHyps)); - contextSet.add(inconsistentContext); - return; - } - else { - - if (hypsToBeRemoved != null) { - removeHypsFromContext(hypsToBeRemoved, conflictingContext); - PropositionSet modifiedHyps = conflictingHyps.removeProps(hypsToBeRemoved); - Context resolvedContext = new Context(conflictingContext, contextSet.getContext(conflictingContext).getHypothesisSet().union(modifiedHyps)); - contextSet.add(resolvedContext); - } - conflictingContext = null; - conflictingHyps = null; - } - - } - - /** - * removes a set of hyps from a context. - * @param hyps - * @param contextName - * @return - * @throws ContextNameDoesntExistException - * @throws NotAPropositionNodeException - * @throws NodeNotFoundInNetworkException - */ - public static Context removeHypsFromContext(PropositionSet hyps, String contextName) throws ContextNameDoesntExistException, NotAPropositionNodeException, NodeNotFoundInNetworkException{ - Context c = contextSet.getContext(contextName); - if (c == null) throw new ContextNameDoesntExistException(contextName); - PropositionSet propSet = c.getHypothesisSet().removeProps(hyps); - c = new Context(contextName, propSet); - return contextSet.add(c); - /* - c = contextSet.add(c); - Network.defineDefaults(); - if (conflictingContext != null && contextName == conflictingContext) { - PropositionNode tempProp = (PropositionNode)Network.buildBaseNode("n"+ -5000, Semantic.proposition); - if (Controller.checkForContradictionCore(tempProp, c, false) == null) - conflictingContext = null; - Network.removeNode(tempProp); - } - return c; - */ - - } - - /** - * removes a proposition fromm all contexts. This means removing all its supports from all contexts. - * @param node - * @throws NodeNotFoundInPropSetException - * @throws NotAPropositionNodeException - * @throws NodeNotFoundInNetworkException - */ - public static void removePropositionFromAllContexts(PropositionNode node) throws NodeNotFoundInPropSetException, NotAPropositionNodeException, NodeNotFoundInNetworkException { - int hyp = node.getId(); - for (String contextName: contextSet.getNames()) { - Context c = new Context(contextName, contextSet.getContext(contextName).getHypothesisSet().remove(hyp)); - contextSet.add(c); - /*c = contextSet.add(c); - Network.defineDefaults(); - if (conflictingContext != null && contextName == conflictingContext) { - PropositionNode tempProp = (PropositionNode)Network.buildBaseNode("n"+ -5000, Semantic.proposition); - if (Controller.checkForContradictionCore(tempProp, c, false) == null) - conflictingContext = null; - Network.removeNode(tempProp); - } */ - } - } - - /** - * Returns all the names of contexts available in the system. - * @return - */ - public static Set getAllNamesOfContexts() { - return contextSet.getNames(); - } - - /** - * Returns a Context given its name - * - * @param contextName the name of the Context to be returned - * @return Context object - */ - public static Context getContextByName(String contextName) { - return contextSet.getContext(contextName); - } - - - - - public static void save(String f) throws FileNotFoundException, IOException { - ObjectOutputStream cos = new ObjectOutputStream(new FileOutputStream(new File(f))); + /* check in downcables */ + if (node.getTerm() instanceof Molecular) { + Hashtable downCables = ((Molecular) node.getTerm()).getDownCableSet().getDownCables(); + DownCable min = downCables.get("min"); + DownCable max = downCables.get("max"); + DownCable arg = downCables.get("arg"); + + if (negationExists(min, max, arg)) { + ArrayList conflictingHypsInContextFromDownCables = getConflictingHypsCollectionForNegating( + node, arg, tempContextBitset); + if (conflictingHypsInContextFromDownCables != null) + return conflictingHypsInContextFromDownCables; + } + } + + /* check in upcables */ + UpCableSet up = node.getUpCableSet(); + + if (up.getUpCables().size() > 0) { + UpCable min = up.getUpCable("min"); + UpCable max = up.getUpCable("max"); + UpCable arg = up.getUpCable("arg"); + if (negationExists(min, max, arg)) { + ArrayList conflictingHypsInContextFromUpCables = getConflictingHypsCollectionForNegated(node, + arg, tempContextBitset); + if (conflictingHypsInContextFromUpCables != null) + return conflictingHypsInContextFromUpCables; + } + + } + + return null; + } + + public static boolean isNegated(PropositionNode node) { + UpCableSet up = node.getUpCableSet(); + + if (up.getUpCables().size() > 0) { + UpCable min = up.getUpCable("min"); + UpCable max = up.getUpCable("max"); + UpCable arg = up.getUpCable("arg"); + + return negationExists(min, max, arg); + } + return false; + } + + /** + * Handles the last found contradiction in the system. + * + * @param hypsToBeRemoved A PropositionSet having all the hyps to be removed + * from the contraictory context to resolve the + * contradiction. + * @param ignore Boolean flag to ignore the contradiciton and adds the + * contradictory proposition anyway. + * @throws NodeNotFoundInNetworkException + * @throws NotAPropositionNodeException + * @throws ContextNameDoesntExistException + * @throws NodeNotFoundInPropSetException + * @throws DuplicatePropositionException + */ + public static void handleContradiction(PropositionSet hypsToBeRemoved, boolean ignore) + throws NodeNotFoundInNetworkException, NotAPropositionNodeException, ContextNameDoesntExistException, + NodeNotFoundInPropSetException, DuplicatePropositionException { + if (ignore) { + Context inconsistentContext = new Context(conflictingContext, + contextSet.getContext(conflictingContext).getHypothesisSet().union(conflictingHyps)); + contextSet.add(inconsistentContext); + return; + } else { + + if (hypsToBeRemoved != null) { + removeHypsFromContext(hypsToBeRemoved, conflictingContext); + PropositionSet modifiedHyps = conflictingHyps.removeProps(hypsToBeRemoved); + Context resolvedContext = new Context(conflictingContext, + contextSet.getContext(conflictingContext).getHypothesisSet().union(modifiedHyps)); + contextSet.add(resolvedContext); + } + conflictingContext = null; + conflictingHyps = null; + } + + } + + /** + * removes a set of hyps from a context. + * + * @param hyps + * @param contextName + * @return + * @throws ContextNameDoesntExistException + * @throws NotAPropositionNodeException + * @throws NodeNotFoundInNetworkException + */ + public static Context removeHypsFromContext(PropositionSet hyps, String contextName) + throws ContextNameDoesntExistException, NotAPropositionNodeException, NodeNotFoundInNetworkException { + Context c = contextSet.getContext(contextName); + if (c == null) + throw new ContextNameDoesntExistException(contextName); + PropositionSet propSet = c.getHypothesisSet().removeProps(hyps); + c = new Context(contextName, propSet); + return contextSet.add(c); + /* + * c = contextSet.add(c); Network.defineDefaults(); if (conflictingContext != + * null && contextName == conflictingContext) { PropositionNode tempProp = + * (PropositionNode)Network.buildBaseNode("n"+ -5000, Semantic.proposition); if + * (Controller.checkForContradictionCore(tempProp, c, false) == null) + * conflictingContext = null; Network.removeNode(tempProp); } return c; + */ + + } + + /** + * removes a proposition fromm all contexts. This means removing all its + * supports from all contexts. + * + * @param node + * @throws NodeNotFoundInPropSetException + * @throws NotAPropositionNodeException + * @throws NodeNotFoundInNetworkException + */ + public static void removePropositionFromAllContexts(PropositionNode node) + throws NodeNotFoundInPropSetException, NotAPropositionNodeException, NodeNotFoundInNetworkException { + int hyp = node.getId(); + for (String contextName : contextSet.getNames()) { + Context c = new Context(contextName, contextSet.getContext(contextName).getHypothesisSet().remove(hyp)); + contextSet.add(c); + /* + * c = contextSet.add(c); Network.defineDefaults(); if (conflictingContext != + * null && contextName == conflictingContext) { PropositionNode tempProp = + * (PropositionNode)Network.buildBaseNode("n"+ -5000, Semantic.proposition); if + * (Controller.checkForContradictionCore(tempProp, c, false) == null) + * conflictingContext = null; Network.removeNode(tempProp); } + */ + } + } + + /** + * Returns all the names of contexts available in the system. + * + * @return + */ + public static Set getAllNamesOfContexts() { + return contextSet.getNames(); + } + + /** + * Returns a Context given its name + * + * @param contextName the name of the Context to be returned + * @return Context object + */ + public static Context getContextByName(String contextName) { + return contextSet.getContext(contextName); + } + + public static void save(String f) throws FileNotFoundException, IOException { + ObjectOutputStream cos = new ObjectOutputStream(new FileOutputStream(new File(f))); cos.writeObject(contextSet); cos.close(); - } - - public static void load(String f) throws IOException, ClassNotFoundException { - ObjectInputStream cis= new ObjectInputStream(new FileInputStream(new File(f))); - ContextSet tempSet = (ContextSet) cis.readObject(); + } + + public static void load(String f) throws IOException, ClassNotFoundException { + ObjectInputStream cis = new ObjectInputStream(new FileInputStream(new File(f))); + ContextSet tempSet = (ContextSet) cis.readObject(); Controller.contextSet = tempSet; cis.close(); tempSet = null; - } + } } \ No newline at end of file diff --git a/src/sneps/snip/Report.java b/src/sneps/snip/Report.java index 71af0363..498c7421 100644 --- a/src/sneps/snip/Report.java +++ b/src/sneps/snip/Report.java @@ -6,6 +6,8 @@ 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.snebr.Support; @@ -13,24 +15,46 @@ public class Report { private Substitutions substitution; - private Support support; + private PropositionSet support; private boolean sign; private InferenceTypes inferenceType; - public Report(Substitutions substitution, Support suppt, boolean sign, InferenceTypes inference) { + public Report(Substitutions substitution, PropositionSet suppt, boolean sign, InferenceTypes inference) { this.substitution = substitution; this.support = suppt; this.sign = sign; this.inferenceType = inference; } + /*** + * Method should be used if the Report has a support of type Support and not a + * PropositionSet + * + * @param reportContext + * @return + * @throws NotAPropositionNodeException + * @throws NodeNotFoundInNetworkException + */ + /* + * public boolean anySupportAssertedInContext(Context reportContext) throws + * NotAPropositionNodeException, NodeNotFoundInNetworkException { + * Collection reportSupportsSet = + * support.getAssumptionBasedSupport().values(); PropositionSet + * contextHypothesisSet = reportContext.getHypothesisSet(); for (PropositionSet + * assumptionHyps : reportSupportsSet) if + * (assumptionHyps.isSubSet(contextHypothesisSet)) return true; return false; } + */ + public boolean anySupportAssertedInContext(Context reportContext) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - Collection reportSupportsSet = support.getAssumptionBasedSupport().values(); - PropositionSet contextHypothesisSet = reportContext.getHypothesisSet(); - for (PropositionSet assumptionHyps : reportSupportsSet) - if (assumptionHyps.isSubSet(contextHypothesisSet)) + 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; } @@ -38,7 +62,7 @@ public Substitutions getSubstitutions() { return substitution; } - public Support getSupport() { + public PropositionSet getSupport() { return support; } diff --git a/src/sneps/snip/Runner.java b/src/sneps/snip/Runner.java index 6bc1a199..ae8b65f8 100644 --- a/src/sneps/snip/Runner.java +++ b/src/sneps/snip/Runner.java @@ -2,27 +2,31 @@ 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; - + 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()) { + 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(); @@ -31,33 +35,33 @@ public static String run() { toRunNext.processReports(); sequence += 'H'; } - while(!lowQueue.isEmpty()) { + while (!lowQueue.isEmpty()) { System.out.println("in"); Node toRunNext = lowQueue.poll(); toRunNext.processRequests(); sequence += 'L'; - if(!highQueue.isEmpty()) + if (!highQueue.isEmpty()) continue main; } - while(!actQueue.isEmpty()) { + 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()) { + 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); } @@ -66,4 +70,11 @@ public static void addToActStack(ActNode node) { actQueue.addLast(node); } + public static void addNodeAssertionThroughFReport(Report report, PropositionNode node) { + forwardAssertedNodes.put(report, node); + } + + public static boolean isNodeAssertedThroughForwardInf(PropositionNode node) { + return forwardAssertedNodes.containsValue(node); + } } diff --git a/src/sneps/snip/channels/AntecedentToRuleChannel.java b/src/sneps/snip/channels/AntecedentToRuleChannel.java index bf007c8c..9d12bd46 100644 --- a/src/sneps/snip/channels/AntecedentToRuleChannel.java +++ b/src/sneps/snip/channels/AntecedentToRuleChannel.java @@ -1,6 +1,7 @@ package sneps.snip.channels; import sneps.network.Node; +import sneps.network.classes.setClasses.ReportSet; import sneps.snip.InferenceTypes; import sneps.snip.matching.Substitutions; @@ -10,4 +11,11 @@ public AntecedentToRuleChannel(Substitutions switchSubstitution, Substitutions f String contextID, Node requester, Node reporter, boolean v) { super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v); } + + public AntecedentToRuleChannel clone() { + AntecedentToRuleChannel channel = new AntecedentToRuleChannel(getSwitch().getSubstitutions(), + getFilter().getSubstitutions(), getContextName(), getRequester(), getReporter(), isValveOpen()); + channel.setReportsBuffer(new ReportSet()); + return channel; + } } diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index 34456cec..b4384117 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -30,7 +30,7 @@ public abstract class Channel { public Channel() { filter = new Filter(); switcher = new Switch(); - reportsBuffer = new ReportSet(); + setReportsBuffer(new ReportSet()); } public Channel(Substitutions switcherSubstitution, Substitutions filterSubstitutions, String contextID, @@ -42,18 +42,21 @@ public Channel(Substitutions switcherSubstitution, Substitutions filterSubstitut this.reporter = reporter; this.valve = v; this.reporter = reporter; - reportsBuffer = new ReportSet(); + setReportsBuffer(new ReportSet()); + } + + public void setFilter(Filter filter) { + this.filter = filter; } public boolean testReportToSend(Report report) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { boolean passTest = filter.canPass(report); System.out.println("Can pass " + passTest); - /* Test the context name if it will pass or not */ Context channelContext = Controller.getContextByName(getContextName()); if (passTest && report.anySupportAssertedInContext(channelContext)) { System.out.println("\nThe switcher data:\n" + switcher); switcher.switchReport(report); - reportsBuffer.addReport(report); + getReportsBuffer().addReport(report); Runner.addToHighQueue(requester); return true; } @@ -109,7 +112,7 @@ public void setValve(boolean valve) { } public void clearReportsBuffer() { - reportsBuffer.clear(); + getReportsBuffer().clear(); } public boolean processedGeneralizedRequest(Substitutions currentChannelFilterSubs) { @@ -126,4 +129,9 @@ public boolean processedGeneralizedRequest(Substitutions currentChannelFilterSub return false; } + + public void setReportsBuffer(ReportSet reportsBuffer) { + this.reportsBuffer = reportsBuffer; + } + } diff --git a/src/sneps/snip/channels/MatchChannel.java b/src/sneps/snip/channels/MatchChannel.java index 2e0706c9..037196a4 100644 --- a/src/sneps/snip/channels/MatchChannel.java +++ b/src/sneps/snip/channels/MatchChannel.java @@ -1,7 +1,16 @@ package sneps.snip.channels; +import sneps.exceptions.NodeNotFoundInNetworkException; +import sneps.exceptions.NotAPropositionNodeException; import sneps.network.Node; +import sneps.network.classes.setClasses.ReportSet; +import sneps.snebr.Context; +import sneps.snebr.Controller; +import sneps.snip.Filter; import sneps.snip.InferenceTypes; +import sneps.snip.Report; +import sneps.snip.Runner; +import sneps.snip.Switch; import sneps.snip.matching.Substitutions; public class MatchChannel extends Channel { @@ -25,4 +34,29 @@ public void setMatchType(int matchType) { this.matchType = matchType; } + public MatchChannel clone() { + MatchChannel channel = new MatchChannel(getSwitch().getSubstitutions(), getFilter().getSubstitutions(), + getContextName(), getRequester(), getReporter(), isValveOpen(), getMatchType()); + channel.setReportsBuffer(new ReportSet()); + return channel; + } + + public boolean testReportToSend(Report report) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + Filter currentChannelFilter = getFilter(); + boolean passTest = currentChannelFilter.canPass(report); + System.out.println("Can pass " + passTest); + Context channelContext = Controller.getContextByName(getContextName()); + int channelMatchType = getMatchType(); + boolean toBeSentFlag = (channelMatchType == 0) || (channelMatchType == 1 && report.isPositive()) + || (channelMatchType == 2 && report.isNegative()); + if (passTest && toBeSentFlag && report.anySupportAssertedInContext(channelContext)) { + Switch currentChannelSwitch = getSwitch(); + System.out.println("\nThe switcher data:\n" + currentChannelSwitch); + currentChannelSwitch.switchReport(report); + getReportsBuffer().addReport(report); + Runner.addToHighQueue(getRequester()); + return true; + } + return false; + } } diff --git a/src/sneps/snip/channels/RuleToConsequentChannel.java b/src/sneps/snip/channels/RuleToConsequentChannel.java index 252c091e..ae685eb5 100644 --- a/src/sneps/snip/channels/RuleToConsequentChannel.java +++ b/src/sneps/snip/channels/RuleToConsequentChannel.java @@ -1,6 +1,7 @@ package sneps.snip.channels; import sneps.network.Node; +import sneps.network.classes.setClasses.ReportSet; import sneps.snip.InferenceTypes; import sneps.snip.matching.Substitutions; @@ -11,4 +12,11 @@ public RuleToConsequentChannel(Substitutions switchSubstitution, Substitutions f super(switchSubstitution, filterSubstitutions, contextID, requester, reporter, v); } + public RuleToConsequentChannel clone() { + RuleToConsequentChannel channel = new RuleToConsequentChannel(getSwitch().getSubstitutions(), + getFilter().getSubstitutions(), getContextName(), getRequester(), getReporter(), isValveOpen()); + channel.setReportsBuffer(new ReportSet()); + return channel; + } + } diff --git a/src/sneps/snip/classes/FlagNode.java b/src/sneps/snip/classes/FlagNode.java index f009788c..f6483a1e 100644 --- a/src/sneps/snip/classes/FlagNode.java +++ b/src/sneps/snip/classes/FlagNode.java @@ -11,19 +11,19 @@ public class FlagNode { private Node node; - private Support supports; + private PropositionSet supports; private int flag; /** * Create a new flag node * * @param n node - * @param support support + * @param propositionSet support * @param f true or false */ - public FlagNode(Node n, Support support, int f) { + public FlagNode(Node n, PropositionSet propositionSet, int f) { node = n; - supports = support; + supports = propositionSet; flag = f; } @@ -41,7 +41,7 @@ public Node getNode() { * * @return support */ - public Support getSupports() { + public PropositionSet getSupports() { return supports; } diff --git a/src/sneps/snip/classes/VariableNodeStats.java b/src/sneps/snip/classes/VariableNodeStats.java index 6c551910..2947b3c1 100644 --- a/src/sneps/snip/classes/VariableNodeStats.java +++ b/src/sneps/snip/classes/VariableNodeStats.java @@ -10,9 +10,9 @@ public class VariableNodeStats { private boolean allVariablesBound; private Substitutions referenceSubs; private int nodeId; - private Vector variableNodeSubs; + private Substitutions variableNodeSubs; - public VariableNodeStats(boolean variablesBound, Vector extractedFilterRelevantToVariables, + public VariableNodeStats(boolean variablesBound, Substitutions extractedFilterRelevantToVariables, Substitutions refSubs, int id) { allVariablesBound = variablesBound; variableNodeSubs = extractedFilterRelevantToVariables; @@ -20,7 +20,7 @@ public VariableNodeStats(boolean variablesBound, Vector extractedFilter nodeId = id; } - public VariableNodeStats(boolean variablesBound, Vector extractedFilterRelevantToVariables, + public VariableNodeStats(boolean variablesBound, Substitutions extractedFilterRelevantToVariables, Substitutions refSubs) { allVariablesBound = variablesBound; variableNodeSubs = extractedFilterRelevantToVariables; @@ -57,11 +57,16 @@ public void setAllVariablesBound(boolean allVariablesBound) { this.allVariablesBound = allVariablesBound; } - public Vector getVariableNodeSubs() { + public Substitutions getVariableNodeSubs() { return variableNodeSubs; } - public void setVariableNodeSubs(Vector variableNodeSubs) { + public void setVariableNodeSubs(Substitutions variableNodeSubs) { this.variableNodeSubs = variableNodeSubs; } + + public boolean isSubSet(Substitutions variableSubstitutions) { + return variableNodeSubs.isSubSet(variableSubstitutions); + } + } diff --git a/src/sneps/snip/matching/HashSubstitutions.java b/src/sneps/snip/matching/HashSubstitutions.java new file mode 100644 index 00000000..e0c3cfd9 --- /dev/null +++ b/src/sneps/snip/matching/HashSubstitutions.java @@ -0,0 +1,192 @@ +package sneps.snip.matching; + +import java.util.HashMap; + +import sneps.network.nodes.Node; +import sneps.network.nodes.VariableNode; + +public class HashSubstitution implements Substitutions { + HashMap sub; + + public HashSubstitution() { + sub = new HashMap(); + } + + public boolean isNew() { + return sub.isEmpty(); + } + + public void putIn(Binding mb) { + + sub.put(mb.getVariable(), mb.getNode()); + + } + + public boolean isCompatible(Binding mb) { + // TODO Auto-generated method stub + return false; + } + + public void update(Binding mb, Node mn) { + sub.put(mb.getVariable(), mn); + + } + + public boolean isBound(VariableNode mv) { + return sub.containsKey(mv); + } + + public boolean isValue(Node mn) { + return sub.containsValue(mn); + } + + public VariableNode srcNode(Node mn) { + VariableNode[] variables = (VariableNode[]) sub.keySet().toArray(); + for (VariableNode variable : variables) + if (sub.get(variable).equals(mn)) + return variable; + return null; + } + + public Binding getBindingByVariable(VariableNode mv) { + return sub.containsKey(mv) ? new Binding(mv, sub.get(mv)) : null; + + } + + public Binding getBindingByNode(Node mn) { + VariableNode key = srcNode(mn); + return key == null ? null : new Binding(key, mn); + } + + public boolean isMember(Binding mb) { + Node node = sub.get(mb.getVariable()); + return node != null && node == mb.getNode(); + } + + @Override + public boolean isSubSet(Substitutions s) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isEqual(Substitutions s) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Substitutions union(Substitutions s) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void unionIn(Substitutions s) { + // TODO Auto-generated method stub + + } + + public Substitutions restrict(VariableNode[] variables) { + HashSubstitution hs = new HashSubstitution(); + for (VariableNode variable : variables) + hs.putIn(new Binding(variable, sub.get(variable))); + + return hs; + } + + public Node term(VariableNode mv) { + return sub.get(mv); + } + + public int cardinality() { + return sub.size(); + } + + @Override + public Binding choose() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Substitutions others() { + // TODO Auto-generated method stub + return null; + } + + public Node value(VariableNode v) { + Node n = sub.get(v); + return n == null ? v : n; + } + + public Substitutions insert(Binding m) { + HashSubstitution s = new HashSubstitution(); + s.insert(this); + s.putIn(m); + return s; + } + + @Override + public boolean isCompatible(Substitutions s) { + // TODO Auto-generated method stub + return false; + } + + public Binding getBinding(int x) { + VariableNode[] vns = new VariableNode[sub.size()]; + vns = sub.keySet().toArray(vns); + return new Binding(vns[x], sub.get(vns[x])); + } + + @Override + public Substitutions[] split() { + // TODO Auto-generated method stub + return null; + } + + public void clear() { + sub = new HashMap(); + + } + + public void insert(Substitutions s) { + for (int i = 0; i < s.cardinality(); i++) + putIn(s.getBinding(i)); + + } + + @Override + public boolean sub(String x, String y) { + for (int i = 0; i < y.length(); i++) { + if (y.charAt(i) != x.charAt(i)) + return false; + } + return true; + } + + public String toString() { + // TODO: Auto-generated method stub + return null; + } + + public int termID(int variableID) { + VariableNode[] vns = new VariableNode[sub.size()]; + vns = sub.keySet().toArray(vns); + for (int i = 0; i < vns.length; i++) + if (vns[i].getId() == variableID) + return sub.get(vns[i]).getId(); + + return -1; + } + + @Override + public void insertOrUpdate(Binding mb) { + if (sub.containsKey(mb.getVariable())) + update(getBindingByVariable(mb.getVariable()), mb.getNode()); + else + putIn(mb); + + } + +} \ No newline at end of file diff --git a/src/sneps/snip/matching/LinearSubstitutions.java b/src/sneps/snip/matching/LinearSubstitutions.java index f9816397..4d5ea847 100644 --- a/src/sneps/snip/matching/LinearSubstitutions.java +++ b/src/sneps/snip/matching/LinearSubstitutions.java @@ -18,6 +18,10 @@ public LinearSubstitutions() { sub = new Vector(); } + public LinearSubstitutions(Vector vectorBindings) { + sub = vectorBindings; + } + /** * Check if the substitutions list new or not (empty) * @@ -473,7 +477,8 @@ public VariableNodeStats extractBoundStatus(VariableSet freeVariables) { extractedFilterRelevantToVariables.add(binding); forAllCondition &= bindingFound; } - return new VariableNodeStats(forAllCondition, extractedFilterRelevantToVariables, this); + Substitutions extractedFilterSubs = new LinearSubstitutions(extractedFilterRelevantToVariables); + return new VariableNodeStats(forAllCondition, extractedFilterSubs, this); } diff --git a/src/sneps/snip/rules/OrNode.java b/src/sneps/snip/rules/OrNode.java index a095098c..8013f9cf 100644 --- a/src/sneps/snip/rules/OrNode.java +++ b/src/sneps/snip/rules/OrNode.java @@ -6,6 +6,7 @@ import java.util.Hashtable; import java.util.Set; +import sneps.exceptions.DuplicatePropositionException; import sneps.exceptions.NodeNotFoundInNetworkException; import sneps.exceptions.NotAPropositionNodeException; import sneps.network.Node; @@ -30,12 +31,12 @@ public OrNode(Term syn) { cq = getDownNodeSet("cq").size(); } - public void applyRuleHandler(Report report, Node node) { + public void applyRuleHandler(Report report, Node node) throws DuplicatePropositionException, NotAPropositionNodeException, NodeNotFoundInNetworkException { if (report.isPositive()) { Support originSupports = this.getBasicSupport(); Collection originSupportsSet = originSupports.getAssumptionBasedSupport().values(); - Support sup = new Support(this); - // sup.add(originSupports); + PropositionSet sup = new PropositionSet(); + sup.add(getId()); Report reply = new Report(report.getSubstitutions(), sup, true, null); for (Channel outChannel : outgoingChannels) try { From 8ab7e61dd3f76390dcfa776b9ab5f6688da02160 Mon Sep 17 00:00:00 2001 From: Youssef Date: Sun, 19 May 2019 23:10:27 +0200 Subject: [PATCH 15/22] finalized reports handling for a proposition node and modified multiple data sctructures such as ChannelSet and Runner --- src/sneps/gui/FXController.java | 3 +- src/sneps/network/Node.java | 33 +-- src/sneps/network/PropositionNode.java | 266 ++++++++++++------ src/sneps/network/RuleNode.java | 169 +++++++---- .../classes/setClasses/ChannelSet.java | 116 ++++++-- src/sneps/snip/Report.java | 27 ++ src/sneps/snip/ReportInstances.java | 37 +++ src/sneps/snip/Runner.java | 14 + src/sneps/snip/channels/Channel.java | 35 ++- .../snip/channels/ChannelIdentifier.java | 64 +++++ src/sneps/snip/channels/MatchChannel.java | 14 +- src/sneps/snip/classes/RuleResponse.java | 32 ++- .../snip/matching/HashSubstitutions.java | 30 +- .../snip/matching/LinearSubstitutions.java | 8 +- src/sneps/snip/matching/Substitutions.java | 2 + 15 files changed, 597 insertions(+), 253 deletions(-) create mode 100644 src/sneps/snip/ReportInstances.java create mode 100644 src/sneps/snip/channels/ChannelIdentifier.java diff --git a/src/sneps/gui/FXController.java b/src/sneps/gui/FXController.java index 27db001b..442305b4 100644 --- a/src/sneps/gui/FXController.java +++ b/src/sneps/gui/FXController.java @@ -112,6 +112,7 @@ import sneps.snebr.Controller; import sneps.snepslog.AP; import sneps.snip.Report; +import sneps.snip.ReportInstances; public class FXController implements Initializable { Network network = new Network(); @@ -3630,7 +3631,7 @@ public void deduce() { // n = Network.buildTemporaryNode(identifier, ); } n.deduce(); - ReportSet rs = n.getKnownInstances(); + ReportInstances rs = n.getKnownInstances(); for (Report r : rs) { res = res + r.toString() + "\n"; } diff --git a/src/sneps/network/Node.java b/src/sneps/network/Node.java index 1d91090e..0d316605 100644 --- a/src/sneps/network/Node.java +++ b/src/sneps/network/Node.java @@ -160,12 +160,10 @@ public boolean equals(Object obj) { } public void receiveRequest(Channel newChannel) { - // TODO Auto-generated method stub - install channel Runner.addToLowQueue(this); } public void receiveReport(Channel newChannel) { - // TODO Auto-generated method stub Runner.addToHighQueue(this); } @@ -208,38 +206,9 @@ public NodeSet getDominatingRules() { return ret; } - /*** - * Checking if this node instance contains not yet bound free variables - * - * @param filterSubs reference substitutions - * @return boolean computed from VariableNodeStats.areAllVariablesBound() - */ - public boolean isWhQuestion(Substitutions filterSubs) { - VariableNodeStats currentNodeStats = computeNodeStats(filterSubs); - return !currentNodeStats.areAllVariablesBound(); - } - /*** - * Method computing an output of VariableNodeStats containing info about a - * certain node with variables by checking the input Substitutions and comparing - * them with the instance freeVariables, stating whether over a given - * substitutions the node will have all its freeVariables bound and also - * filtering the input substitutions to match the free variables (not including - * extra irrelevant filters) - * - * @param filterSubs Substitutions the given substitutions on which bindings - * check will occur - * @return VariableNodeStats - */ - public VariableNodeStats computeNodeStats(Substitutions filterSubs) { - VariableSet freeVariables = new VariableSet(); - if (term instanceof Open) - freeVariables = ((Open) term).getFreeVariables(); - VariableNodeStats toBeReturned = filterSubs.extractBoundStatus(freeVariables); - toBeReturned.setNodeId(id); - return toBeReturned; - } + Context fake() { return null; diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index c48a66a3..4311648a 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -17,6 +17,8 @@ import sneps.network.classes.setClasses.NodeSet; import sneps.network.classes.setClasses.PropositionSet; import sneps.network.classes.setClasses.ReportSet; +import sneps.network.classes.setClasses.VariableSet; +import sneps.network.classes.term.Open; import sneps.network.classes.term.Term; import java.util.Hashtable; @@ -30,12 +32,14 @@ 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; import sneps.snip.channels.ChannelTypes; import sneps.snip.channels.MatchChannel; import sneps.snip.channels.RuleToConsequentChannel; +import sneps.snip.classes.VariableNodeStats; import sneps.snip.matching.LinearSubstitutions; import sneps.snip.matching.Match; import sneps.snip.matching.Matcher; @@ -45,20 +49,20 @@ public class PropositionNode extends Node implements Serializable { private 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(); } public PropositionNode(Term trm) { super(Semantic.proposition, trm); outgoingChannels = new ChannelSet(); incomingChannels = new ChannelSet(); - knownInstances = new ReportSet(); + knownInstances = new ReportInstances(); setTerm(trm); } @@ -94,7 +98,14 @@ protected Channel establishChannel(ChannelTypes type, Object currentElement, Sub newChannel = new RuleToConsequentChannel(switchLinearSubs, filterSubs, contextName, this, evaluatedReporter, true); } - return newChannel; + ChannelSet incomingChannels = getIncomingChannels(); + Channel extractedChannel = incomingChannels.getChannel(newChannel); + if (extractedChannel == null) { + ((PropositionNode) evaluatedReporter).addToOutgoingChannels(newChannel); + addToIncomingChannels(newChannel); + return newChannel; + } + return extractedChannel; } @@ -127,6 +138,16 @@ public void broadcastReport(Report report) { sendReport(report, outChannel); } + /*** + * Trying to send reports to all outgoing channels + * + * @param report + */ + public void broadcastReports(ReportSet reports) { + for (Report report : reports) + broadcastReport(report); + } + /*** * Helper method responsible for establishing channels between this current node * and each of the NodeSet to further request instances with the given inputs @@ -137,22 +158,17 @@ public void broadcastReport(Report report) { * @param channelType * @param inferenceType */ - protected void sendReportToNodeSet(NodeSet ns, Report toBeSent, String contextID, ChannelTypes channelType) { + protected void sendReportToNodeSet(NodeSet ns, Report toBeSent, String contextName, ChannelTypes channelType) { for (Node sentTo : ns) { Substitutions reportSubs = toBeSent.getSubstitutions(); - Channel newChannel = establishChannel(channelType, sentTo, null, reportSubs, contextID, -1); - ReportSet channelReportBuffer = newChannel.getReportsBuffer(); - channelReportBuffer.addReport(toBeSent); - outgoingChannels.addChannel(newChannel); - sentTo.receiveReport(newChannel); + Channel newChannel = establishChannel(channelType, sentTo, null, reportSubs, contextName, -1); + sendReport(toBeSent, newChannel); } } - protected void sendReportsToNodeSet(NodeSet ns, ReportSet reports, String contextID, ChannelTypes channelType) { - for (Report report : reports) { - sendReportToNodeSet(ns, report, contextID, channelType); - } - + protected void sendReportsToNodeSet(NodeSet ns, ReportSet toBeSent, String contextName, ChannelTypes channelType) { + for (Report report : toBeSent) + sendReportToNodeSet(ns, report, contextName, channelType); } /*** @@ -171,10 +187,7 @@ protected void sendReportToMatches(List list, Report toBeSent, String con int matchType = currentMatch.getMatchType(); Channel newChannel = establishChannel(ChannelTypes.MATCHED, currentMatch, null, reportSubs, contextId, matchType); - ReportSet channelReportBuffer = newChannel.getReportsBuffer(); - channelReportBuffer.addReport(toBeSent); - outgoingChannels.addChannel(newChannel); - currentMatch.getNode().receiveReport(newChannel); + sendReport(toBeSent, newChannel); } } @@ -184,6 +197,13 @@ protected void sendReportsToMatches(List list, ReportSet reports, String } } + protected void sendReportToChannelSet(ChannelSet filteredNodeSet, Report toBeSent) { + for (Channel channel : filteredNodeSet) { + sendReport(toBeSent, channel); + } + + } + /*** * Helper method responsible for establishing channels between this current node * and each of the List to further request instances with the given @@ -198,28 +218,24 @@ protected void sendRequestsToMatches(List list, String contextId) { Substitutions switchSubs = currentMatch.getSwitchSubs(); Substitutions filterSubs = currentMatch.getFilterSubs(); int matchType = currentMatch.getMatchType(); + PropositionNode matchedNode = (PropositionNode) currentMatch.getNode(); Channel newChannel = establishChannel(ChannelTypes.MATCHED, currentMatch, switchSubs, filterSubs, contextId, matchType); - incomingChannels.addChannel(newChannel); - currentMatch.getNode().receiveRequest(newChannel); + matchedNode.receiveRequest(newChannel); } } /*** * Helper method responsible for establishing channels between this current node - * and each of the NodeSet to further request instances with the given inputs + * and each of the Matches to further request instances with the given inputs * - * @param ns NodeSet to be sent to - * @param filterSubs Substitutions to be passed - * @param contextID latest channel context - * @param channelType - * @param inferenceType + * @param list List to be sent to + * @param contextID latest channel context */ protected void sendRequestsToNodeSet(NodeSet ns, Substitutions filterSubs, String contextID, ChannelTypes channelType) { for (Node sentTo : ns) { Channel newChannel = establishChannel(channelType, sentTo, null, filterSubs, contextID, -1); - incomingChannels.addChannel(newChannel); sentTo.receiveRequest(newChannel); } } @@ -246,7 +262,6 @@ public boolean assertedInContext(String desiredContextName) * through the runner. */ public void receiveRequest(Channel channel) { - outgoingChannels.addChannel(channel); Runner.addToLowQueue(this); channel.setRequestProcessed(true); } @@ -255,8 +270,7 @@ public void receiveRequest(Channel channel) { * Reports received added to the high priority queue to be served accordingly * through the runner. */ - public void receiveReports(Channel channel) { - outgoingChannels.addChannel(channel); + public void receiveReport(Channel channel) { Runner.addToHighQueue(this); channel.setReportProcessed(true); } @@ -264,8 +278,8 @@ public void receiveReports(Channel channel) { public void deduce() { Runner.initiate(); String currentContextName = Controller.getCurrentContextName(); - getNodesToSendRequest(ChannelTypes.RuleCons, currentContextName, null, InferenceTypes.BACKWARD); - getNodesToSendRequest(ChannelTypes.MATCHED, currentContextName, null, InferenceTypes.BACKWARD); + getNodesToSendRequest(ChannelTypes.RuleCons, currentContextName, null); + getNodesToSendRequest(ChannelTypes.MATCHED, currentContextName, null); // what to return here ? System.out.println(Runner.run()); } @@ -317,7 +331,7 @@ protected void getNodesToSendReport(ChannelTypes channelType, String currentCont * @param inferenceType inference type used for this process */ protected void getNodesToSendRequest(ChannelTypes channelType, String currentContextName, - Substitutions substitutions, InferenceTypes inferenceType) { + Substitutions substitutions) { try { switch (channelType) { case MATCHED: @@ -341,7 +355,7 @@ protected void getNodesToSendRequest(ChannelTypes channelType, String currentCon } /*** - * Method comparing opened incoming channels over each match's node of the + * Method comparing opened outgoing channels over each match's node of the * matches whether a more generic request of the specified channel was * previously sent in order not to re-send redundant requests -- ruleType gets * applied on Andor or Thresh part. @@ -351,32 +365,30 @@ protected void getNodesToSendRequest(ChannelTypes channelType, String currentCon * @param ruleType * @return */ - protected List removeAlreadyWorkingOn(List matchingNodes, Channel currentChannel, boolean ruleType) { + protected List removeAlreadyWorkingOn(List matchingNodes, Channel currentChannel) { List nodesToConsider = new ArrayList(); for (Match sourceMatch : matchingNodes) { Node sourceNode = sourceMatch.getNode(); if (sourceNode instanceof PropositionNode) { - boolean conditionMet = ruleType && sourceNode == currentChannel.getRequester(); - if (!conditionMet) { - conditionMet = true; - Substitutions currentChannelFilterSubs = currentChannel.getFilter().getSubstitutions(); - ChannelSet outgoingChannels = ((PropositionNode) sourceNode).getOutgoingChannels(); - ChannelSet filteredChannelsSet = outgoingChannels.getFilteredRequestChannels(true); - for (Channel outgoingChannel : filteredChannelsSet) { - Substitutions processedChannelFilterSubs = outgoingChannel.getFilter().getSubstitutions(); - conditionMet &= !processedChannelFilterSubs.isSubSet(currentChannelFilterSubs) - && outgoingChannel.getRequester() == currentChannel.getReporter(); - } - if (conditionMet) - nodesToConsider.add(sourceMatch); + boolean conditionMet = true; + Substitutions currentChannelFilterSubs = currentChannel.getFilter().getSubstitutions(); + ChannelSet outgoingChannels = ((PropositionNode) sourceNode).getOutgoingChannels(); + // ChannelSet filteredChannelsSet = + // outgoingChannels.getFilteredRequestChannels(true); + for (Channel outgoingChannel : outgoingChannels) { + Substitutions processedChannelFilterSubs = outgoingChannel.getFilter().getSubstitutions(); + conditionMet &= !processedChannelFilterSubs.isSubSet(currentChannelFilterSubs) + && outgoingChannel.getRequester().getId() == currentChannel.getReporter().getId(); } + if (conditionMet) + nodesToConsider.add(sourceMatch); } } return nodesToConsider; } /*** - * Method comparing opened incoming channels over each node of the nodes whether + * Method comparing opened outgoing channels over each node of the nodes whether * a more generic request of the specified channel was previously sent in order * not to re-send redundant requests -- ruleType gets applied on Andor or Thresh * part. @@ -392,15 +404,14 @@ protected static NodeSet removeAlreadyWorkingOn(NodeSet nodes, Channel channel, NodeSet nodesToConsider = new NodeSet(); for (Node sourceNode : nodes) if (sourceNode instanceof PropositionNode) { - boolean conditionMet = ruleType && sourceNode == channel.getRequester(); - if (!conditionMet) { - conditionMet = true; + boolean conditionMet = !ruleType || sourceNode.getId() != channel.getRequester().getId(); + if (conditionMet) { ChannelSet outgoingChannels = ((PropositionNode) sourceNode).getOutgoingChannels(); - ChannelSet filteredChannelsSet = outgoingChannels.getFilteredRequestChannels(true); - for (Channel outgoingChannel : filteredChannelsSet) { +// ChannelSet filteredChannelsSet = outgoingChannels.getFilteredRequestChannels(true); + for (Channel outgoingChannel : outgoingChannels) { Substitutions processedChannelFilterSubs = outgoingChannel.getFilter().getSubstitutions(); conditionMet &= !processedChannelFilterSubs.isSubSet(toBeCompared) - && outgoingChannel.getRequester() == channel.getReporter(); + && outgoingChannel.getRequester().getId() == channel.getReporter().getId(); } if (conditionMet) nodesToConsider.addNode(sourceNode); @@ -433,11 +444,11 @@ 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; } @@ -483,13 +494,16 @@ public NodeSet getUpConsNodeSet() { NodeSet ret = new NodeSet(); UpCable consequentCable = this.getUpCableSet().getUpCable("cq"); UpCable argsCable = this.getUpCableSet().getUpCable("arg"); + UpCable propCable = this.getUpCableSet().getUpCable("prop"); if (argsCable != null) { ret.addAll(argsCable.getNodeSet()); } if (consequentCable != null) { ret.addAll(consequentCable.getNodeSet()); } - + if (propCable != null) { + ret.addAll(propCable.getNodeSet()); + } return ret; } @@ -566,30 +580,97 @@ public void setHyp(boolean isHyp) throws NotAPropositionNodeException, NodeNotFo basicSupport.setHyp(isHyp); } - protected Set getOutgoingAntecedentRuleChannels() { + protected Collection getOutgoingAntecedentRuleChannels() { return outgoingChannels.getAntRuleChannels(); } - protected Set getOutgoingRuleConsequentChannels() { + protected Collection getOutgoingRuleConsequentChannels() { return outgoingChannels.getRuleConsChannels(); } - protected Set getOutgoingMatchChannels() { + protected Collection getOutgoingMatchChannels() { return outgoingChannels.getMatchChannels(); } - protected Set getIncomingAntecedentRuleChannels() { + public void addToOutgoingChannels(Channel channel) { + outgoingChannels.addChannel(channel); + } + + public void addToIncomingChannels(Channel channel) { + incomingChannels.addChannel(channel); + } + + protected Collection getIncomingAntecedentRuleChannels() { return incomingChannels.getAntRuleChannels(); } - protected Set getIncomingRuleConsequentChannels() { + protected Collection getIncomingRuleConsequentChannels() { return incomingChannels.getRuleConsChannels(); } - protected Set getIncomingMatchChannels() { + protected Collection getIncomingMatchChannels() { return incomingChannels.getMatchChannels(); } + /*** + * Checking if this node instance contains not yet bound free variables + * + * @param filterSubs reference substitutions + * @return boolean computed from VariableNodeStats.areAllVariablesBound() + */ + public boolean isWhQuestion(Substitutions filterSubs) { + VariableNodeStats currentNodeStats = computeNodeStats(filterSubs); + return !currentNodeStats.areAllVariablesBound(); + } + + /*** + * Method computing an output of VariableNodeStats containing info about a + * certain node with variables by checking the input Substitutions and comparing + * them with the instance freeVariables, stating whether over a given + * substitutions the node will have all its freeVariables bound and also + * filtering the input substitutions to match the free variables (not including + * extra irrelevant filters) + * + * @param filterSubs Substitutions the given substitutions on which bindings + * check will occur + * @return VariableNodeStats + */ + public VariableNodeStats computeNodeStats(Substitutions filterSubs) { + VariableSet freeVariables = new VariableSet(); + if (term instanceof Open) + freeVariables = ((Open) term).getFreeVariables(); + VariableNodeStats toBeReturned = filterSubs.extractBoundStatus(freeVariables); + toBeReturned.setNodeId(getId()); + return toBeReturned; + + } + + private Report attemptAddingReportToKnownInstances(Channel channel, Report report) { + Substitutions reportSubs = report.getSubstitutions(); + Set compatibleReports = knownInstances.getReportBySubstitutions(reportSubs); + boolean channelCheck = channel instanceof MatchChannel || channel instanceof RuleToConsequentChannel; + Report evaluatedReport; + if (compatibleReports == null) { + if (channelCheck) + knownInstances.addReport(report); + return report; + } + for (Report singleReport : compatibleReports) { + evaluatedReport = singleReport.computeReportFromDifferencesToSend(report); + if (evaluatedReport != null) { + if (channelCheck) + knownInstances.addReport(report); + return evaluatedReport; + } + } + return null; + } + + protected PropositionNode buildNodeSubstitutions(Substitutions subs) { + return null; + // TODO nawar + } + public void processRequests() { for (Channel outChannel : outgoingChannels) try { @@ -611,8 +692,6 @@ public void processRequests() { */ protected void processSingleRequestsChannel(Channel currentChannel) throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { - Support nodeSupport = getBasicSupport(); - String currentContextName = currentChannel.getContextName(); Context desiredContext = Controller.getContextByName(currentContextName); if (assertedInContext(desiredContext)) { @@ -620,7 +699,8 @@ protected void processSingleRequestsChannel(Channel currentChannel) int propNodeId = getId(); PropositionSet supportPropSet = new PropositionSet(); supportPropSet.add(propNodeId); - Report reply = new Report(new LinearSubstitutions(), supportPropSet, true, InferenceTypes.BACKWARD); + boolean reportSign = Controller.isNegated(this); + Report reply = new Report(new LinearSubstitutions(), supportPropSet, reportSign, InferenceTypes.BACKWARD); sendReport(reply, currentChannel); } else { boolean sentAtLeastOne = false; @@ -628,13 +708,13 @@ protected void processSingleRequestsChannel(Channel currentChannel) sentAtLeastOne |= sendReport(currentReport, currentChannel); Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); if (!sentAtLeastOne || isWhQuestion(filterSubs)) { - NodeSet dominatingRules = getDominatingRules(); + NodeSet dominatingRules = getUpConsNodeSet(); NodeSet toBeSentToDom = removeAlreadyWorkingOn(dominatingRules, currentChannel, filterSubs, false); sendRequestsToNodeSet(toBeSentToDom, new LinearSubstitutions(), currentContextName, ChannelTypes.RuleAnt); if (!(currentChannel instanceof MatchChannel)) { List matchingNodes = Matcher.match(this); - List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel, false); + List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel); sendRequestsToMatches(toBeSentToMatch, currentContextName); } } @@ -645,7 +725,8 @@ public void processReports() { for (Channel inChannel : incomingChannels) try { processSingleReportsChannel(inChannel); - } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException | DuplicatePropositionException e) { + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException | DuplicatePropositionException + | NodeNotFoundInPropSetException | CannotInsertJustificationSupportException e) { // TODO Auto-generated catch block e.printStackTrace(); } @@ -658,33 +739,36 @@ public void processReports() { * @throws NodeNotFoundInNetworkException * @throws NotAPropositionNodeException * @throws DuplicatePropositionException + * @throws CannotInsertJustificationSupportException + * @throws NodeNotFoundInPropSetException */ protected void processSingleReportsChannel(Channel currentChannel) - throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException, + NodeNotFoundInPropSetException, CannotInsertJustificationSupportException { ReportSet reports = currentChannel.getReportsBuffer(); String currentChannelContextName = currentChannel.getContextName(); for (Report currentReport : reports) { - Substitutions reportSubs = currentReport.getSubstitutions(); - PropositionSet reportSupport = currentReport.getSupport(); - boolean reportSign = currentReport.isPositive(); - boolean toBeSentFlag = true; - /* to be removed and handled in testReportToSend */ - Report alteredBReport = new Report(reportSubs, reportSupport, reportSign, InferenceTypes.BACKWARD); - Report alteredFReport = new Report(reportSubs, reportSupport, reportSign, InferenceTypes.FORWARD); - boolean backwardReportFound = knownInstances.contains(alteredBReport); - boolean forwardReportFound = knownInstances.contains(alteredFReport); - if ((!backwardReportFound || !forwardReportFound) && toBeSentFlag) { - broadcastReport(!forwardReportFound ? alteredFReport : alteredBReport); - } - /* Handling forward inference broadcasting */ - if (currentReport.getInferenceType() == InferenceTypes.FORWARD) { - List matchesReturned = Matcher.match(this); - sendReportToMatches(matchesReturned, currentReport, currentChannelContextName); - NodeSet isAntecedentTo = getUpAntNodeSet(); - sendReportToNodeSet(isAntecedentTo, currentReport, currentChannelContextName, ChannelTypes.RuleAnt); + Report reportToBeBroadcasted = attemptAddingReportToKnownInstances(currentChannel, currentReport); + if (reportToBeBroadcasted != null) { + boolean forwardReportType = reportToBeBroadcasted.getInferenceType() == InferenceTypes.FORWARD; + PropositionNode supportNode = buildNodeSubstitutions(currentReport.getSubstitutions()); + supportNode.addJustificationBasedSupport(reportToBeBroadcasted.getSupport()); + PropositionSet reportSupportPropSet = new PropositionSet(); + reportSupportPropSet.add(supportNode.getId()); + reportToBeBroadcasted.setSupport(reportSupportPropSet); + // TODO: GRADED PROPOSITIONS HANDLING REPORTS + if (forwardReportType) { + List matchesReturned = Matcher.match(this); + sendReportToMatches(matchesReturned, currentReport, currentChannelContextName); + NodeSet isAntecedentTo = getUpAntNodeSet(); + sendReportToNodeSet(isAntecedentTo, currentReport, currentChannelContextName, ChannelTypes.RuleAnt); + } else + broadcastReport(reportToBeBroadcasted); + } + if (!(this instanceof RuleNode)) + currentChannel.getReportsBuffer().removeReport(currentReport); } - currentChannel.clearReportsBuffer(); } // PROCESS REPORT : 3adi -> , forward diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index ce54c303..e526dfd6 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -4,11 +4,14 @@ import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; +import java.util.List; import java.util.Set; import java.util.Vector; +import sneps.exceptions.CannotInsertJustificationSupportException; import sneps.exceptions.DuplicatePropositionException; import sneps.exceptions.NodeNotFoundInNetworkException; +import sneps.exceptions.NodeNotFoundInPropSetException; import sneps.exceptions.NotAPropositionNodeException; import sneps.network.classes.Semantic; import sneps.network.classes.setClasses.ChannelSet; @@ -29,6 +32,7 @@ import sneps.snip.Filter; import sneps.snip.InferenceTypes; import sneps.snip.Report; +import sneps.snip.ReportInstances; import sneps.snip.Runner; import sneps.snip.channels.AntecedentToRuleChannel; import sneps.snip.channels.Channel; @@ -112,7 +116,7 @@ protected void processNodes(NodeSet antNodes) { sharedVars = getSharedVarsInts(antNodesWithVars); } - public RuleResponse applyRuleHandler(Report report, Channel currentChannel) { + public Collection applyRuleHandler(Report report, Channel currentChannel) { Node currentChannelReporter = currentChannel.getReporter(); String contextID = currentChannel.getContextName(); // Context context = SNeBR.getContextByID(contextID); @@ -270,11 +274,13 @@ public static boolean isConstantNode(Node n) { return !(n instanceof VariableNode) || n instanceof RuleNode || ((VariableNode) n).getFreeVariables().isEmpty(); } - protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel) { - NodeSet antecedentNodeSet = getDownAntNodeSet(); + protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel, boolean removeSender) { + NodeSet antecedentsNodeSet = getDownAntNodeSet(); + if (removeSender) + antecedentsNodeSet.removeNode(currentChannel.getRequester()); boolean ruleType = this instanceof ThreshNode || this instanceof AndOrNode; Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); - NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentNodeSet, currentChannel, filterSubs, ruleType); + NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentsNodeSet, currentChannel, filterSubs, ruleType); sendRequestsToNodeSet(toBeSentTo, currentChannel.getFilter().getSubstitutions(), currentChannel.getContextName(), ChannelTypes.RuleAnt); } @@ -307,25 +313,30 @@ protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel, Rep * false; } */ - public void handleResponseOfApplyRuleHandler(RuleResponse ruleResponse, Report currentReport, + public void handleResponseOfApplyRuleHandler(Collection ruleResponses, Report currentReport, Channel currentChannel) { - String currentChannelContextName = currentChannel.getContextName(); - if (ruleResponse != null) { - Report toBeSent = ruleResponse.getReport(); - broadcastReport(toBeSent); - if (toBeSent.getInferenceType() == InferenceTypes.FORWARD) { - NodeSet consequents = ruleResponse.getConsequents(); - NodeSet filteredNodeSet = removeExistingNodesOutgoingChannels(consequents); - sendReportToNodeSet(filteredNodeSet, toBeSent, currentChannelContextName, ChannelTypes.RuleCons); - } - } else if (currentReport.getInferenceType() == InferenceTypes.FORWARD) { - - Substitutions currentChannelFilterSubs = currentChannel.getFilter().getSubstitutions(); - NodeSet antecedents = getDownAntNodeSet(); - antecedents.removeNode(currentChannel.getReporter()); - sendRequestsToNodeSet(antecedents, currentChannelFilterSubs, currentChannelContextName, - ChannelTypes.RuleAnt); + for (RuleResponse ruleResponse : ruleResponses) { + if (ruleResponse != null) { + Report reportToBeSent = ruleResponse.getReport(); +// if (reportToBeSent.getInferenceType() == InferenceTypes.FORWARD) { + Collection consequentsChannels = ruleResponse.getConsequentChannels(); + for (Channel consequentChannel : consequentsChannels) { + sendReport(reportToBeSent, consequentChannel); + } +// } + /* + * OLD + * + * broadcastReport(reportToBeSent); if (reportToBeSent.getInferenceType() == + * InferenceTypes.FORWARD) { ChannelSet consequents = + * ruleResponse.getConsequentChannels(); ChannelSet filteredNodeSet = + * removeExistingOutgoingChannelsFromSet(consequents); + * sendReportToChannelSet(filteredNodeSet, reportToBeSent); } + */ + } else if (currentReport.getInferenceType() == InferenceTypes.FORWARD) + requestAntecedentsNotAlreadyWorkingOn(currentChannel, true); } + } private NodeSet removeExistingNodesOutgoingChannels(NodeSet nodeSet) { @@ -340,6 +351,23 @@ private NodeSet removeExistingNodesOutgoingChannels(NodeSet nodeSet) { return nodeSet; } + /*** + * Method filtering given ChannelSet to remove previously existing channels to + * avoid redundancy + * + * @param channelSet + * @return + */ + private Collection removeExistingOutgoingChannelsFromSet(Collection channelSet) { + ChannelSet outgoingChannels = getOutgoingChannels(); + for (Channel inputChannel : channelSet) + for (Channel channel : outgoingChannels) { + if (inputChannel.equals(channel)) + channelSet.remove(inputChannel); + } + return channelSet; + } + public void processRequests() { for (Channel outChannel : outgoingChannels) try { @@ -369,35 +397,29 @@ protected void processSingleRequestsChannel(Channel currentChannel) if (closedTypeTerm) { /* Case 1 */ if (assertedInContext(currentContext)) { - requestAntecedentsNotAlreadyWorkingOn(currentChannel); - return; - } else { + requestAntecedentsNotAlreadyWorkingOn(currentChannel, false); + } else super.processSingleRequestsChannel(currentChannel); - } } else { VariableNodeStats ruleNodeStats = computeNodeStats(filterSubs); boolean ruleNodeAllVariablesBound = ruleNodeStats.areAllVariablesBound(); Substitutions ruleNodeExtractedSubs = ruleNodeStats.getVariableNodeSubs(); /* Case 2 & 3 */ - ReportSet knownReportSet = knownInstances; + ReportInstances knownReportSet = knownInstances; for (Report report : knownReportSet) { Substitutions reportSubstitutions = report.getSubstitutions(); boolean subSetCheck = ruleNodeExtractedSubs.isSubSet(reportSubstitutions); - if (subSetCheck && report.anySupportAssertedInContext(currentContext)) { + boolean supportCheck = report.anySupportAssertedInContext(currentContext); + if (subSetCheck && supportCheck) { if (ruleNodeAllVariablesBound) { - requestAntecedentsNotAlreadyWorkingOn(currentChannel); + requestAntecedentsNotAlreadyWorkingOn(currentChannel, false); return; } else requestAntecedentsNotAlreadyWorkingOn(currentChannel, report); - } } - /* - * balash delwa2ty: badal el super i just need the isWhQuestion mel superto be - * executed bas - */ + /* TODO instead of calling super we know it's the case of isWhQuestion */ super.processSingleRequestsChannel(currentChannel); - return; } } else super.processSingleRequestsChannel(currentChannel); @@ -413,14 +435,16 @@ public void processReports() { for (Channel currentChannel : incomingChannels) try { processSingleReportsChannel(currentChannel); - } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException | DuplicatePropositionException e) { + } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException | DuplicatePropositionException + | NodeNotFoundInPropSetException | CannotInsertJustificationSupportException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void processSingleReportsChannel(Channel currentChannel) - throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException { + throws NotAPropositionNodeException, NodeNotFoundInNetworkException, DuplicatePropositionException, + NodeNotFoundInPropSetException, CannotInsertJustificationSupportException { ReportSet channelReports = currentChannel.getReportsBuffer(); String currentChannelContextName = currentChannel.getContextName(); boolean assertedInContext = assertedInContext(currentChannelContextName); @@ -430,49 +454,70 @@ protected void processSingleReportsChannel(Channel currentChannel) boolean forwardReportType = currentReport.getInferenceType() == InferenceTypes.FORWARD; Substitutions currentReportSubs = currentReport.getSubstitutions(); if (currentChannel instanceof AntecedentToRuleChannel) { + /** AntecedentToRule Channel */ if (forwardReportType) { + /** Forward Inference */ if (closedTypeTerm) { - /* Check ana asserted ezay */ - } else if (assertedInContext) { - RuleResponse ruleResponse = applyRuleHandler(currentReport, currentChannel); - handleResponseOfApplyRuleHandler(ruleResponse, currentReport, currentChannel); - /* DONE: remove the report 3ashan khalas i asserted myself */ - currentChannelReportBuffer.removeReport(currentReport); + /** Close Type Implementation */ + if (assertedInContext) { + requestAntecedentsNotAlreadyWorkingOn(currentChannel, false); + Collection ruleResponse = applyRuleHandler(currentReport, currentChannel); + handleResponseOfApplyRuleHandler(ruleResponse, currentReport, currentChannel); + currentChannelReportBuffer.removeReport(currentReport); + /* requests the antecedents, applyRuleHandler(), remove report from buffer */ + // DONE Close Type - Asserted through Forward Inference + } else { + /* try to assert myself through requests and leave the report fel buffer */ + // TODO Close Type - Not Asserted through Forward Inference + } } else { + /** Open Type Implementation */ + /* + * for every known instance compatible with the report, send requests to the + * rest of the antecedents gheir el ba3at el report and apply rule handler and + * not remove the report from the reports buffer + */ + Collection ruleResponse = applyRuleHandler(currentReport, currentChannel); + handleResponseOfApplyRuleHandler(ruleResponse, currentReport, currentChannel); Channel newChannel = ((AntecedentToRuleChannel) currentChannel).clone(); Filter newChannelSubs = new Filter(currentReportSubs); newChannel.setFilter(newChannelSubs); super.processSingleRequestsChannel(newChannel); } - /* add report to buffer */ } else { - /* keda keda asserted, fa remove the report from the buffer */ - RuleResponse ruleResponse = applyRuleHandler(currentReport, currentChannel); + /** Backward Inference */ + Collection ruleResponse = applyRuleHandler(currentReport, currentChannel); handleResponseOfApplyRuleHandler(ruleResponse, currentReport, currentChannel); - /* DONE: remove the report 3ashan khalas i asserted myself */ currentChannelReportBuffer.removeReport(currentReport); } } else { - Set ruleConsChannels = getOutgoingRuleConsequentChannels(); - if (forwardReportType) { + /** Not AntecedentToRule Channel */ - } else { - if (ruleConsChannels.isEmpty()) { - Runner.addToLowQueue(this); - } else { + /* + * Nafs el bt3mlo lel proposition node without removing the report from the + * buffer if. forward type: send requests to all antecedents + */ + super.processSingleReportsChannel(currentChannel); + ChannelSet outgoingChannels = getOutgoingChannels(); + ChannelSet incomingChannels = getIncomingChannels(); + if (forwardReportType) { + if (closedTypeTerm) { + Runner.addNodeAssertionThroughFReport(currentReport, this); + getNodesToSendRequest(ChannelTypes.RuleAnt, currentChannelContextName, currentReportSubs); + // 3alashan el rule got asserted be forward inference we lazem acheck el + // antecedents by3arfo yereport wala la2 } + } else { + if (!outgoingChannels.getChannels().isEmpty()) + receiveRequest(currentChannel); + if (!incomingChannels.getChannels().isEmpty() && true /* non empty buffers */) + receiveReport(currentChannel); + // law fih outgoing channels -> low queue + // law fih incoming channels and non empty buffers -> queue high + currentChannelReportBuffer.removeReport(currentReport); } - /* - * backward: if existing outgoing channels (ruletoconsequent) to handle request, - * put on the low queue - * - * else same as super but add filters over outgoing channels to send on to send - * over antecedent to rule and match types - * - * - * forward: send requests to the antecedents with the report subs - */ + } } } diff --git a/src/sneps/network/classes/setClasses/ChannelSet.java b/src/sneps/network/classes/setClasses/ChannelSet.java index d2538c49..c7698cad 100644 --- a/src/sneps/network/classes/setClasses/ChannelSet.java +++ b/src/sneps/network/classes/setClasses/ChannelSet.java @@ -1,24 +1,56 @@ package sneps.network.classes.setClasses; +import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; +import java.util.List; import java.util.Set; import sneps.snip.channels.AntecedentToRuleChannel; import sneps.snip.channels.Channel; +import sneps.snip.channels.ChannelIdentifier; import sneps.snip.channels.ChannelTypes; import sneps.snip.channels.RuleToConsequentChannel; +import sneps.snip.matching.Substitutions; public class ChannelSet implements Iterable { - private Hashtable> channels; + private Hashtable> channels; public ChannelSet() { - channels = new Hashtable>(); + channels = new Hashtable>(); } - public void addChannel(Channel channel) { + public Channel addChannel(Channel channel) { + int channelRequesterId = channel.getRequester().getId(); + int channelReporterId = channel.getReporter().getId(); + String channelContextName = channel.getContextName(); + Substitutions channelSubs = channel.getFilter().getSubstitutions(); + ChannelTypes channelType = getChannelType(channel); + Hashtable targetSet = channels.remove(channelType); + ChannelIdentifier channelId = new ChannelIdentifier(channelRequesterId, channelReporterId, channelContextName, + channelSubs); + Channel added = targetSet.put(channelId, channel); + channels.put(channelType, targetSet); + return added; + } + + public Channel removeChannel(Channel channel) { + int channelRequesterId = channel.getRequester().getId(); + int channelReporterId = channel.getReporter().getId(); + String channelContextName = channel.getContextName(); + Substitutions channelSubs = channel.getFilter().getSubstitutions(); + ChannelTypes channelType = getChannelType(channel); + Hashtable targetSet = channels.remove(channelType); + ChannelIdentifier channelId = new ChannelIdentifier(channelRequesterId, channelReporterId, channelContextName, + channelSubs); + Channel removed = targetSet.remove(channelId); + channels.put(channelType, targetSet); + return removed; + } + + public ChannelTypes getChannelType(Channel channel) { ChannelTypes channelType; if (channel instanceof AntecedentToRuleChannel) channelType = ChannelTypes.RuleAnt; @@ -26,17 +58,31 @@ else if (channel instanceof RuleToConsequentChannel) channelType = ChannelTypes.RuleCons; else channelType = ChannelTypes.MATCHED; - Set targetSet = channels.get(channelType); - targetSet.add(channel); - channels.put(channelType, targetSet); + return channelType; } @Override public Iterator iterator() { - Set allMergedChannels = new HashSet(); - Collection> collectionOfSets = channels.values(); - for (Set set : collectionOfSets) - allMergedChannels.addAll(set); + /* + * add ruletoantecedent channels fel akher 3alashan a serve el reports el gaya + * menhom ba3d ma aserve el reports el tanya men channels tanya -- RuleNode + * proceessReport + */ + Collection toBeAddedLater = new ArrayList(); + Collection allMergedChannels = new ArrayList(); + Collection> collectionOfSets = channels.values(); + for (Hashtable set : collectionOfSets) { + for (Channel channel : set.values()) { + boolean ruleAntChannel = channel instanceof AntecedentToRuleChannel; + if (ruleAntChannel) + toBeAddedLater.add(channel); + else + allMergedChannels.add(channel); + } + } + for (Channel ruleAntChannel : toBeAddedLater) { + allMergedChannels.add(ruleAntChannel); + } return allMergedChannels.iterator(); } @@ -49,10 +95,10 @@ public Iterator iterator() { */ public ChannelSet getFilteredRequestChannels(boolean processedRequest) { ChannelSet processedRequestsChannels = new ChannelSet(); - Set allMergedChannels = new HashSet(); - Collection> collectionOfSets = channels.values(); - for (Set set : collectionOfSets) - allMergedChannels.addAll(set); + Collection allMergedChannels = new ArrayList(); + Collection> collectionOfSets = channels.values(); + for (Hashtable set : collectionOfSets) + allMergedChannels.addAll(set.values()); for (Channel channel : allMergedChannels) { if (channel.isRequestProcessed() == processedRequest) processedRequestsChannels.addChannel(channel); @@ -60,23 +106,43 @@ public ChannelSet getFilteredRequestChannels(boolean processedRequest) { return processedRequestsChannels; } - public Set getChannels() { - Set allMergedChannels = new HashSet(); - Collection> collectionOfSets = channels.values(); - for (Set set : collectionOfSets) - allMergedChannels.addAll(set); + public Collection getChannels() { + Collection allMergedChannels = new ArrayList(); + Collection> collectionOfSets = channels.values(); + for (Hashtable set : collectionOfSets) + allMergedChannels.addAll(set.values()); return allMergedChannels; } - public Set getAntRuleChannels() { - return channels.get(ChannelTypes.RuleAnt); + public Collection getAntRuleChannels() { + Hashtable channelsHash = channels.get(ChannelTypes.RuleAnt); + return channelsHash.values(); + } + + public Collection getRuleConsChannels() { + Hashtable channelsHash = channels.get(ChannelTypes.RuleCons); + return channelsHash.values(); } - public Set getRuleConsChannels() { - return channels.get(ChannelTypes.RuleCons); + public Collection getMatchChannels() { + Hashtable channelsHash = channels.get(ChannelTypes.MATCHED); + return channelsHash.values(); } - public Set getMatchChannels() { - return channels.get(ChannelTypes.MATCHED); + public boolean contains(Channel newChannel) { + return getChannel(newChannel) != null; } + + public Channel getChannel(Channel newChannel) { + int channelRequesterId = newChannel.getRequester().getId(); + int channelReporterId = newChannel.getReporter().getId(); + String channelContextName = newChannel.getContextName(); + Substitutions channelSubs = newChannel.getFilter().getSubstitutions(); + ChannelIdentifier channelId = new ChannelIdentifier(channelRequesterId, channelReporterId, channelContextName, + channelSubs); + ChannelTypes channelType = getChannelType(newChannel); + Hashtable set = channels.get(channelType); + return set.get(channelId); + } + } diff --git a/src/sneps/snip/Report.java b/src/sneps/snip/Report.java index 498c7421..9e5d5c64 100644 --- a/src/sneps/snip/Report.java +++ b/src/sneps/snip/Report.java @@ -100,4 +100,31 @@ public void setInferenceType(InferenceTypes inferenceType) { this.inferenceType = inferenceType; } + /*** + * Handling checks done in processing single report, evaluating differences to + * know what + * + * @param report + * @return + */ + public Report computeReportFromDifferencesToSend(Report report) { + InferenceTypes instanceInfType = getInferenceType(); + InferenceTypes reportInfType = report.getInferenceType(); + PropositionSet instanceSupport = getSupport(); + PropositionSet reportSupport = report.getSupport(); + boolean supportCheck = instanceSupport.equals(reportSupport); + if (instanceInfType == InferenceTypes.BACKWARD && reportInfType == InferenceTypes.FORWARD) { + return report; + } else if (!supportCheck) { + if (instanceInfType == InferenceTypes.FORWARD && reportInfType == InferenceTypes.BACKWARD) + report.setInferenceType(InferenceTypes.FORWARD); + return report; + } + return null; + } + + public void setSupport(PropositionSet support) { + this.support = support; + } + } diff --git a/src/sneps/snip/ReportInstances.java b/src/sneps/snip/ReportInstances.java new file mode 100644 index 00000000..1f17b88c --- /dev/null +++ b/src/sneps/snip/ReportInstances.java @@ -0,0 +1,37 @@ +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.channels.Channel; +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(); + } +} diff --git a/src/sneps/snip/Runner.java b/src/sneps/snip/Runner.java index ae8b65f8..19b64256 100644 --- a/src/sneps/snip/Runner.java +++ b/src/sneps/snip/Runner.java @@ -70,10 +70,24 @@ 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) { return forwardAssertedNodes.containsValue(node); } diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index b4384117..f340cf96 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -16,8 +16,9 @@ import sneps.snip.matching.Substitutions; public abstract class Channel { - - private Filter filter; + static int count = 0; + private int idCount; + protected Filter filter; private Switch switcher; private String contextName; private Node requester; @@ -28,6 +29,7 @@ public abstract class Channel { private boolean reportProcessed = false; public Channel() { + idCount = count++; filter = new Filter(); switcher = new Switch(); setReportsBuffer(new ReportSet()); @@ -35,6 +37,7 @@ public Channel() { public Channel(Substitutions switcherSubstitution, Substitutions filterSubstitutions, String contextID, Node requester, Node reporter, boolean v) { + idCount = count++; this.filter = new Filter(filterSubstitutions); this.switcher = new Switch(switcherSubstitution); this.contextName = contextID; @@ -50,19 +53,20 @@ public void setFilter(Filter filter) { } public boolean testReportToSend(Report report) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - boolean passTest = filter.canPass(report); - System.out.println("Can pass " + passTest); + boolean passTest = filter.canPass(report); // te be reviewed Context channelContext = Controller.getContextByName(getContextName()); if (passTest && report.anySupportAssertedInContext(channelContext)) { System.out.println("\nThe switcher data:\n" + switcher); switcher.switchReport(report); + PropositionNode requesterNode = (PropositionNode) getRequester(); + requesterNode.receiveReport(this); getReportsBuffer().addReport(report); - Runner.addToHighQueue(requester); return true; } return false; } + /* add helper to check report test */ public String getContextName() { return contextName; } @@ -134,4 +138,25 @@ public void setReportsBuffer(ReportSet reportsBuffer) { this.reportsBuffer = reportsBuffer; } + public int getId() { + return idCount; + } + + public void setId(int idCount) { + this.idCount = idCount; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Channel) { + Channel channel = (Channel) obj; + boolean filterCheck = filter.getSubstitutions().equals(channel.getFilter().getSubstitutions()); + boolean contextCheck = getContextName().equals(channel.getContextName()); + boolean requesterCheck = getRequester().getId() == channel.getRequester().getId(); + boolean reporterCheck = getReporter().getId() == channel.getReporter().getId(); + return filterCheck && contextCheck && requesterCheck && reporterCheck; + } + return super.equals(obj); + } + } diff --git a/src/sneps/snip/channels/ChannelIdentifier.java b/src/sneps/snip/channels/ChannelIdentifier.java new file mode 100644 index 00000000..c2374e50 --- /dev/null +++ b/src/sneps/snip/channels/ChannelIdentifier.java @@ -0,0 +1,64 @@ +package sneps.snip.channels; + +import sneps.snip.matching.Substitutions; + +public class ChannelIdentifier { + int requesterId; + int reporterId; + String contextName; + Substitutions filterSubstitutions; + + public ChannelIdentifier(int rqId, int rpId, String cName, Substitutions fSubs) { + requesterId = rqId; + reporterId = rpId; + contextName = cName; + filterSubstitutions = fSubs; + } + + @Override + public boolean equals(Object obj) { + ChannelIdentifier channelId; + if (obj instanceof ChannelIdentifier) { + channelId = (ChannelIdentifier) obj; + boolean filterCheck = filterSubstitutions.equals(channelId.getFilterSubstitutions()); + boolean requesterCheck = getRequesterId() == channelId.getRequesterId(); + boolean reporterCheck = getReporterId() == channelId.getReporterId(); + boolean contextCheck = getContextName() == channelId.getContextName(); + return filterCheck && reporterCheck && requesterCheck && contextCheck; + } + return false; + } + + public String getContextName() { + return contextName; + } + + public void setContextName(String contextName) { + this.contextName = contextName; + } + + public int getRequesterId() { + return requesterId; + } + + public void setRequesterId(int requesterId) { + this.requesterId = requesterId; + } + + public int getReporterId() { + return reporterId; + } + + public void setReporterId(int reporterId) { + this.reporterId = reporterId; + } + + public Substitutions getFilterSubstitutions() { + return filterSubstitutions; + } + + public void setFilterSubstitutions(Substitutions filterSubstitutions) { + this.filterSubstitutions = filterSubstitutions; + } + +} diff --git a/src/sneps/snip/channels/MatchChannel.java b/src/sneps/snip/channels/MatchChannel.java index 037196a4..8772eda6 100644 --- a/src/sneps/snip/channels/MatchChannel.java +++ b/src/sneps/snip/channels/MatchChannel.java @@ -42,21 +42,9 @@ public MatchChannel clone() { } public boolean testReportToSend(Report report) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - Filter currentChannelFilter = getFilter(); - boolean passTest = currentChannelFilter.canPass(report); - System.out.println("Can pass " + passTest); - Context channelContext = Controller.getContextByName(getContextName()); int channelMatchType = getMatchType(); boolean toBeSentFlag = (channelMatchType == 0) || (channelMatchType == 1 && report.isPositive()) || (channelMatchType == 2 && report.isNegative()); - if (passTest && toBeSentFlag && report.anySupportAssertedInContext(channelContext)) { - Switch currentChannelSwitch = getSwitch(); - System.out.println("\nThe switcher data:\n" + currentChannelSwitch); - currentChannelSwitch.switchReport(report); - getReportsBuffer().addReport(report); - Runner.addToHighQueue(getRequester()); - return true; - } - return false; + return toBeSentFlag && super.testReportToSend(report); } } diff --git a/src/sneps/snip/classes/RuleResponse.java b/src/sneps/snip/classes/RuleResponse.java index 532ed6d0..93b9b14f 100644 --- a/src/sneps/snip/classes/RuleResponse.java +++ b/src/sneps/snip/classes/RuleResponse.java @@ -1,35 +1,43 @@ package sneps.snip.classes; -import sneps.network.classes.setClasses.NodeSet; +import java.util.ArrayList; +import java.util.Collection; + +import sneps.network.classes.setClasses.ChannelSet; +import sneps.network.classes.setClasses.ReportSet; import sneps.snip.Report; +import sneps.snip.channels.Channel; public class RuleResponse { private Report report; - private NodeSet consequents; + private Collection consequentChannels; public RuleResponse() { + consequentChannels = new ArrayList(); + } + public Report getReport() { + return report; } - public RuleResponse(Report report, NodeSet consequents) { + public void setReports(Report report) { this.report = report; - this.consequents = consequents; } - public Report getReport() { - return report; + public void addReport(Report report) { + this.report = report; } - public void setReport(Report report) { - this.report = report; + public Collection getConsequentChannels() { + return consequentChannels; } - public NodeSet getConsequents() { - return consequents; + public void setConsequentChannels(Collection consequentChannels) { + this.consequentChannels = consequentChannels; } - public void setConsequents(NodeSet consequents) { - this.consequents = consequents; + public void addChannel(Channel channel) { + this.consequentChannels.add(channel); } } \ No newline at end of file diff --git a/src/sneps/snip/matching/HashSubstitutions.java b/src/sneps/snip/matching/HashSubstitutions.java index e0c3cfd9..4244d930 100644 --- a/src/sneps/snip/matching/HashSubstitutions.java +++ b/src/sneps/snip/matching/HashSubstitutions.java @@ -2,13 +2,15 @@ import java.util.HashMap; -import sneps.network.nodes.Node; -import sneps.network.nodes.VariableNode; +import sneps.network.Node; +import sneps.network.VariableNode; +import sneps.network.classes.setClasses.VariableSet; +import sneps.snip.classes.VariableNodeStats; -public class HashSubstitution implements Substitutions { +public class HashSubstitutions implements Substitutions { HashMap sub; - public HashSubstitution() { + public HashSubstitutions() { sub = new HashMap(); } @@ -18,7 +20,7 @@ public boolean isNew() { public void putIn(Binding mb) { - sub.put(mb.getVariable(), mb.getNode()); + sub.put(mb.getVariableNode(), mb.getNode()); } @@ -28,7 +30,7 @@ public boolean isCompatible(Binding mb) { } public void update(Binding mb, Node mn) { - sub.put(mb.getVariable(), mn); + sub.put(mb.getVariableNode(), mn); } @@ -59,7 +61,7 @@ public Binding getBindingByNode(Node mn) { } public boolean isMember(Binding mb) { - Node node = sub.get(mb.getVariable()); + Node node = sub.get(mb.getVariableNode()); return node != null && node == mb.getNode(); } @@ -88,7 +90,7 @@ public void unionIn(Substitutions s) { } public Substitutions restrict(VariableNode[] variables) { - HashSubstitution hs = new HashSubstitution(); + HashSubstitutions hs = new HashSubstitutions(); for (VariableNode variable : variables) hs.putIn(new Binding(variable, sub.get(variable))); @@ -121,7 +123,7 @@ public Node value(VariableNode v) { } public Substitutions insert(Binding m) { - HashSubstitution s = new HashSubstitution(); + HashSubstitutions s = new HashSubstitutions(); s.insert(this); s.putIn(m); return s; @@ -182,11 +184,17 @@ public int termID(int variableID) { @Override public void insertOrUpdate(Binding mb) { - if (sub.containsKey(mb.getVariable())) - update(getBindingByVariable(mb.getVariable()), mb.getNode()); + if (sub.containsKey(mb.getVariableNode())) + update(getBindingByVariable(mb.getVariableNode()), mb.getNode()); else putIn(mb); } + @Override + public VariableNodeStats extractBoundStatus(VariableSet freeVariables) { + // TODO Auto-generated method stub + return null; + } + } \ No newline at end of file diff --git a/src/sneps/snip/matching/LinearSubstitutions.java b/src/sneps/snip/matching/LinearSubstitutions.java index 4d5ea847..8891fb8a 100644 --- a/src/sneps/snip/matching/LinearSubstitutions.java +++ b/src/sneps/snip/matching/LinearSubstitutions.java @@ -472,14 +472,20 @@ public VariableNodeStats extractBoundStatus(VariableSet freeVariables) { boolean bindingFound = false; Variable bindingVariable = (Variable) bindingVariableNode.getTerm(); for (Variable variable : freeVariables) - bindingFound |= variable.equals(bindingVariable); + bindingFound |= variable.getIdentifier().equals(bindingVariable.getIdentifier()); if (bindingFound) extractedFilterRelevantToVariables.add(binding); forAllCondition &= bindingFound; } Substitutions extractedFilterSubs = new LinearSubstitutions(extractedFilterRelevantToVariables); return new VariableNodeStats(forAllCondition, extractedFilterSubs, this); + } + @Override + public boolean equals(Object obj) { + if (obj instanceof LinearSubstitutions) + return isEqual((Substitutions) obj); + return false; } } \ No newline at end of file diff --git a/src/sneps/snip/matching/Substitutions.java b/src/sneps/snip/matching/Substitutions.java index 0ee95a7e..eca74d7e 100644 --- a/src/sneps/snip/matching/Substitutions.java +++ b/src/sneps/snip/matching/Substitutions.java @@ -59,6 +59,8 @@ public interface Substitutions { public void insert(Substitutions s); + public boolean equals(Object obj); + public boolean sub(String x, String y); public String toString(); From 21749617ae7632ddea0d12f73abbfa67cbd137c1 Mon Sep 17 00:00:00 2001 From: Youssef Date: Mon, 20 May 2019 08:07:37 +0200 Subject: [PATCH 16/22] minor modifications to Channel and Match classes --- src/sneps/snip/channels/Channel.java | 2 +- src/sneps/snip/matching/Match.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index f340cf96..929c50bc 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -53,7 +53,7 @@ public void setFilter(Filter filter) { } public boolean testReportToSend(Report report) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { - boolean passTest = filter.canPass(report); // te be reviewed + boolean passTest = filter.canPass(report); // TODO te be reviewed Context channelContext = Controller.getContextByName(getContextName()); if (passTest && report.anySupportAssertedInContext(channelContext)) { System.out.println("\nThe switcher data:\n" + switcher); diff --git a/src/sneps/snip/matching/Match.java b/src/sneps/snip/matching/Match.java index a57f4d7d..0e71f027 100644 --- a/src/sneps/snip/matching/Match.java +++ b/src/sneps/snip/matching/Match.java @@ -1,6 +1,7 @@ package sneps.snip.matching; import sneps.network.Node; +import sneps.network.classes.setClasses.PropositionSet; public class Match { private Substitutions filterSubs; // whquestion atleastone free not bound @@ -10,7 +11,7 @@ public class Match { private Substitutions switchSubs; private Node node; private int matchType; - // add propset as support + private PropositionSet support; public Match(Substitutions filterSubs, Substitutions switchSubs, Node n, int type) { this.filterSubs = filterSubs; From 4d9d2605af36faa7e858784c5110268566d12c93 Mon Sep 17 00:00:00 2001 From: Youssef Date: Thu, 23 May 2019 18:58:12 +0200 Subject: [PATCH 17/22] renamed ReportInstances to KnownInstances and finalized report processing in Rule Node --- src/sneps/gui/FXController.java | 4 +- src/sneps/network/PropositionNode.java | 38 ++++--- src/sneps/network/RuleNode.java | 107 ++++++++++++------ .../network/classes/setClasses/ReportSet.java | 4 + ...portInstances.java => KnownInstances.java} | 4 +- src/sneps/snip/Report.java | 4 +- src/sneps/snip/channels/Channel.java | 3 +- 7 files changed, 103 insertions(+), 61 deletions(-) rename src/sneps/snip/{ReportInstances.java => KnownInstances.java} (91%) diff --git a/src/sneps/gui/FXController.java b/src/sneps/gui/FXController.java index 442305b4..47b07ef3 100644 --- a/src/sneps/gui/FXController.java +++ b/src/sneps/gui/FXController.java @@ -112,7 +112,7 @@ import sneps.snebr.Controller; import sneps.snepslog.AP; import sneps.snip.Report; -import sneps.snip.ReportInstances; +import sneps.snip.KnownInstances; public class FXController implements Initializable { Network network = new Network(); @@ -3631,7 +3631,7 @@ public void deduce() { // n = Network.buildTemporaryNode(identifier, ); } n.deduce(); - ReportInstances rs = n.getKnownInstances(); + KnownInstances rs = n.getKnownInstances(); for (Report r : rs) { res = res + r.toString() + "\n"; } diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 4311648a..3f8bc855 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -32,7 +32,7 @@ import sneps.snip.InferenceTypes; import sneps.snip.Pair; import sneps.snip.Report; -import sneps.snip.ReportInstances; +import sneps.snip.KnownInstances; import sneps.snip.Runner; import sneps.snip.channels.AntecedentToRuleChannel; import sneps.snip.channels.Channel; @@ -49,20 +49,20 @@ public class PropositionNode extends Node implements Serializable { private Support basicSupport; protected ChannelSet outgoingChannels; protected ChannelSet incomingChannels; - protected ReportInstances knownInstances; + protected KnownInstances knownInstances; protected ReportSet newInstances; public PropositionNode() { outgoingChannels = new ChannelSet(); incomingChannels = new ChannelSet(); - knownInstances = new ReportInstances(); + knownInstances = new KnownInstances(); } public PropositionNode(Term trm) { super(Semantic.proposition, trm); outgoingChannels = new ChannelSet(); incomingChannels = new ChannelSet(); - knownInstances = new ReportInstances(); + knownInstances = new KnownInstances(); setTerm(trm); } @@ -444,11 +444,11 @@ public void setIncomingChannels(ChannelSet incomingChannels) { this.incomingChannels = incomingChannels; } - public ReportInstances getKnownInstances() { + public KnownInstances getKnownInstances() { return knownInstances; } - public void setKnownInstances(ReportInstances knownInstances) { + public void setKnownInstances(KnownInstances knownInstances) { this.knownInstances = knownInstances; } @@ -710,8 +710,7 @@ protected void processSingleRequestsChannel(Channel currentChannel) if (!sentAtLeastOne || isWhQuestion(filterSubs)) { NodeSet dominatingRules = getUpConsNodeSet(); NodeSet toBeSentToDom = removeAlreadyWorkingOn(dominatingRules, currentChannel, filterSubs, false); - sendRequestsToNodeSet(toBeSentToDom, new LinearSubstitutions(), currentContextName, - ChannelTypes.RuleAnt); + sendRequestsToNodeSet(toBeSentToDom, filterSubs, currentContextName, ChannelTypes.RuleAnt); if (!(currentChannel instanceof MatchChannel)) { List matchingNodes = Matcher.match(this); List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel); @@ -751,17 +750,22 @@ protected void processSingleReportsChannel(Channel currentChannel) Report reportToBeBroadcasted = attemptAddingReportToKnownInstances(currentChannel, currentReport); if (reportToBeBroadcasted != null) { boolean forwardReportType = reportToBeBroadcasted.getInferenceType() == InferenceTypes.FORWARD; - PropositionNode supportNode = buildNodeSubstitutions(currentReport.getSubstitutions()); - supportNode.addJustificationBasedSupport(reportToBeBroadcasted.getSupport()); - PropositionSet reportSupportPropSet = new PropositionSet(); - reportSupportPropSet.add(supportNode.getId()); - reportToBeBroadcasted.setSupport(reportSupportPropSet); + if (currentChannel instanceof RuleToConsequentChannel) { + PropositionNode supportNode = buildNodeSubstitutions(currentReport.getSubstitutions()); + supportNode.addJustificationBasedSupport(reportToBeBroadcasted.getSupport()); + PropositionSet reportSupportPropSet = new PropositionSet(); + reportSupportPropSet.add(supportNode.getId()); + reportToBeBroadcasted.setSupport(reportSupportPropSet); + } // TODO: GRADED PROPOSITIONS HANDLING REPORTS if (forwardReportType) { - List matchesReturned = Matcher.match(this); - sendReportToMatches(matchesReturned, currentReport, currentChannelContextName); - NodeSet isAntecedentTo = getUpAntNodeSet(); - sendReportToNodeSet(isAntecedentTo, currentReport, currentChannelContextName, ChannelTypes.RuleAnt); + if (currentChannel instanceof MatchChannel) { + List matchesReturned = Matcher.match(this); + sendReportToMatches(matchesReturned, currentReport, currentChannelContextName); + } + NodeSet dominatingRules = getUpAntNodeSet(); + sendReportToNodeSet(dominatingRules, currentReport, currentChannelContextName, + ChannelTypes.RuleAnt); } else broadcastReport(reportToBeBroadcasted); diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index e526dfd6..b8d3c5e6 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -32,7 +32,7 @@ import sneps.snip.Filter; import sneps.snip.InferenceTypes; import sneps.snip.Report; -import sneps.snip.ReportInstances; +import sneps.snip.KnownInstances; import sneps.snip.Runner; import sneps.snip.channels.AntecedentToRuleChannel; import sneps.snip.channels.Channel; @@ -46,6 +46,8 @@ import sneps.snip.classes.VariableNodeStats; import sneps.snip.matching.Binding; import sneps.snip.matching.LinearSubstitutions; +import sneps.snip.matching.Match; +import sneps.snip.matching.Matcher; import sneps.snip.matching.Substitutions; import sneps.snip.rules.AndOrNode; import sneps.snip.rules.ThreshNode; @@ -279,10 +281,10 @@ protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel, boo if (removeSender) antecedentsNodeSet.removeNode(currentChannel.getRequester()); boolean ruleType = this instanceof ThreshNode || this instanceof AndOrNode; + String currentContextName = currentChannel.getContextName(); Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentsNodeSet, currentChannel, filterSubs, ruleType); - sendRequestsToNodeSet(toBeSentTo, currentChannel.getFilter().getSubstitutions(), - currentChannel.getContextName(), ChannelTypes.RuleAnt); + sendRequestsToNodeSet(toBeSentTo, filterSubs, currentContextName, ChannelTypes.RuleAnt); } /*** @@ -295,11 +297,21 @@ protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel, boo protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel, Report report) { NodeSet antecedentNodeSet = getDownAntNodeSet(); boolean ruleType = this instanceof ThreshNode || this instanceof AndOrNode; + String currentContextName = currentChannel.getContextName(); Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); Substitutions reportSubs = report.getSubstitutions(); Substitutions unionSubs = filterSubs.union(reportSubs); NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentNodeSet, currentChannel, unionSubs, ruleType); - sendRequestsToNodeSet(toBeSentTo, unionSubs, currentChannel.getContextName(), ChannelTypes.RuleAnt); + sendRequestsToNodeSet(toBeSentTo, unionSubs, currentContextName, ChannelTypes.RuleAnt); + } + + protected void requestAntecedentsNotAlreadyWorkingOn(Channel currentChannel, Report report, boolean removeSender) { + NodeSet antecedentNodeSet = getDownAntNodeSet(); + boolean ruleType = this instanceof ThreshNode || this instanceof AndOrNode; + String currentContextName = currentChannel.getContextName(); + Substitutions reportSubs = report.getSubstitutions(); + NodeSet toBeSentTo = removeAlreadyWorkingOn(antecedentNodeSet, currentChannel, reportSubs, ruleType); + sendRequestsToNodeSet(toBeSentTo, reportSubs, currentContextName, ChannelTypes.RuleAnt); } /* @@ -392,11 +404,10 @@ protected void processSingleRequestsChannel(Channel currentChannel) if (currentChannel instanceof RuleToConsequentChannel) { boolean closedTypeTerm = term instanceof Closed; String currentContextName = currentChannel.getContextName(); - Context currentContext = Controller.getContextByName(currentContextName); Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); if (closedTypeTerm) { /* Case 1 */ - if (assertedInContext(currentContext)) { + if (assertedInContext(currentContextName)) { requestAntecedentsNotAlreadyWorkingOn(currentChannel, false); } else super.processSingleRequestsChannel(currentChannel); @@ -405,11 +416,11 @@ protected void processSingleRequestsChannel(Channel currentChannel) boolean ruleNodeAllVariablesBound = ruleNodeStats.areAllVariablesBound(); Substitutions ruleNodeExtractedSubs = ruleNodeStats.getVariableNodeSubs(); /* Case 2 & 3 */ - ReportInstances knownReportSet = knownInstances; + KnownInstances knownReportSet = knownInstances; for (Report report : knownReportSet) { Substitutions reportSubstitutions = report.getSubstitutions(); boolean subSetCheck = ruleNodeExtractedSubs.isSubSet(reportSubstitutions); - boolean supportCheck = report.anySupportAssertedInContext(currentContext); + boolean supportCheck = report.anySupportAssertedInContext(currentContextName); if (subSetCheck && supportCheck) { if (ruleNodeAllVariablesBound) { requestAntecedentsNotAlreadyWorkingOn(currentChannel, false); @@ -464,25 +475,55 @@ protected void processSingleReportsChannel(Channel currentChannel) Collection ruleResponse = applyRuleHandler(currentReport, currentChannel); handleResponseOfApplyRuleHandler(ruleResponse, currentReport, currentChannel); currentChannelReportBuffer.removeReport(currentReport); - /* requests the antecedents, applyRuleHandler(), remove report from buffer */ - // DONE Close Type - Asserted through Forward Inference } else { - /* try to assert myself through requests and leave the report fel buffer */ - // TODO Close Type - Not Asserted through Forward Inference + NodeSet dominatingRules = getUpConsNodeSet(); + NodeSet toBeSentToDom = removeAlreadyWorkingOn(dominatingRules, currentChannel, + currentReportSubs, false); + sendRequestsToNodeSet(toBeSentToDom, currentReportSubs, currentChannelContextName, + ChannelTypes.RuleAnt); + List matchingNodes = Matcher.match(this); + List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel); + sendRequestsToMatches(toBeSentToMatch, currentChannelContextName); } } else { /** Open Type Implementation */ /* - * for every known instance compatible with the report, send requests to the - * rest of the antecedents gheir el ba3at el report and apply rule handler and - * not remove the report from the reports buffer + * for every known instance compatible (el free variables el fel rule hntala3 el + * bindings beta3thom fel report we necheck law dah subset men had men el known + * instance ; use variablenodestats) with the report, if(zay belzabt el check + * beta3 el subset wel support el fe requests)send requests to the rest of the + * antecedents gheir el ba3at el report and apply rule handler and not remove + * the report from the reports buffer, try to assert */ + /* + * le kol known instance hanla2ih hnt3amel ma3 el node ka2enaha asserted we + * closed + */ + VariableNodeStats ruleNodeStats = computeNodeStats(currentReportSubs); + Substitutions ruleNodeExtractedSubs = ruleNodeStats.getVariableNodeSubs(); + for (Report knownInstance : knownInstances) { + Substitutions knownInstanceSubstitutions = knownInstance.getSubstitutions(); + boolean subSetCheck = ruleNodeExtractedSubs.isSubSet(knownInstanceSubstitutions); + boolean supportCheck = knownInstance.anySupportAssertedInContext(currentChannelContextName); + if (subSetCheck && supportCheck) { + requestAntecedentsNotAlreadyWorkingOn(currentChannel, knownInstance, true); + Collection ruleResponse = applyRuleHandler(knownInstance, currentChannel); + handleResponseOfApplyRuleHandler(ruleResponse, knownInstance, currentChannel); + } + } Collection ruleResponse = applyRuleHandler(currentReport, currentChannel); handleResponseOfApplyRuleHandler(ruleResponse, currentReport, currentChannel); - Channel newChannel = ((AntecedentToRuleChannel) currentChannel).clone(); - Filter newChannelSubs = new Filter(currentReportSubs); - newChannel.setFilter(newChannelSubs); - super.processSingleRequestsChannel(newChannel); + NodeSet dominatingRules = getUpConsNodeSet(); + NodeSet toBeSentToDom = removeAlreadyWorkingOn(dominatingRules, currentChannel, + currentReportSubs, false); + sendRequestsToNodeSet(toBeSentToDom, currentReportSubs, currentChannelContextName, + ChannelTypes.RuleAnt); + List matchingNodes = Matcher.match(this); + List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel); + sendRequestsToMatches(toBeSentToMatch, currentChannelContextName); + /* + * zeyada 3aleiha hnkamel akenaha mesh asserted el heya open + */ } } else { /** Backward Inference */ @@ -492,32 +533,24 @@ protected void processSingleReportsChannel(Channel currentChannel) } } else { /** Not AntecedentToRule Channel */ - - /* - * Nafs el bt3mlo lel proposition node without removing the report from the - * buffer if. forward type: send requests to all antecedents - */ super.processSingleReportsChannel(currentChannel); - ChannelSet outgoingChannels = getOutgoingChannels(); - ChannelSet incomingChannels = getIncomingChannels(); - if (forwardReportType) { - if (closedTypeTerm) { + if (closedTypeTerm) Runner.addNodeAssertionThroughFReport(currentReport, this); - getNodesToSendRequest(ChannelTypes.RuleAnt, currentChannelContextName, currentReportSubs); - // 3alashan el rule got asserted be forward inference we lazem acheck el - // antecedents by3arfo yereport wala la2 - } + getNodesToSendRequest(ChannelTypes.RuleAnt, currentChannelContextName, currentReportSubs); } else { - if (!outgoingChannels.getChannels().isEmpty()) + Collection outgoingChannels = getOutgoingChannels().getChannels(); + Collection incomingChannels = getIncomingChannels().getAntRuleChannels(); + boolean existsReportBuffers = false; + for (Channel incomingChannel : incomingChannels) { + existsReportBuffers |= !incomingChannel.getReportsBuffer().isEmpty(); + } + if (!outgoingChannels.isEmpty()) receiveRequest(currentChannel); - if (!incomingChannels.getChannels().isEmpty() && true /* non empty buffers */) + if (!incomingChannels.isEmpty() && existsReportBuffers) receiveReport(currentChannel); - // law fih outgoing channels -> low queue - // law fih incoming channels and non empty buffers -> queue high currentChannelReportBuffer.removeReport(currentReport); } - } } } diff --git a/src/sneps/network/classes/setClasses/ReportSet.java b/src/sneps/network/classes/setClasses/ReportSet.java index 2dcd415b..268238c2 100644 --- a/src/sneps/network/classes/setClasses/ReportSet.java +++ b/src/sneps/network/classes/setClasses/ReportSet.java @@ -34,4 +34,8 @@ public boolean removeReport(Report report) { return reports.remove(report); } + public boolean isEmpty() { + return reports.size() == 0; + } + } diff --git a/src/sneps/snip/ReportInstances.java b/src/sneps/snip/KnownInstances.java similarity index 91% rename from src/sneps/snip/ReportInstances.java rename to src/sneps/snip/KnownInstances.java index 1f17b88c..3de754ef 100644 --- a/src/sneps/snip/ReportInstances.java +++ b/src/sneps/snip/KnownInstances.java @@ -9,10 +9,10 @@ import sneps.snip.channels.Channel; import sneps.snip.matching.Substitutions; -public class ReportInstances implements Iterable { +public class KnownInstances implements Iterable { Hashtable> instances; - public ReportInstances() { + public KnownInstances() { instances = new Hashtable>(); } diff --git a/src/sneps/snip/Report.java b/src/sneps/snip/Report.java index 9e5d5c64..c8cbe33f 100644 --- a/src/sneps/snip/Report.java +++ b/src/sneps/snip/Report.java @@ -10,6 +10,7 @@ import sneps.network.PropositionNode; import sneps.network.classes.setClasses.PropositionSet; import sneps.snebr.Context; +import sneps.snebr.Controller; import sneps.snebr.Support; import sneps.snip.matching.Substitutions; @@ -45,8 +46,9 @@ public Report(Substitutions substitution, PropositionSet suppt, boolean sign, In * (assumptionHyps.isSubSet(contextHypothesisSet)) return true; return false; } */ - public boolean anySupportAssertedInContext(Context reportContext) + public boolean anySupportAssertedInContext(String reportContextName) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { + Context reportContext = Controller.getContextByName(reportContextName); int[] reportSupportsSet = support.getProps(); int currentPropNodeId; for (int i = 0; i < reportSupportsSet.length; i++) { diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index 929c50bc..afe9d08f 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -54,8 +54,7 @@ public void setFilter(Filter filter) { public boolean testReportToSend(Report report) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { boolean passTest = filter.canPass(report); // TODO te be reviewed - Context channelContext = Controller.getContextByName(getContextName()); - if (passTest && report.anySupportAssertedInContext(channelContext)) { + if (passTest && report.anySupportAssertedInContext(getContextName())) { System.out.println("\nThe switcher data:\n" + switcher); switcher.switchReport(report); PropositionNode requesterNode = (PropositionNode) getRequester(); From 20ed4ee679cc22febbcd6be2a4cbb4ce6c73b451 Mon Sep 17 00:00:00 2001 From: Youssef Date: Thu, 23 May 2019 19:06:41 +0200 Subject: [PATCH 18/22] added switch substitutions for the ChannelIdentifier class --- .../network/classes/setClasses/ChannelSet.java | 13 ++++++++----- src/sneps/snip/channels/ChannelIdentifier.java | 17 ++++++++++++++--- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/sneps/network/classes/setClasses/ChannelSet.java b/src/sneps/network/classes/setClasses/ChannelSet.java index c7698cad..7db179bf 100644 --- a/src/sneps/network/classes/setClasses/ChannelSet.java +++ b/src/sneps/network/classes/setClasses/ChannelSet.java @@ -26,11 +26,12 @@ public Channel addChannel(Channel channel) { int channelRequesterId = channel.getRequester().getId(); int channelReporterId = channel.getReporter().getId(); String channelContextName = channel.getContextName(); - Substitutions channelSubs = channel.getFilter().getSubstitutions(); + Substitutions filterSubs = channel.getFilter().getSubstitutions(); + Substitutions switchSubs = channel.getSwitch().getSubstitutions(); ChannelTypes channelType = getChannelType(channel); Hashtable targetSet = channels.remove(channelType); ChannelIdentifier channelId = new ChannelIdentifier(channelRequesterId, channelReporterId, channelContextName, - channelSubs); + filterSubs, switchSubs); Channel added = targetSet.put(channelId, channel); channels.put(channelType, targetSet); return added; @@ -40,11 +41,12 @@ public Channel removeChannel(Channel channel) { int channelRequesterId = channel.getRequester().getId(); int channelReporterId = channel.getReporter().getId(); String channelContextName = channel.getContextName(); - Substitutions channelSubs = channel.getFilter().getSubstitutions(); + Substitutions filterSubs = channel.getFilter().getSubstitutions(); + Substitutions switchSubs = channel.getSwitch().getSubstitutions(); ChannelTypes channelType = getChannelType(channel); Hashtable targetSet = channels.remove(channelType); ChannelIdentifier channelId = new ChannelIdentifier(channelRequesterId, channelReporterId, channelContextName, - channelSubs); + filterSubs, switchSubs); Channel removed = targetSet.remove(channelId); channels.put(channelType, targetSet); return removed; @@ -138,8 +140,9 @@ public Channel getChannel(Channel newChannel) { int channelReporterId = newChannel.getReporter().getId(); String channelContextName = newChannel.getContextName(); Substitutions channelSubs = newChannel.getFilter().getSubstitutions(); + Substitutions switchSubs = newChannel.getSwitch().getSubstitutions(); ChannelIdentifier channelId = new ChannelIdentifier(channelRequesterId, channelReporterId, channelContextName, - channelSubs); + channelSubs, switchSubs); ChannelTypes channelType = getChannelType(newChannel); Hashtable set = channels.get(channelType); return set.get(channelId); diff --git a/src/sneps/snip/channels/ChannelIdentifier.java b/src/sneps/snip/channels/ChannelIdentifier.java index c2374e50..9019e0c9 100644 --- a/src/sneps/snip/channels/ChannelIdentifier.java +++ b/src/sneps/snip/channels/ChannelIdentifier.java @@ -7,12 +7,14 @@ public class ChannelIdentifier { int reporterId; String contextName; Substitutions filterSubstitutions; + Substitutions switchSubstitutions; - public ChannelIdentifier(int rqId, int rpId, String cName, Substitutions fSubs) { + public ChannelIdentifier(int rqId, int rpId, String cName, Substitutions fSubs, Substitutions sSubs) { requesterId = rqId; reporterId = rpId; contextName = cName; filterSubstitutions = fSubs; + switchSubstitutions = sSubs; } @Override @@ -20,11 +22,12 @@ public boolean equals(Object obj) { ChannelIdentifier channelId; if (obj instanceof ChannelIdentifier) { channelId = (ChannelIdentifier) obj; - boolean filterCheck = filterSubstitutions.equals(channelId.getFilterSubstitutions()); boolean requesterCheck = getRequesterId() == channelId.getRequesterId(); boolean reporterCheck = getReporterId() == channelId.getReporterId(); boolean contextCheck = getContextName() == channelId.getContextName(); - return filterCheck && reporterCheck && requesterCheck && contextCheck; + boolean filterCheck = filterSubstitutions.equals(channelId.getFilterSubstitutions()); + boolean switchCheck = switchSubstitutions.equals(channelId.getSwitchSubstitutions()); + return reporterCheck && requesterCheck && contextCheck && filterCheck && switchCheck; } return false; } @@ -61,4 +64,12 @@ public void setFilterSubstitutions(Substitutions filterSubstitutions) { this.filterSubstitutions = filterSubstitutions; } + public Substitutions getSwitchSubstitutions() { + return switchSubstitutions; + } + + public void setSwitchSubstitutions(Substitutions switchSubstututions) { + this.switchSubstitutions = switchSubstututions; + } + } From b2bb841f28354ad8d4e13eda2b45becfb176d02c Mon Sep 17 00:00:00 2001 From: Youssef Date: Mon, 27 May 2019 15:15:00 +0200 Subject: [PATCH 19/22] added another match method and initiated test methods --- src/sneps/network/Network.java | 466 ++++++++---------- src/sneps/network/PropositionNode.java | 9 +- src/sneps/network/RuleNode.java | 14 +- .../classes/setClasses/ChannelSet.java | 3 + .../network/classes/setClasses/ReportSet.java | 9 + src/sneps/snepslog/AP.java | 169 +++---- src/sneps/snip/Runner.java | 4 + src/sneps/snip/Test.java | 73 +++ src/sneps/snip/matching/Matcher.java | 58 ++- tests/SnipTest.java | 271 ++++++++++ 10 files changed, 699 insertions(+), 377 deletions(-) create mode 100644 src/sneps/snip/Test.java create mode 100644 tests/SnipTest.java diff --git a/src/sneps/network/Network.java b/src/sneps/network/Network.java index 23368a59..1f001ee8 100644 --- a/src/sneps/network/Network.java +++ b/src/sneps/network/Network.java @@ -226,12 +226,11 @@ public static LinkedList getUserDefinedVarSuffix() { /** * - * @param name - * the name of the relation that will be retrieved. + * @param name the name of the relation that will be retrieved. * * @return the relation with the specified name if it exists. - * @throws RelationDoesntExistException - * if the requested relation does not exist. + * @throws RelationDoesntExistException if the requested relation does not + * exist. */ public static Relation getRelation(String name) throws RelationDoesntExistException { if (relations.containsKey(name)) { @@ -243,13 +242,12 @@ public static Relation getRelation(String name) throws RelationDoesntExistExcept /** * - * @param id - * the string id of the case frame that will be retrieved. + * @param id the string id of the case frame that will be retrieved. * * @return the case frame with the specified id if it exists. * - * @throws CaseFrameWithSetOfRelationsNotFoundException - * if the requested frame does not exist. + * @throws CaseFrameWithSetOfRelationsNotFoundException if the requested frame + * does not exist. */ public static CaseFrame getCaseFrame(String id) throws CaseFrameWithSetOfRelationsNotFoundException { if (caseFrames.containsKey(id)) { @@ -262,13 +260,11 @@ public static CaseFrame getCaseFrame(String id) throws CaseFrameWithSetOfRelatio /** * - * @param identifier - * the name of the node that will be retrieved. + * @param identifier the name of the node that will be retrieved. * * @return the node with the specified name if it exists. * - * @throws NodeNotFoundInNetworkException - * if the requested node does not exist. + * @throws NodeNotFoundInNetworkException if the requested node does not exist. */ public static Node getNode(String identifier) throws NodeNotFoundInNetworkException { if (nodes.containsKey(identifier)) { @@ -289,22 +285,17 @@ public static Node getNodeById(int id) throws NodeNotFoundInNetworkException { /** * This method is used to define a new relation in the network. * - * @param name - * the name of the new relation. - * @param type - * the name of the semantic class that specify the semantic of the - * nodes that this new relation can point to. - * @param adjust - * the adjustability of the new relation. - * @param limit - * the minimum number of nodes that this new relation can point to - * within a down-cable. + * @param name the name of the new relation. + * @param type the name of the semantic class that specify the semantic of the + * nodes that this new relation can point to. + * @param adjust the adjustability of the new relation. + * @param limit the minimum number of nodes that this new relation can point to + * within a down-cable. * * @return the newly created relation. * - * @throws CustomException - * if another relation with the same given name is already defined - * in the network. + * @throws CustomException if another relation with the same given name is + * already defined in the network. */ public static Relation defineRelation(String name, String type, String adjust, int limit) { if (relations.containsKey(name)) { @@ -331,11 +322,10 @@ public static Relation defineRelation(String name, String type) { /** * This method is used to delete a relation from the network. * - * @param name - * the name of the relation that will be deleted. - * @throws CaseFrameCannotBeRemovedException - * if the relation cannot be removed because one of the case frames - * that contains it cannot be removed. + * @param name the name of the relation that will be deleted. + * @throws CaseFrameCannotBeRemovedException if the relation cannot be removed + * because one of the case frames that + * contains it cannot be removed. */ public static void undefineRelation(String name) throws CaseFrameCannotBeRemovedException { Relation r = relations.get(name); @@ -359,11 +349,10 @@ public static void undefineRelation(String name) throws CaseFrameCannotBeRemoved /** * This method is used to define a new case frame. * - * @param semanticType - * the default semantic type specified by the new case frame. - * @param relationSet - * the list that contains the RCFP's of the relations included in the - * new case frame. + * @param semanticType the default semantic type specified by the new case + * frame. + * @param relationSet the list that contains the RCFP's of the relations + * included in the new case frame. * * @return the newly created case frame. * @@ -399,13 +388,12 @@ public static CaseFrame defineCaseFrame(String semanticType, LinkedList wires, CaseFrame caseFrame) throws CannotBuildNodeException, - EquivalentNodeException, NotAPropositionNodeException, NodeNotFoundInNetworkException { + public static Node buildMolecularNode(ArrayList wires, CaseFrame caseFrame) + throws CannotBuildNodeException, EquivalentNodeException, NotAPropositionNodeException, + NodeNotFoundInNetworkException, CaseFrameMissMatchException { Object[][] array = turnWiresIntoArray(wires); - Object[] result = downCableSetExists(array); + // this node is either null, or an equivalent node to the one this method is + // tryin to build + // if an equivalent node is found, it is returned and no new node is built. + Node equivalentNodeInNetwork = downCableSetExists(array); // System.out.println("Downcable set exists > "+ downCableSetExists(array)); - if (((Boolean) result[0] == true) && (result[1] == null)) { - // TODO Look for that node and return it - return null; - } - - if (((Boolean) result[0] == true) && (result[1] != null)) { - throw new EquivalentNodeException("The equivalent node '" + "' was used instead", (Node) result[1]); + if (equivalentNodeInNetwork != null) { + return equivalentNodeInNetwork; } - // check the validity of the relation-node pairs // System.out.println("done 1st"); if (!validRelNodePairs(array)) @@ -669,7 +648,9 @@ public static Node buildMolecularNode(ArrayList wires, CaseFrame caseFrame // System.out.println("done 2nd"); Object[][] relNodeSet = turnIntoRelNodeSet(array); // check that the down cable set is following the case frame - // System.out.println("done 3rd"); + if (!followingCaseFrame(relNodeSet, caseFrame)) + throw new CaseFrameMissMatchException( + "Not following the case frame .. wrong node set size or wrong set of relations"); // create the Molecular Node if (caseFrame.getSemanticClass().equals("Proposition")) { PropositionNode propNode; @@ -708,16 +689,14 @@ public static Node buildMolecularNode(ArrayList wires, RelationsRestricted throws CannotBuildNodeException, EquivalentNodeException, CaseFrameMissMatchException, NotAPropositionNodeException, NodeNotFoundInNetworkException { Object[][] array = turnWiresIntoArray(wires); - Object[] result = downCableSetExists(array); + // this node is either null, or an equivalent node to the one this method is + // tryin to build + // if an equivalent node is found, it is returned and no new node is built. + Node equivalentNodeInNetwork = downCableSetExists(array); // System.out.println("Downcable set exists > "+ downCableSetExists(array)); - if (((Boolean) result[0] == true) && (result[1] == null)) { - // TODO Look for that node and return it - return null; - } - if (((Boolean) result[0] == true) && (result[1] != null)) { - throw new EquivalentNodeException( - "The equivalent node '" + ((Node) result[1]).toString() + "' was used instead", (Node) result[1]); + if (equivalentNodeInNetwork != null) { + return equivalentNodeInNetwork; } // check the validity of the relation-node pairs // System.out.println("done 1st"); @@ -767,16 +746,16 @@ public static Node buildMolecularNode(ArrayList wires, RelationsRestricted /** * checks whether the given down cable set already exists in the network or not. * - * @param array - * a 2D array of Relation-Node pairs representing a down cable set - * specifications. + * @param array a 2D array of Relation-Node pairs representing a down cable set + * specifications. * - * @return true if the down cable set exists, and false otherwise + * @return the node that has this DownCableSet if it is found, or the node that + * has an equivalent DownCableSet if it is found. Returns null otherwise */ - private static Object[] downCableSetExists(Object[][] array) { + private static Node downCableSetExists(Object[][] array) { int size = 0; - Object[] result = new Object[2]; + boolean result = false; boolean newBoundVarsExist = false; boolean networkBoundVarsExist = false; boolean[] newFlags = new boolean[array.length]; @@ -871,33 +850,25 @@ private static Object[] downCableSetExists(Object[][] array) { } if (ns.size() == 1) { - result[0] = (Boolean) true; - result[1] = null; - - if ((newBoundVarsExist) && (networkBoundVarsExist)) { - Object[] s = ns.get(0); - result[1] = (Node) s[0]; - } + result = true; if ((newBoundVarsExist) && (!networkBoundVarsExist)) { - result[0] = (Boolean) false; + result = false; ns.remove(); } } else { - result[0] = (Boolean) false; - result[1] = null; + result = false; } - if ((ns.size() == 1) && ((Boolean) result[0] == false)) { - // System.out.println("Downcable set already exist"); - } - if (!(ns.size() == 1)) { - // System.out.println("Molecular Node built successfully"); + if (result) { + // if given DownCableSet exists within the network, return the node that this + // DownCableSet belongs to + return (Node) ns.get(0)[0]; + } else { + return null; } - return result; - } /** @@ -907,9 +878,8 @@ private static Object[] downCableSetExists(Object[][] array) { * implementation any relation can point to the variable node because all nodes * have infimum as their semantic type. * - * @param array - * a 2D array of Relation-Node pairs that represents the - * specifications of the down cable set of a new molecular node. + * @param array a 2D array of Relation-Node pairs that represents the + * specifications of the down cable set of a new molecular node. * * @return true if each pair in the 2D array is valid, and false otherwise. */ @@ -1017,14 +987,32 @@ private static boolean followingCaseFrame(Object[][] array, RelationsRestrictedC return true; } + private static boolean followingCaseFrame(Object[][] array, CaseFrame caseFrame) { + LinkedList list = caseFrame.getRelations(); + for (int i = 0; i < array.length; i++) { + Relation r = (Relation) array[i][0]; + if (list.contains(r)) { + if (((NodeSet) array[i][1]).size() >= r.getLimit()) { + list.remove(r); + } else { + return false; + } + } else { + return false; + } + } + if (!list.isEmpty()) + return false; + return true; + } + /** * This method examines the down cable set of a certain molecular node to check * whether it dominate free variables or not. Pattern nodes dominate free * variables while closed nodes do not dominate free variables. * - * @param array - * a 2D array of Relation-Node pairs that represents the - * specifications of the down cable set of the new molecular node. + * @param array a 2D array of Relation-Node pairs that represents the + * specifications of the down cable set of the new molecular node. * * @return true if the node dominates free variable and thus should be pattern * node, and false otherwise. @@ -1063,17 +1051,15 @@ private static boolean isToBePattern(Object[][] array) { * This method builds a new pattern node or proposition node with the given down * cable set specifications and case frame. * - * @param relNodeSet - * a 2D array of relation-nodeSet pairs that represents the down - * cable set of the new pattern or proposition node. - * @param caseFrame - * the case frame implemented by the new pattern or proposition node. + * @param relNodeSet a 2D array of relation-nodeSet pairs that represents the + * down cable set of the new pattern or proposition node. + * @param caseFrame the case frame implemented by the new pattern or + * proposition node. * * @return the newly created pattern node or proposition node. * - * @throws Exception - * if the semantic class specified by the case frame was not - * successfully created and thus the node was not built. + * @throws Exception if the semantic class specified by the case frame was not + * successfully created and thus the node was not built. */ @SuppressWarnings("rawtypes") private static Node createPatNode(Object[][] relNodeSet, CaseFrame caseFrame) { @@ -1161,17 +1147,15 @@ else if (caseFrame == RelationsRestrictedCaseFrame.whenDo) * set specifications and case frame. * * - * @param relNodeSet - * a 2D array of relation-nodeSet pairs that represents the down - * cable set of the new closed or proposition node. - * @param caseFrame - * the case frame implemented by the new closed or proposition node. + * @param relNodeSet a 2D array of relation-nodeSet pairs that represents the + * down cable set of the new closed or proposition node. + * @param caseFrame the case frame implemented by the new closed or proposition + * node. * * @return the newly created closed or proposition node. * - * @throws Exception - * if the semantic class specified by the case frame was not - * successfully created and thus the node was not built. + * @throws Exception if the semantic class specified by the case frame was not + * successfully created and thus the node was not built. */ @SuppressWarnings("rawtypes") private static Node createClosedNode(Object[][] relNodeSet, CaseFrame caseFrame) { @@ -1252,9 +1236,8 @@ private static Node createClosedNode(Object[][] relNodeSet, RelationsRestrictedC * the key and and the node set that contains the nodes pointed to by the * corresponding relation as the value. * - * @param relNodeSet - * a given 2D array of relation-nodeSet pairs that will be used to - * create the hash table + * @param relNodeSet a given 2D array of relation-nodeSet pairs that will be + * used to create the hash table * * @return the newly created hash table. */ @@ -1270,12 +1253,10 @@ public static Hashtable turnIntoHashtable(Object[][] relNodeSet * This method gets the case frame signature specified by the case frame based * on the down cable set of a certain node. * - * @param relNodeSet - * a hash table with entry having the relation name as the key and - * the node set of nodes pointed to by the corresponding relation as - * the value. - * @param caseframe - * a given case frame. + * @param relNodeSet a hash table with entry having the relation name as the key + * and the node set of nodes pointed to by the corresponding + * relation as the value. + * @param caseframe a given case frame. * * @return the (case frame signature) semantic type specified by the given case * frame based on the given down cable set specifications. @@ -1341,10 +1322,8 @@ public static String getCFSignature(Hashtable relNodeSet, Relat } /** - * @param array - * a given 2D array that contains pairs of paths and node sets. - * @param context - * a given context. + * @param array a given 2D array that contains pairs of paths and node sets. + * @param context a given context. * * @return the node set of nodes that we can start following those paths in the * array from, in order to reach at least one node at each node set in @@ -1355,12 +1334,10 @@ public static LinkedList find(Object[][] array, Context context) { } /** - * @param array - * a given 2D array that contains pairs of paths and node sets. - * @param context - * a given context. - * @param index - * the index of the 2D array at which we should start traversing it. + * @param array a given 2D array that contains pairs of paths and node sets. + * @param context a given context. + * @param index the index of the 2D array at which we should start traversing + * it. * * @return the node set of nodes that we can start following those paths in the * array from, in order to reach at least one node of node sets at each @@ -1403,13 +1380,10 @@ private static LinkedList findIntersection(Object[][] array, Context c } /** - * @param path - * the path that can be followed to get to one of the nodes - * specified. - * @param nodeSet - * the nodes that can be reached by following the path. - * @param context - * a given context. + * @param path the path that can be followed to get to one of the nodes + * specified. + * @param nodeSet the nodes that can be reached by following the path. + * @param context a given context. * @return a node set of nodes that we can start following the path from in * order to get to one of the nodes in the specified node set. */ @@ -1439,14 +1413,12 @@ private static LinkedList findUnion(Path path, NodeSet nodeSet, Contex /** * This method builds a new case frame signature with the given parameters. * - * @param result - * the name of the semantic class specified by the new case frame - * signature. - * @param rules - * the list of sub-domain constraints included in the new case frame - * signature. - * @param caseframeId - * the case frame if that this CFSignature will be included in + * @param result the name of the semantic class specified by the new case + * frame signature. + * @param rules the list of sub-domain constraints included in the new + * case frame signature. + * @param caseframeId the case frame if that this CFSignature will be included + * in * * @return the newly created case frame signature. */ @@ -1458,15 +1430,12 @@ public CFSignature createCFSignature(String result, LinkedList findConstant(Object[][] array, Context contex } /** - * @param array - * the array that contains pairs of paths and node sets + * @param array the array that contains pairs of paths and node sets * @return the node set of base nodes that we can start following those paths in * the array from, in order to reach at least one node at each node set * in all entries of the array @@ -1895,8 +1848,7 @@ public static LinkedList findBase(Object[][] array, Context context) { } /** - * @param array - * the array that contains pairs of paths and node sets + * @param array the array that contains pairs of paths and node sets * @return the node set of variable nodes that we can start following those * paths in the array from, in order to reach at least one node at each * node set in all entries of the array @@ -1914,8 +1866,7 @@ public static LinkedList findVariable(Object[][] array, Context contex } /** - * @param array - * the array that contains pairs of paths and node sets + * @param array the array that contains pairs of paths and node sets * @return the node set of pattern nodes that we can start following those paths * in the array from, in order to reach at least one node at each node * set in all entries of the array @@ -1962,36 +1913,37 @@ public static void defineDefaults() { RCFP.createDefaultProperties(); Semantic.createDefaultSemantics(); RelationsRestrictedCaseFrame.createDefaultCaseFrames(); - //SNeBR.getContextSet().add(SNeBR.getCurrentContext()); - //ControlActionNode.initControlActions(); + // SNeBR.getContextSet().add(SNeBR.getCurrentContext()); + // ControlActionNode.initControlActions(); } - - public static void save(String relationsData, String caseFramesData, String nodesData, String molData, String mcd, String pcd, String vcd, String pNData, String nodesIndexData, String userDefinedMolSuffixData, String userDefinedPatSuffixData, String userDefinedVarSuffixData) throws IOException { + + public static void save(String relationsData, String caseFramesData, String nodesData, String molData, String mcd, + String pcd, String vcd, String pNData, String nodesIndexData, String userDefinedMolSuffixData, + String userDefinedPatSuffixData, String userDefinedVarSuffixData) throws IOException { ObjectOutputStream ros = new ObjectOutputStream(new FileOutputStream(new File(relationsData))); ros.writeObject(relations); ros.close(); - + ObjectOutputStream cFos = new ObjectOutputStream(new FileOutputStream(new File(caseFramesData))); cFos.writeObject(caseFrames); cFos.close(); - - + ObjectOutputStream nodesOS = new ObjectOutputStream(new FileOutputStream(new File(nodesData))); nodesOS.writeObject(nodes); nodesOS.close(); - + ObjectOutputStream molNodesOs = new ObjectOutputStream(new FileOutputStream(new File(molData))); molNodesOs.writeObject(molecularNodes); molNodesOs.close(); - + ObjectOutputStream mc = new ObjectOutputStream(new FileOutputStream(new File(mcd))); mc.writeObject(molCounter); mc.close(); - + ObjectOutputStream pc = new ObjectOutputStream(new FileOutputStream(new File(pcd))); pc.writeObject(patternCounter); pc.close(); - + ObjectOutputStream vc = new ObjectOutputStream(new FileOutputStream(new File(vcd))); vc.writeObject(varCounter); vc.close(); @@ -2016,35 +1968,35 @@ public static void save(String relationsData, String caseFramesData, String node udvs.writeObject(userDefinedVarSuffix); udvs.close(); } - + public static void saveNetworks() throws IOException { ObjectOutputStream networks = new ObjectOutputStream(new FileOutputStream(new File("Networks"))); networks.writeObject(savedNetworks); networks.close(); } - + public static void loadNetworks() throws FileNotFoundException, IOException, ClassNotFoundException { - ObjectInputStream ns= new ObjectInputStream(new FileInputStream(new File("Networks"))); + ObjectInputStream ns = new ObjectInputStream(new FileInputStream(new File("Networks"))); ArrayList temp = (ArrayList) ns.readObject(); Network.savedNetworks = temp; ns.close(); } - + public static ArrayList getSavedNetworks() { return savedNetworks; } public static boolean addToSavedNetworks(String n) { boolean r; - if(savedNetworks.contains(n)) { + if (savedNetworks.contains(n)) { r = false; - }else { + } else { savedNetworks.add(n); r = true; } return r; } - + public static void deleteFromSavedNetworks(String f) { savedNetworks.remove(f); try { @@ -2055,75 +2007,76 @@ public static void deleteFromSavedNetworks(String f) { } } - public static void load(String relationsData, String caseFramesData, String nodesData, String molData, String mcd, String pcd, String vcd, String pNData, String nodesIndexData, String userDefinedMolSuffixData, String userDefinedPatSuffixData, String userDefinedVarSuffixData) throws IOException, ClassNotFoundException { - ObjectInputStream ris= new ObjectInputStream(new FileInputStream(new File(relationsData))); + public static void load(String relationsData, String caseFramesData, String nodesData, String molData, String mcd, + String pcd, String vcd, String pNData, String nodesIndexData, String userDefinedMolSuffixData, + String userDefinedPatSuffixData, String userDefinedVarSuffixData) + throws IOException, ClassNotFoundException { + ObjectInputStream ris = new ObjectInputStream(new FileInputStream(new File(relationsData))); Hashtable tempRelations = (Hashtable) ris.readObject(); Network.relations = tempRelations; ris.close(); tempRelations = null; - - ObjectInputStream cFis= new ObjectInputStream(new FileInputStream(new File(caseFramesData))); + + ObjectInputStream cFis = new ObjectInputStream(new FileInputStream(new File(caseFramesData))); Hashtable tempcF = (Hashtable) cFis.readObject(); Network.caseFrames = tempcF; cFis.close(); tempcF = null; - - - ObjectInputStream nodesis= new ObjectInputStream(new FileInputStream(new File(nodesData))); + + ObjectInputStream nodesis = new ObjectInputStream(new FileInputStream(new File(nodesData))); Hashtable tempNodes = (Hashtable) nodesis.readObject(); Network.nodes = tempNodes; nodesis.close(); tempNodes = null; - - ObjectInputStream molNodesis= new ObjectInputStream(new FileInputStream(new File(molData))); + ObjectInputStream molNodesis = new ObjectInputStream(new FileInputStream(new File(molData))); Hashtable tempMolNodes = (Hashtable) molNodesis.readObject(); Network.molecularNodes = tempMolNodes; molNodesis.close(); tempMolNodes = null; - - ObjectInputStream mc= new ObjectInputStream(new FileInputStream(new File(mcd))); + + ObjectInputStream mc = new ObjectInputStream(new FileInputStream(new File(mcd))); int tempMC = (int) mc.readObject(); Network.molCounter = tempMC; mc.close(); - - ObjectInputStream pc= new ObjectInputStream(new FileInputStream(new File(pcd))); + + ObjectInputStream pc = new ObjectInputStream(new FileInputStream(new File(pcd))); int tempPC = (int) pc.readObject(); Network.patternCounter = tempPC; pc.close(); - - ObjectInputStream vc= new ObjectInputStream(new FileInputStream(new File(vcd))); + + ObjectInputStream vc = new ObjectInputStream(new FileInputStream(new File(vcd))); int tempVC = (int) vc.readObject(); Network.varCounter = tempVC; vc.close(); - ObjectInputStream pn= new ObjectInputStream(new FileInputStream(new File(pNData))); + ObjectInputStream pn = new ObjectInputStream(new FileInputStream(new File(pNData))); Hashtable temppn = (Hashtable) pn.readObject(); Network.propositionNodes = temppn; pn.close(); - ObjectInputStream niis= new ObjectInputStream(new FileInputStream(new File(nodesIndexData))); + ObjectInputStream niis = new ObjectInputStream(new FileInputStream(new File(nodesIndexData))); ArrayList tempni = (ArrayList) niis.readObject(); Network.nodesIndex = tempni; niis.close(); - ObjectInputStream udmsis= new ObjectInputStream(new FileInputStream(new File(userDefinedMolSuffixData))); + ObjectInputStream udmsis = new ObjectInputStream(new FileInputStream(new File(userDefinedMolSuffixData))); LinkedList tempudms = (LinkedList) udmsis.readObject(); Network.userDefinedMolSuffix = tempudms; udmsis.close(); - ObjectInputStream udpsis= new ObjectInputStream(new FileInputStream(new File(userDefinedPatSuffixData))); + ObjectInputStream udpsis = new ObjectInputStream(new FileInputStream(new File(userDefinedPatSuffixData))); LinkedList tempudps = (LinkedList) udpsis.readObject(); Network.userDefinedPatSuffix = tempudps; udpsis.close(); - ObjectInputStream udvsis= new ObjectInputStream(new FileInputStream(new File(userDefinedVarSuffixData))); + ObjectInputStream udvsis = new ObjectInputStream(new FileInputStream(new File(userDefinedVarSuffixData))); LinkedList tempudvs = (LinkedList) udvsis.readObject(); Network.userDefinedVarSuffix = tempudvs; udvsis.close(); - + Node.setCount(nodes.size()); - + } /** @@ -2145,9 +2098,4 @@ public static void clearNetwork() { userDefinedVarSuffix.clear(); } - public static PropositionNode buildTemporaryNode(String identifier) { - // TODO build temporary node for the deduce method - return null; - } - -} +} \ No newline at end of file diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 3f8bc855..b99c535e 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -80,7 +80,7 @@ public PropositionNode(Term trm) { * node scenario * @return the established type based channel */ - protected Channel establishChannel(ChannelTypes type, Object currentElement, Substitutions switchSubs, + public Channel establishChannel(ChannelTypes type, Object currentElement, Substitutions switchSubs, Substitutions filterSubs, String contextName, int matchType) { boolean matchTypeEstablishing = currentElement instanceof Match; Node evaluatedReporter = matchTypeEstablishing ? ((Match) currentElement).getNode() : (Node) currentElement; @@ -223,6 +223,7 @@ protected void sendRequestsToMatches(List list, String contextId) { matchType); matchedNode.receiveRequest(newChannel); } + System.out.println("Sent requests to " + list.size() + " matched nodes"); } /*** @@ -301,7 +302,7 @@ protected void getNodesToSendReport(ChannelTypes channelType, String currentCont Report toBeSent = new Report(substitutions, supportPropSet, reportSign, inferenceType); switch (channelType) { case MATCHED: - List matchesReturned = Matcher.match(this); + List matchesReturned = Matcher.match(this, substitutions); if (matchesReturned != null) sendReportToMatches(matchesReturned, toBeSent, currentContextName); break; @@ -335,7 +336,7 @@ protected void getNodesToSendRequest(ChannelTypes channelType, String currentCon try { switch (channelType) { case MATCHED: - List matchesReturned = Matcher.match(this); + List matchesReturned = Matcher.match(this, substitutions); if (matchesReturned != null) sendRequestsToMatches(matchesReturned, currentContextName); break; @@ -712,7 +713,7 @@ protected void processSingleRequestsChannel(Channel currentChannel) NodeSet toBeSentToDom = removeAlreadyWorkingOn(dominatingRules, currentChannel, filterSubs, false); sendRequestsToNodeSet(toBeSentToDom, filterSubs, currentContextName, ChannelTypes.RuleAnt); if (!(currentChannel instanceof MatchChannel)) { - List matchingNodes = Matcher.match(this); + List matchingNodes = Matcher.match(this, filterSubs); List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel); sendRequestsToMatches(toBeSentToMatch, currentContextName); } diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index b8d3c5e6..bb46a96c 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -481,7 +481,7 @@ protected void processSingleReportsChannel(Channel currentChannel) currentReportSubs, false); sendRequestsToNodeSet(toBeSentToDom, currentReportSubs, currentChannelContextName, ChannelTypes.RuleAnt); - List matchingNodes = Matcher.match(this); + List matchingNodes = Matcher.match(this, currentReportSubs); List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel); sendRequestsToMatches(toBeSentToMatch, currentChannelContextName); } @@ -499,6 +499,8 @@ protected void processSingleReportsChannel(Channel currentChannel) * le kol known instance hanla2ih hnt3amel ma3 el node ka2enaha asserted we * closed */ + + /* always sue the extracted report subs in the requests */ VariableNodeStats ruleNodeStats = computeNodeStats(currentReportSubs); Substitutions ruleNodeExtractedSubs = ruleNodeStats.getVariableNodeSubs(); for (Report knownInstance : knownInstances) { @@ -516,9 +518,9 @@ protected void processSingleReportsChannel(Channel currentChannel) NodeSet dominatingRules = getUpConsNodeSet(); NodeSet toBeSentToDom = removeAlreadyWorkingOn(dominatingRules, currentChannel, currentReportSubs, false); - sendRequestsToNodeSet(toBeSentToDom, currentReportSubs, currentChannelContextName, + sendRequestsToNodeSet(toBeSentToDom, ruleNodeExtractedSubs, currentChannelContextName, ChannelTypes.RuleAnt); - List matchingNodes = Matcher.match(this); + List matchingNodes = Matcher.match(this, ruleNodeExtractedSubs); List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel); sendRequestsToMatches(toBeSentToMatch, currentChannelContextName); /* @@ -541,13 +543,13 @@ protected void processSingleReportsChannel(Channel currentChannel) } else { Collection outgoingChannels = getOutgoingChannels().getChannels(); Collection incomingChannels = getIncomingChannels().getAntRuleChannels(); - boolean existsReportBuffers = false; + boolean existsForwardReportBuffers = false; for (Channel incomingChannel : incomingChannels) { - existsReportBuffers |= !incomingChannel.getReportsBuffer().isEmpty(); + existsForwardReportBuffers |= !incomingChannel.getReportsBuffer().hasForwardReports(); } if (!outgoingChannels.isEmpty()) receiveRequest(currentChannel); - if (!incomingChannels.isEmpty() && existsReportBuffers) + if (!incomingChannels.isEmpty() && existsForwardReportBuffers) receiveReport(currentChannel); currentChannelReportBuffer.removeReport(currentReport); } diff --git a/src/sneps/network/classes/setClasses/ChannelSet.java b/src/sneps/network/classes/setClasses/ChannelSet.java index 7db179bf..9e7eaae8 100644 --- a/src/sneps/network/classes/setClasses/ChannelSet.java +++ b/src/sneps/network/classes/setClasses/ChannelSet.java @@ -20,6 +20,9 @@ public class ChannelSet implements Iterable { public ChannelSet() { channels = new Hashtable>(); + channels.put(ChannelTypes.MATCHED, new Hashtable()); + channels.put(ChannelTypes.RuleAnt, new Hashtable()); + channels.put(ChannelTypes.RuleCons, new Hashtable()); } public Channel addChannel(Channel channel) { diff --git a/src/sneps/network/classes/setClasses/ReportSet.java b/src/sneps/network/classes/setClasses/ReportSet.java index 268238c2..3db79d10 100644 --- a/src/sneps/network/classes/setClasses/ReportSet.java +++ b/src/sneps/network/classes/setClasses/ReportSet.java @@ -4,6 +4,7 @@ import java.util.HashSet; import java.util.Iterator; +import sneps.snip.InferenceTypes; import sneps.snip.Report; public class ReportSet implements Iterable, Serializable { @@ -38,4 +39,12 @@ public boolean isEmpty() { return reports.size() == 0; } + public boolean hasForwardReports() { + for (Report report : reports) { + InferenceTypes reportInferenceType = report.getInferenceType(); + return reportInferenceType == InferenceTypes.FORWARD; + } + return false; + } + } diff --git a/src/sneps/snepslog/AP.java b/src/sneps/snepslog/AP.java index 2b616df4..cbaacfa7 100644 --- a/src/sneps/snepslog/AP.java +++ b/src/sneps/snepslog/AP.java @@ -125,8 +125,7 @@ protected static int getSnepslogMode() { } /** - * @param snepslogMode - * The number of the SNePSLOG mode to be used. + * @param snepslogMode The number of the SNePSLOG mode to be used. */ protected static void setSnepslogMode(int snepslogMode) { AP.snepslogMode = snepslogMode; @@ -140,8 +139,7 @@ protected static String getPrintingMode() { } /** - * @param printingMode - * The name of the printing mode to be used. + * @param printingMode The name of the printing mode to be used. */ protected static void setPrintingMode(String printingMode) { AP.printingMode = printingMode; @@ -150,8 +148,7 @@ protected static void setPrintingMode(String printingMode) { /** * This method is used to create a customized CaseFrame for Mode 1. * - * @param noOfArguments - * The number of argument relations. + * @param noOfArguments The number of argument relations. * * @return The created CaseFrame. */ @@ -169,11 +166,9 @@ protected static CaseFrame createModeOneCaseFrame(int noOfArguments) { /** * This method is used to create a customized CaseFrame for Mode 2. * - * @param p - * The name of the p relation. + * @param p The name of the p relation. * - * @param noOfArguments - * The number of argument relations. + * @param noOfArguments The number of argument relations. * * @return The created CaseFrame. */ @@ -192,16 +187,13 @@ protected static CaseFrame createModeTwoCaseFrame(String p, int noOfArguments) { * This method is used to create a CaseFrame for Mode 3 and stores it in a * Hashtable using the name as key. * - * @param semanticType - * This specifies the semantic type of the case frame. - * @param name - * This acts as an identifier for the case frame. - * @param relations - * This String contains the relations that is used to create the - * CaseFrame. + * @param semanticType This specifies the semantic type of the case frame. + * @param name This acts as an identifier for the case frame. + * @param relations This String contains the relations that is used to create + * the CaseFrame. * @return The created CaseFrame case frame. - * @throws RelationDoesntExistException - * If a relation was not defined in the Network. + * @throws RelationDoesntExistException If a relation was not defined in the + * Network. */ protected static CaseFrame createModeThreeCaseFrame(String name, String semanticType, ArrayList relations, String description) throws RelationDoesntExistException { @@ -232,13 +224,10 @@ protected static CaseFrame createModeThreeCaseFrame(String name, String semantic * This method is used to construct the nodes representing an infixedTerm in the * network. * - * @param type - * A String specifying the type of the infixed term. It should have - * one of the following values: and, or, or equality. - * @param arg1 - * The first argument node. - * @param arg2 - * The second argument node. + * @param type A String specifying the type of the infixed term. It should have + * one of the following values: and, or, or equality. + * @param arg1 The first argument node. + * @param arg2 The second argument node. * @return A molecular node representing the infixed term. * @throws NodeNotFoundInNetworkException * @throws NotAPropositionNodeException @@ -279,17 +268,13 @@ protected static Node buildInfixedTerm(String type, Node arg1, Node arg2) * This method is used to construct the nodes representing entailments in the * network. * - * @param entailmentType - * A String specifying the type of the entailment. It should have one - * of the following values: AndEntailment, OrEntailment, - * NumericalEntailment or Implication. - * @param antecedents - * An ArrayList of the nodes representing the antecedents. - * @param consequents - * An ArrayList of the nodes representing the consequents. - * @param optionalI - * A String which contains the value of "i" in case of a numerical - * entailment. + * @param entailmentType A String specifying the type of the entailment. It + * should have one of the following values: AndEntailment, + * OrEntailment, NumericalEntailment or Implication. + * @param antecedents An ArrayList of the nodes representing the antecedents. + * @param consequents An ArrayList of the nodes representing the consequents. + * @param optionalI A String which contains the value of "i" in case of a + * numerical entailment. * @return A molecular node representing the entailment. * @throws CaseFrameMissMatchException * @throws EquivalentNodeException @@ -351,8 +336,7 @@ protected static Node buildEntailment(String entailmentType, ArrayList ant * This method is used to construct the nodes representing a negatedTerm in the * network. * - * @param node - * A node to be negated. + * @param node A node to be negated. * @return A molecular node representing a negatedTerm. * @throws NodeNotFoundInNetworkException * @throws NotAPropositionNodeException @@ -377,12 +361,9 @@ protected static Node buildNegatedTerm(Node node) * This method is used to construct the nodes representing an andTerm in the * network. * - * @param i - * The andor min. - * @param j - * The andor max. - * @param arguments - * An ArrayList of the nodes representing the arguments. + * @param i The andor min. + * @param j The andor max. + * @param arguments An ArrayList of the nodes representing the arguments. * @return A molecular node representing an andorTerm. * @throws NodeNotFoundInNetworkException * @throws NotAPropositionNodeException @@ -409,11 +390,9 @@ protected static Node buildAndorTerm(String i, String j, ArrayList argumen * This method is used to construct the nodes representing setTerms in the * network. * - * @param type - * A String specifying the type of the setTerm. It should have one of - * the following values: and, or, nand, nor, xor or iff. - * @param arguments - * An ArrayList of the nodes representing the arguments. + * @param type A String specifying the type of the setTerm. It should have + * one of the following values: and, or, nand, nor, xor or iff. + * @param arguments An ArrayList of the nodes representing the arguments. * @return A molecular node representing a setTerm. * @throws NodeNotFoundInNetworkException * @throws NotAPropositionNodeException @@ -470,12 +449,9 @@ protected static Node buildSetTerm(String type, ArrayList arguments) * This method is used to construct the nodes representing a threshTerm in the * network. * - * @param thresh - * The thresh min. - * @param threshmax - * The thresh max. - * @param arguments - * An ArrayList of the nodes representing the arguments. + * @param thresh The thresh min. + * @param threshmax The thresh max. + * @param arguments An ArrayList of the nodes representing the arguments. * @return A molecular node representing a threshTerm. * @throws CaseFrameMissMatchException * @throws EquivalentNodeException @@ -502,14 +478,11 @@ protected static Node buildThreshTerm(String thresh, String threshmax, ArrayList * This method is used to construct the nodes representing a SNeRE TERM in the * network. * - * @param type - * A String specifying the type of the SNeRE term. It should have one - * of the following values: ifdo, whendo, wheneverdo, ActPlan, - * Effect, GoalPlan or Precondition. - * @param arg1 - * The first argument node. - * @param arg2 - * The second argument node. + * @param type A String specifying the type of the SNeRE term. It should have + * one of the following values: ifdo, whendo, wheneverdo, ActPlan, + * Effect, GoalPlan or Precondition. + * @param arg1 The first argument node. + * @param arg2 The second argument node. * @return A molecular node representing the SNeRE term. * @throws CaseFrameMissMatchException * @throws EquivalentNodeException @@ -567,17 +540,12 @@ protected static Node buildSNeRETerm(String type, Node arg1, Node arg2) * This method is used to construct the nodes representing withsome and withall * terms in the network. * - * @param type - * A String specifying the type of the term. It should have one of - * the following values: withsome or withall. - * @param vars - * An ArrayList of the nodes representing the vars. - * @param suchthat - * An ArrayList of the nodes representing the suchthat. - * @param doo - * An ArrayList of the nodes representing the doo. - * @param elsee - * An ArrayList of the nodes representing the elsee. + * @param type A String specifying the type of the term. It should have one + * of the following values: withsome or withall. + * @param vars An ArrayList of the nodes representing the vars. + * @param suchthat An ArrayList of the nodes representing the suchthat. + * @param doo An ArrayList of the nodes representing the doo. + * @param elsee An ArrayList of the nodes representing the elsee. * @return A molecular node representing the withsome/allTerm. * @throws CaseFrameMissMatchException * @throws EquivalentNodeException @@ -647,10 +615,8 @@ protected static Node buildWithsomeAllTerm(String type, ArrayList vars, Ar * This method is used to construct the nodes representing an allTerm in the * network. * - * @param vars - * An ArrayList of the nodes representing the vars. - * @param wff - * A node representing the scope of the quantifier. + * @param vars An ArrayList of the nodes representing the vars. + * @param wff A node representing the scope of the quantifier. * @return A molecular node representing the allTerm. * @throws EquivalentNodeException * @throws CannotBuildNodeException @@ -659,10 +625,12 @@ protected static Node buildWithsomeAllTerm(String type, ArrayList vars, Ar * @throws NodeNotFoundInNetworkException * @throws NotAPropositionNodeException * @throws IllegalIdentifierException + * @throws CaseFrameMissMatchException */ - protected static Node buildAllTerm(ArrayList vars, Node wff) throws CannotBuildNodeException, - EquivalentNodeException, NodeCannotBeRemovedException, RelationDoesntExistException, - NotAPropositionNodeException, NodeNotFoundInNetworkException, IllegalIdentifierException, NodeNotFoundInPropSetException { + protected static Node buildAllTerm(ArrayList vars, Node wff) + throws CannotBuildNodeException, EquivalentNodeException, NodeCannotBeRemovedException, + RelationDoesntExistException, NotAPropositionNodeException, NodeNotFoundInNetworkException, + IllegalIdentifierException, NodeNotFoundInPropSetException, CaseFrameMissMatchException { LinkedList relations = new LinkedList(); Relation forAll = Network.defineRelation("forall", "Infimum"); relations.add(forAll); @@ -699,10 +667,9 @@ protected static Node buildAllTerm(ArrayList vars, Node wff) throws Cannot * This method traverses the nodes in the given DownCableSet and set the * snepslogFlag of any variable node with one of the given names to false. * - * @param varNames - * An ArrayList which contains the names of these variable nodes. - * @param downCableSet - * The DownCableSet of a node. + * @param varNames An ArrayList which contains the names of these variable + * nodes. + * @param downCableSet The DownCableSet of a node. * @throws IllegalIdentifierException */ private static void resetTheFlags(ArrayList varNames, DownCableSet downCableSet) @@ -728,8 +695,7 @@ private static void resetTheFlags(ArrayList varNames, DownCableSet downC * This method converts a group of Nodes into a String representation according * to the printing mode in use. * - * @param wffs - * An ArrayList of some nodes. + * @param wffs An ArrayList of some nodes. * @return A String holding the representation. * @throws NotAPropositionNodeException * @throws NodeNotFoundInNetworkException @@ -787,8 +753,7 @@ protected static String displayWffs(ArrayList wffs) /** * This method converts a group of Nodes into a String representation. * - * @param terms - * An ArrayList of some nodes. + * @param terms An ArrayList of some nodes. * @return A String holding the representation. * @throws NotAPropositionNodeException * @throws NodeNotFoundInNetworkException @@ -817,8 +782,7 @@ protected static String displayTerms(ArrayList terms) /** * A method to convert an ArrayList of Nodes to a PropositionSet. * - * @param nodes - * An ArrayList that contains a group of nodes. + * @param nodes An ArrayList that contains a group of nodes. * @return A PropositionSet which contains the nodes in the given ArrayList. * @throws NotAPropositionNodeException * @throws NodeNotFoundInNetworkException @@ -835,8 +799,7 @@ protected static PropositionSet arrayListToPropositionSet(ArrayList nodes) /** * A method to convert a PropositionSet to an ArrayList of Nodes. * - * @param nodes - * A PropositionSet that contains a group of nodes. + * @param nodes A PropositionSet that contains a group of nodes. * @return An ArrayList which contains the nodes in the given PropositionSet * @throws NotAPropositionNodeException * @throws NodeNotFoundInNetworkException @@ -854,8 +817,7 @@ protected static ArrayList propositionSetToArrayList(PropositionSet set) /** * A method returning the molecular nodes from an ArrayList of Nodes. * - * @param nodes - * An ArrayList that contains a group of nodes. + * @param nodes An ArrayList that contains a group of nodes. * @return A ArrayList which contains only the molecular nodes from the ones in * given ArrayList. */ @@ -888,8 +850,7 @@ protected static ArrayList getAllMolecularNodesFromTheNetwork() { /** * A method returning the closed nodes from an ArrayList of Nodes. * - * @param nodes - * An ArrayList that contains a group of nodes. + * @param nodes An ArrayList that contains a group of nodes. * @return A ArrayList which contains only the closed nodes from the ones in * given ArrayList. */ @@ -922,8 +883,7 @@ protected static ArrayList getAllClosedNodesFromTheNetwork() { /** * A method returning the asserted nodes dominating a set of nodes. * - * @param nodes - * An ArrayList that contains a group of nodes. + * @param nodes An ArrayList that contains a group of nodes. * @return An ArrayList which contains the nodes dominating the given nodes. * @throws NodeNotFoundInNetworkException * @throws NotAPropositionNodeException @@ -949,8 +909,7 @@ protected static ArrayList beliefsAbout(ArrayList nodes) /** * A method returning the description of some given nodes. * - * @param nodes - * An ArrayList that contains a group of nodes. + * @param nodes An ArrayList that contains a group of nodes. * @return A String which contains the descriptions of the given nodes. * @throws NodeNotFoundInNetworkException * @throws NotAPropositionNodeException @@ -983,8 +942,7 @@ protected static String describeTerms(ArrayList nodes) /** * A method that loads some commands from a file and execute them. * - * @param path - * A String which contains the path of the file. + * @param path A String which contains the path of the file. * * @return A String representing the output of the commands in this file. */ @@ -1103,8 +1061,7 @@ protected static void clearKnowledgeBase() { /** * This method is used to execute a SNePSLOG command. * - * @param command - * A String holding the command that is to be executed. + * @param command A String holding the command that is to be executed. * * @return A String representing the output of that command. * diff --git a/src/sneps/snip/Runner.java b/src/sneps/snip/Runner.java index 19b64256..b8a21000 100644 --- a/src/sneps/snip/Runner.java +++ b/src/sneps/snip/Runner.java @@ -23,6 +23,10 @@ public static void initiate() { forwardAssertedNodes = new Hashtable(); } + public static void inspect() { + System.out.println("hihi"); + } + public static String run() { String sequence = ""; main: while (!highQueue.isEmpty() || !lowQueue.isEmpty() || !actQueue.isEmpty()) { diff --git a/src/sneps/snip/Test.java b/src/sneps/snip/Test.java new file mode 100644 index 00000000..8660a25f --- /dev/null +++ b/src/sneps/snip/Test.java @@ -0,0 +1,73 @@ +package sneps.snip; + +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.LinkedList; + +import sneps.exceptions.IllegalIdentifierException; +import sneps.exceptions.NodeNotFoundInNetworkException; +import sneps.exceptions.NotAPropositionNodeException; +import sneps.network.Network; +import sneps.network.Node; +import sneps.network.PropositionNode; +import sneps.network.VariableNode; +import sneps.network.classes.CaseFrame; +import sneps.network.classes.Relation; +import sneps.network.classes.Semantic; +import sneps.network.classes.SemanticHierarchy; +import sneps.network.classes.Wire; +import sneps.network.classes.setClasses.PropositionSet; +import sneps.network.classes.term.Molecular; +import sneps.network.classes.term.Variable; +import sneps.snebr.Controller; +import sneps.snip.channels.Channel; +import sneps.snip.channels.ChannelTypes; +import sneps.snip.matching.Binding; +import sneps.snip.matching.LinearSubstitutions; +import sneps.snip.matching.Substitutions; + +public class Test { + + public static void main(String[] args) throws Exception { + Semantic.createDefaultSemantics(); + + LinkedList relationSet = new LinkedList(); + relationSet.add(Network.defineRelation("member", "Proposition")); + relationSet.add(Network.defineRelation("class", "Proposition")); + CaseFrame caseFrame = Network.defineCaseFrame("Proposition", relationSet); + Node leo = Network.buildBaseNode("Leo", SemanticHierarchy.getSemantic("Proposition")); + Node fido = Network.buildBaseNode("Fido", SemanticHierarchy.getSemantic("Proposition")); + Node dog = Network.buildBaseNode("Dog", SemanticHierarchy.getSemantic("Proposition")); + VariableNode X = Network.buildVariableNode("X"); + ArrayList wires = new ArrayList(); + wires.add(new Wire(Network.getRelation("member"), fido)); + wires.add(new Wire(Network.getRelation("class"), dog)); + Node fidoIsADog = Network.buildMolecularNode(wires, caseFrame); + wires.clear(); + wires.add(new Wire(Network.getRelation("member"), leo)); + wires.add(new Wire(Network.getRelation("class"), dog)); + wires.clear(); + wires.add(new Wire(Network.getRelation("member"), X)); + wires.add(new Wire(Network.getRelation("class"), dog)); + + Substitutions filterSubs = new LinearSubstitutions(); + filterSubs.insert(new Binding(X, fido)); + +// Node leoIsADog = Network.buildMolecularNode(wires, caseFrame); + Node xIsADog = Network.buildMolecularNode(wires, caseFrame); + Channel channel = ((PropositionNode) xIsADog).establishChannel(ChannelTypes.MATCHED, fidoIsADog, null, + filterSubs, Controller.getCurrentContextName(), 0); + + Report report = new Report(filterSubs, new PropositionSet(), true, InferenceTypes.BACKWARD); + channel.testReportToSend(report); + ((PropositionNode) fidoIsADog).deduce(); + ArrayList wires1 = new ArrayList(); + wires1.add(new Wire(Network.getRelation("member"), X)); + wires1.add(new Wire(Network.getRelation("class"), dog)); + + Node XIsADog = Network.buildMolecularNode(wires1, caseFrame); + } + +} diff --git a/src/sneps/snip/matching/Matcher.java b/src/sneps/snip/matching/Matcher.java index 060b8316..ab4b4a32 100644 --- a/src/sneps/snip/matching/Matcher.java +++ b/src/sneps/snip/matching/Matcher.java @@ -1,14 +1,68 @@ package sneps.snip.matching; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.LinkedList; import java.util.List; +import sneps.exceptions.CannotBuildNodeException; +import sneps.exceptions.CaseFrameMissMatchException; +import sneps.exceptions.EquivalentNodeException; +import sneps.exceptions.IllegalIdentifierException; +import sneps.exceptions.NodeNotFoundInNetworkException; +import sneps.exceptions.NotAPropositionNodeException; +import sneps.exceptions.RelationDoesntExistException; +import sneps.exceptions.SemanticNotFoundInNetworkException; +import sneps.network.Network; +import sneps.network.Node; import sneps.network.PropositionNode; +import sneps.network.RuleNode; +import sneps.network.VariableNode; +import sneps.network.classes.CaseFrame; +import sneps.network.classes.Relation; +import sneps.network.classes.SemanticHierarchy; +import sneps.network.classes.Wire; public class Matcher { public static List match(PropositionNode toBeDeduced) { - // TODO Auto-generated method stub - return null; + List listOfMatches = new ArrayList(); + try { + Node leo; + Hashtable nodes = Network.getNodes(); + leo = Network.getNode("Leo"); + + VariableNode X = (VariableNode) Network.getNode("X"); + Substitutions filterSubs = new LinearSubstitutions(); + filterSubs.insert(new Binding(X, leo)); + Match newMatch = new Match(filterSubs, new LinearSubstitutions(), leo, 0); + + listOfMatches.add(newMatch); + } catch (NodeNotFoundInNetworkException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return listOfMatches; + } + + public static List match(PropositionNode propositionNode, Substitutions currentReportSubs) { + List listOfMatches = new ArrayList(); + try { + Node leo; + Hashtable nodes = Network.getNodes(); + leo = Network.getNode("M1"); + + VariableNode X = (VariableNode) Network.getNode("X"); + Substitutions filterSubs = new LinearSubstitutions(); + filterSubs.insert(new Binding(X, leo)); + Match newMatch = new Match(filterSubs, new LinearSubstitutions(), leo, 0); + + listOfMatches.add(newMatch); + } catch (NodeNotFoundInNetworkException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return listOfMatches; } } diff --git a/tests/SnipTest.java b/tests/SnipTest.java new file mode 100644 index 00000000..d257f2e5 --- /dev/null +++ b/tests/SnipTest.java @@ -0,0 +1,271 @@ +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.LinkedList; + +import org.junit.*; + +import sneps.exceptions.CannotBuildNodeException; +import sneps.exceptions.DuplicateContextNameException; +import sneps.exceptions.DuplicatePropositionException; +import sneps.exceptions.EquivalentNodeException; +import sneps.exceptions.IllegalIdentifierException; +import sneps.exceptions.NodeNotFoundInNetworkException; +import sneps.exceptions.NotAPropositionNodeException; +import sneps.network.Network; +import sneps.network.Node; +import sneps.network.RuleNode; +import sneps.network.VariableNode; +import sneps.network.cables.DownCable; +import sneps.network.cables.DownCableSet; +import sneps.network.classes.CaseFrame; +import sneps.network.classes.RCFP; +import sneps.network.classes.Relation; +import sneps.network.classes.RelationsRestrictedCaseFrame; +import sneps.network.classes.Semantic; +import sneps.network.classes.Wire; +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.network.classes.setClasses.FlagNodeSet; +import sneps.network.classes.setClasses.NodeSet; +import sneps.network.classes.setClasses.PropositionSet; +import sneps.snebr.Context; +import sneps.snebr.Controller; +import sneps.snip.Report; +import sneps.snip.classes.FlagNode; +import sneps.snip.classes.RuleUseInfo; +import sneps.snip.matching.Binding; +import sneps.snip.matching.LinearSubstitutions; +import sneps.snip.rules.AndEntailment; +import sneps.snip.rules.OrEntailment; + +public class SnipTest { + private static Context context; + private static String contextName = "TempContext"; + private static OrEntailment or; + private static Node fido, var, dog, barks; + private static Node prop1, prop2, prop3, prop4; + private static RuleUseInfo rui; + private static Report report; + + @BeforeClass + public static void BuildNetwork() throws Exception { + /** + * build context + */ + try { + context = Controller.createContext(contextName); + } catch (DuplicateContextNameException e1) { + assertNotNull(e1.getMessage(), e1); + } + + /** + * Create substitutions, FlagNodeSet, FlagNode, PropositionSet, wires, + * relations, caseFrames + */ + + 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(); + Relation memberRel = Network.defineRelation("Member", "NodeSet"); + Relation classRel = Network.defineRelation("Class", "NodeSet"); + Relation doesRel = Network.defineRelation("Does", "NodeSet"); + Relation antsRel = Network.defineRelation("Vant", "Vant"); + Relation consRel = Network.defineRelation("Vconsq", "Vconsq"); + 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; + rels.clear(); + + /** + * Building propositions & base nodes, adding wires + */ + + 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); + } catch (IllegalIdentifierException | NotAPropositionNodeException | NodeNotFoundInNetworkException e1) { + assertNotNull(e1.getMessage(), e1); + var = new VariableNode(new Variable("X")); + } + + try { + wires.clear(); + wires.add(wire1); + wires.add(wire2); + prop1 = Network.buildMolecularNode(wires, caseFrameMC); + + wires.clear(); + wires.add(wire2); + wires.add(wire3); + prop2 = Network.buildMolecularNode(wires, caseFrameCD); + + wires.clear(); + wires.add(wire4); + wires.add(wire2); + prop3 = Network.buildMolecularNode(wires, caseFrameMC); + + wires.clear(); + wires.add(wire1); + wires.add(wire3); + prop4 = Network.buildMolecularNode(wires, caseFrameMD); + } catch (CannotBuildNodeException | EquivalentNodeException | NotAPropositionNodeException + | NodeNotFoundInNetworkException e1) { + assertNotNull(e1.getMessage(), e1); + LinkedList dcList = new LinkedList(); + NodeSet nodeSet1 = new NodeSet(); + DownCable dc1; + DownCableSet dcs; + + nodeSet1.addNode(fido); + dc1 = new DownCable(memberRel, nodeSet1); + dcList.add(dc1); + nodeSet1.clear(); + nodeSet1.addNode(dog); + dc1 = new DownCable(classRel, nodeSet1); + dcList.add(dc1); + dcs = new DownCableSet(dcList, caseFrameMC); + prop1 = new Node(new Open("Prop1", dcs)); + dcList.clear(); + // ------------------------------------------------------------// + nodeSet1.clear(); + nodeSet1.addNode(dog); + dc1 = new DownCable(classRel, nodeSet1); + dcList.add(dc1); + nodeSet1.clear(); + nodeSet1.addNode(barks); + dc1 = new DownCable(doesRel, nodeSet1); + dcList.add(dc1); + dcs = new DownCableSet(dcList, caseFrameCD); + prop2 = new Node(new Open("Prop2", dcs)); + dcList.clear(); + // ------------------------------------------------------------// + nodeSet1.clear(); + nodeSet1.addNode(var); + dc1 = new DownCable(memberRel, nodeSet1); + dcList.add(dc1); + nodeSet1.clear(); + nodeSet1.addNode(dog); + dc1 = new DownCable(classRel, nodeSet1); + dcList.add(dc1); + dcs = new DownCableSet(dcList, caseFrameMC); + prop3 = new Node(new Open("Prop3", dcs)); + dcList.clear(); + // ------------------------------------------------------------// + nodeSet1.clear(); + nodeSet1.addNode(fido); + dc1 = new DownCable(memberRel, nodeSet1); + dcList.add(dc1); + nodeSet1.clear(); + nodeSet1.addNode(barks); + dc1 = new DownCable(doesRel, nodeSet1); + dcList.add(dc1); + dcs = new DownCableSet(dcList, caseFrameMD); + prop4 = new Node(new Open("Prop4", dcs)); + dcList.clear(); + } + + try { + support.add(prop1.getId()); + } catch (DuplicatePropositionException | NotAPropositionNodeException | NodeNotFoundInNetworkException e) { + assertNotNull(e.getMessage(), e); + } + fn = new FlagNode(prop1, support, 1); + fns.insert(fn); + + support.clearSet(); + try { + support.add(prop2.getId()); + } catch (DuplicatePropositionException | NotAPropositionNodeException | NodeNotFoundInNetworkException e) { + assertNotNull(e.getMessage(), e); + } + fn = new FlagNode(prop2, support, 1); + fns.insert(fn); + + support.clearSet(); + try { + support.add(prop3.getId()); + } catch (DuplicatePropositionException | NotAPropositionNodeException | NodeNotFoundInNetworkException e) { + assertNotNull(e.getMessage(), e); + } + fn = new FlagNode(prop3, support, 1); + fns.insert(fn); + + nodeSet.addNode(prop1); + dc.add(new DownCable(antsRel, nodeSet)); + + nodeSet.clear(); + nodeSet.addNode(prop2); + dc.add(new DownCable(antsRel, nodeSet)); + + nodeSet.clear(); + nodeSet.addNode(prop3); + dc.add(new DownCable(antsRel, nodeSet)); + + nodeSet.clear(); + nodeSet.addNode(prop4); + dc.add(new DownCable(consRel, nodeSet)); + + DownCableSet dcs = new DownCableSet(dc, caseFrameAC); + + /** + * Or-entailment + */ + + or = new OrEntailment(new Open("Open", dcs)); + + try { + support.add(dog.getId()); + support.add(fido.getId()); + support.add(var.getId()); + } catch (DuplicatePropositionException | NotAPropositionNodeException | NodeNotFoundInNetworkException e) { + assertNotNull(e.getMessage(), e); + } + + sub.insert(new Binding((VariableNode) var, fido)); + rui = new RuleUseInfo(sub, 1, 0, fns); + report = new Report(sub, support, true, contextName); + + } + + @Test + public void applyRuleHandler() { + + or.applyRuleHandler(report, fido); + assertEquals(true, or.getReply()); + } + + @Test + public void test() { + fail("Not yet implemented"); + } + + + +} From ffce72c00e0faff42bc805109bfdeff60d88e613 Mon Sep 17 00:00:00 2001 From: Youssef Date: Sun, 2 Jun 2019 19:09:48 +0200 Subject: [PATCH 20/22] added helpful prints and some tests in snip/Test --- src/sneps/network/Network.java | 6 +- src/sneps/network/PropositionNode.java | 58 ++++++++++++++++--- src/sneps/network/RuleNode.java | 14 ++--- .../classes/setClasses/ChannelSet.java | 38 ++++++------ .../classes/setClasses/VariableSet.java | 13 +++++ src/sneps/snip/Runner.java | 6 +- src/sneps/snip/Test.java | 48 ++++++++++----- .../snip/channels/ChannelIdentifier.java | 4 ++ src/sneps/snip/classes/VariableNodeStats.java | 25 ++++++++ .../snip/matching/LinearSubstitutions.java | 16 +++-- src/sneps/snip/matching/Matcher.java | 23 +++++--- 11 files changed, 183 insertions(+), 68 deletions(-) diff --git a/src/sneps/network/Network.java b/src/sneps/network/Network.java index 1f001ee8..6d461443 100644 --- a/src/sneps/network/Network.java +++ b/src/sneps/network/Network.java @@ -988,7 +988,8 @@ private static boolean followingCaseFrame(Object[][] array, RelationsRestrictedC } private static boolean followingCaseFrame(Object[][] array, CaseFrame caseFrame) { - LinkedList list = caseFrame.getRelations(); + LinkedList list = new LinkedList(); + list.addAll(caseFrame.getRelations()); for (int i = 0; i < array.length; i++) { Relation r = (Relation) array[i][0]; if (list.contains(r)) { @@ -1001,8 +1002,9 @@ private static boolean followingCaseFrame(Object[][] array, CaseFrame caseFrame) return false; } } - if (!list.isEmpty()) + if (!list.isEmpty()) { return false; + } return true; } diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index b99c535e..28663836 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -80,10 +80,16 @@ public PropositionNode(Term trm) { * node scenario * @return the established type based channel */ - public Channel establishChannel(ChannelTypes type, Object currentElement, Substitutions switchSubs, + protected Channel establishChannel(ChannelTypes type, Object currentElement, Substitutions switchSubs, Substitutions filterSubs, String contextName, int matchType) { + boolean matchTypeEstablishing = currentElement instanceof Match; Node evaluatedReporter = matchTypeEstablishing ? ((Match) currentElement).getNode() : (Node) currentElement; + /* BEGIN - Helpful Prints */ + String requesterIdent = getIdentifier(); + String reporterIdent = evaluatedReporter.getIdentifier(); + System.out.println("Trying to establish a channel from " + requesterIdent + " to " + reporterIdent); + /* END - Helpful Prints */ Substitutions switchLinearSubs = switchSubs == null ? new LinearSubstitutions() : switchSubs; Channel newChannel; switch (type) { @@ -101,10 +107,16 @@ public Channel establishChannel(ChannelTypes type, Object currentElement, Substi ChannelSet incomingChannels = getIncomingChannels(); Channel extractedChannel = incomingChannels.getChannel(newChannel); if (extractedChannel == null) { + /* BEGIN - Helpful Prints */ + System.out.println("Channel successfully created"); + /* END - Helpful Prints */ ((PropositionNode) evaluatedReporter).addToOutgoingChannels(newChannel); addToIncomingChannels(newChannel); return newChannel; } + /* BEGIN - Helpful Prints */ + System.out.println("Channel was already created"); + /* END - Helpful Prints */ return extractedChannel; } @@ -263,6 +275,10 @@ public boolean assertedInContext(String desiredContextName) * through the runner. */ public void receiveRequest(Channel channel) { + /* BEGIN - Helpful Prints */ + String nodeIdent = getIdentifier(); + System.out.println("PropositionNode " + nodeIdent + " just received a request."); + /* END - Helpful Prints */ Runner.addToLowQueue(this); channel.setRequestProcessed(true); } @@ -272,6 +288,10 @@ public void receiveRequest(Channel channel) { * through the runner. */ public void receiveReport(Channel channel) { + /* BEGIN - Helpful Prints */ + String nodeIdent = getIdentifier(); + System.out.println("PropositionNode " + nodeIdent + " just received a report."); + /* END - Helpful Prints */ Runner.addToHighQueue(this); channel.setReportProcessed(true); } @@ -402,9 +422,16 @@ protected List removeAlreadyWorkingOn(List matchingNodes, Channel */ protected static NodeSet removeAlreadyWorkingOn(NodeSet nodes, Channel channel, Substitutions toBeCompared, boolean ruleType) { + /* BEGIN - Helpful Prints */ + String nodesToBeFiltered = "[ "; + String nodesToBeKept = "[ "; + /* END - Helpful Prints */ NodeSet nodesToConsider = new NodeSet(); for (Node sourceNode : nodes) if (sourceNode instanceof PropositionNode) { + /* BEGIN - Helpful Prints */ + nodesToBeFiltered += sourceNode.getIdentifier() + ", "; + /* END - Helpful Prints */ boolean conditionMet = !ruleType || sourceNode.getId() != channel.getRequester().getId(); if (conditionMet) { ChannelSet outgoingChannels = ((PropositionNode) sourceNode).getOutgoingChannels(); @@ -414,10 +441,26 @@ protected static NodeSet removeAlreadyWorkingOn(NodeSet nodes, Channel channel, conditionMet &= !processedChannelFilterSubs.isSubSet(toBeCompared) && outgoingChannel.getRequester().getId() == channel.getReporter().getId(); } - if (conditionMet) + if (conditionMet) { nodesToConsider.addNode(sourceNode); + /* BEGIN - Helpful Prints */ + nodesToBeKept += sourceNode.getIdentifier() + ", "; + /* END - Helpful Prints */ + } } } + if (nodesToBeKept.length() > 2) + nodesToBeKept = nodesToBeKept.substring(0, nodesToBeKept.length() - 2) + " ]"; + else + nodesToBeKept += "]"; + if (nodesToBeFiltered.length() > 2) + nodesToBeFiltered = nodesToBeFiltered.substring(0, nodesToBeFiltered.length() - 2) + " ]"; + else + nodesToBeFiltered += "]"; + + System.out.println("\n\u2022 Removing nodes with a request that is subset of " + toBeCompared.toString() + ":"); + System.out.println("Result: " + nodesToBeKept + " from " + nodesToBeFiltered + "."); + /* END - Helpful Prints */ return nodesToConsider; } @@ -621,6 +664,10 @@ protected Collection getIncomingMatchChannels() { */ public boolean isWhQuestion(Substitutions filterSubs) { VariableNodeStats currentNodeStats = computeNodeStats(filterSubs); + /* BEGIN - Helpful Prints */ + System.out.println("\n\u2022 Testing if " + getIdentifier() + " is a Wh-Question:"); + System.out.println(currentNodeStats.toString() + "\n"); + /* END - Helpful Prints */ return !currentNodeStats.areAllVariablesBound(); } @@ -708,7 +755,8 @@ protected void processSingleRequestsChannel(Channel currentChannel) for (Report currentReport : knownInstances) sentAtLeastOne |= sendReport(currentReport, currentChannel); Substitutions filterSubs = currentChannel.getFilter().getSubstitutions(); - if (!sentAtLeastOne || isWhQuestion(filterSubs)) { + boolean isWhQuestion = isWhQuestion(filterSubs); + if (!sentAtLeastOne || isWhQuestion) { NodeSet dominatingRules = getUpConsNodeSet(); NodeSet toBeSentToDom = removeAlreadyWorkingOn(dominatingRules, currentChannel, filterSubs, false); sendRequestsToNodeSet(toBeSentToDom, filterSubs, currentContextName, ChannelTypes.RuleAnt); @@ -776,8 +824,4 @@ protected void processSingleReportsChannel(Channel currentChannel) } } - // PROCESS REPORT : 3adi -> , forward - // -> same as 3adi , plus matching to send and get the nodes el howa lihom - // antecedents we send reports - } \ No newline at end of file diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index bb46a96c..59c188e0 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -436,9 +436,6 @@ protected void processSingleRequestsChannel(Channel currentChannel) super.processSingleRequestsChannel(currentChannel); } - // PROCESS REPORT : 3adi -> outgoing channels node we ab3at accordingly, forard - // -> outgoing channels and the rest of the consequents kolohom we ab3at 3adi - /*** * Report handling in Rule proposition nodes. */ @@ -464,6 +461,8 @@ protected void processSingleReportsChannel(Channel currentChannel) for (Report currentReport : channelReports) { boolean forwardReportType = currentReport.getInferenceType() == InferenceTypes.FORWARD; Substitutions currentReportSubs = currentReport.getSubstitutions(); + VariableNodeStats ruleNodeStats = computeNodeStats(currentReportSubs); + Substitutions ruleNodeExtractedSubs = ruleNodeStats.getVariableNodeSubs(); if (currentChannel instanceof AntecedentToRuleChannel) { /** AntecedentToRule Channel */ if (forwardReportType) { @@ -478,10 +477,10 @@ protected void processSingleReportsChannel(Channel currentChannel) } else { NodeSet dominatingRules = getUpConsNodeSet(); NodeSet toBeSentToDom = removeAlreadyWorkingOn(dominatingRules, currentChannel, - currentReportSubs, false); - sendRequestsToNodeSet(toBeSentToDom, currentReportSubs, currentChannelContextName, + ruleNodeExtractedSubs, false); + sendRequestsToNodeSet(toBeSentToDom, ruleNodeExtractedSubs, currentChannelContextName, ChannelTypes.RuleAnt); - List matchingNodes = Matcher.match(this, currentReportSubs); + List matchingNodes = Matcher.match(this, ruleNodeExtractedSubs); List toBeSentToMatch = removeAlreadyWorkingOn(matchingNodes, currentChannel); sendRequestsToMatches(toBeSentToMatch, currentChannelContextName); } @@ -501,8 +500,7 @@ protected void processSingleReportsChannel(Channel currentChannel) */ /* always sue the extracted report subs in the requests */ - VariableNodeStats ruleNodeStats = computeNodeStats(currentReportSubs); - Substitutions ruleNodeExtractedSubs = ruleNodeStats.getVariableNodeSubs(); + for (Report knownInstance : knownInstances) { Substitutions knownInstanceSubstitutions = knownInstance.getSubstitutions(); boolean subSetCheck = ruleNodeExtractedSubs.isSubSet(knownInstanceSubstitutions); diff --git a/src/sneps/network/classes/setClasses/ChannelSet.java b/src/sneps/network/classes/setClasses/ChannelSet.java index 9e7eaae8..839e7ef8 100644 --- a/src/sneps/network/classes/setClasses/ChannelSet.java +++ b/src/sneps/network/classes/setClasses/ChannelSet.java @@ -16,13 +16,13 @@ import sneps.snip.matching.Substitutions; public class ChannelSet implements Iterable { - private Hashtable> channels; + private Hashtable> channels; public ChannelSet() { - channels = new Hashtable>(); - channels.put(ChannelTypes.MATCHED, new Hashtable()); - channels.put(ChannelTypes.RuleAnt, new Hashtable()); - channels.put(ChannelTypes.RuleCons, new Hashtable()); + channels = new Hashtable>(); + channels.put(ChannelTypes.MATCHED, new Hashtable()); + channels.put(ChannelTypes.RuleAnt, new Hashtable()); + channels.put(ChannelTypes.RuleCons, new Hashtable()); } public Channel addChannel(Channel channel) { @@ -32,10 +32,10 @@ public Channel addChannel(Channel channel) { Substitutions filterSubs = channel.getFilter().getSubstitutions(); Substitutions switchSubs = channel.getSwitch().getSubstitutions(); ChannelTypes channelType = getChannelType(channel); - Hashtable targetSet = channels.remove(channelType); + Hashtable targetSet = channels.remove(channelType); ChannelIdentifier channelId = new ChannelIdentifier(channelRequesterId, channelReporterId, channelContextName, filterSubs, switchSubs); - Channel added = targetSet.put(channelId, channel); + Channel added = targetSet.put(channelId.toString(), channel); channels.put(channelType, targetSet); return added; } @@ -47,7 +47,7 @@ public Channel removeChannel(Channel channel) { Substitutions filterSubs = channel.getFilter().getSubstitutions(); Substitutions switchSubs = channel.getSwitch().getSubstitutions(); ChannelTypes channelType = getChannelType(channel); - Hashtable targetSet = channels.remove(channelType); + Hashtable targetSet = channels.remove(channelType); ChannelIdentifier channelId = new ChannelIdentifier(channelRequesterId, channelReporterId, channelContextName, filterSubs, switchSubs); Channel removed = targetSet.remove(channelId); @@ -75,8 +75,8 @@ public Iterator iterator() { */ Collection toBeAddedLater = new ArrayList(); Collection allMergedChannels = new ArrayList(); - Collection> collectionOfSets = channels.values(); - for (Hashtable set : collectionOfSets) { + Collection> collectionOfSets = channels.values(); + for (Hashtable set : collectionOfSets) { for (Channel channel : set.values()) { boolean ruleAntChannel = channel instanceof AntecedentToRuleChannel; if (ruleAntChannel) @@ -101,8 +101,8 @@ public Iterator iterator() { public ChannelSet getFilteredRequestChannels(boolean processedRequest) { ChannelSet processedRequestsChannels = new ChannelSet(); Collection allMergedChannels = new ArrayList(); - Collection> collectionOfSets = channels.values(); - for (Hashtable set : collectionOfSets) + Collection> collectionOfSets = channels.values(); + for (Hashtable set : collectionOfSets) allMergedChannels.addAll(set.values()); for (Channel channel : allMergedChannels) { if (channel.isRequestProcessed() == processedRequest) @@ -113,24 +113,24 @@ public ChannelSet getFilteredRequestChannels(boolean processedRequest) { public Collection getChannels() { Collection allMergedChannels = new ArrayList(); - Collection> collectionOfSets = channels.values(); - for (Hashtable set : collectionOfSets) + Collection> collectionOfSets = channels.values(); + for (Hashtable set : collectionOfSets) allMergedChannels.addAll(set.values()); return allMergedChannels; } public Collection getAntRuleChannels() { - Hashtable channelsHash = channels.get(ChannelTypes.RuleAnt); + Hashtable channelsHash = channels.get(ChannelTypes.RuleAnt); return channelsHash.values(); } public Collection getRuleConsChannels() { - Hashtable channelsHash = channels.get(ChannelTypes.RuleCons); + Hashtable channelsHash = channels.get(ChannelTypes.RuleCons); return channelsHash.values(); } public Collection getMatchChannels() { - Hashtable channelsHash = channels.get(ChannelTypes.MATCHED); + Hashtable channelsHash = channels.get(ChannelTypes.MATCHED); return channelsHash.values(); } @@ -147,8 +147,8 @@ public Channel getChannel(Channel newChannel) { ChannelIdentifier channelId = new ChannelIdentifier(channelRequesterId, channelReporterId, channelContextName, channelSubs, switchSubs); ChannelTypes channelType = getChannelType(newChannel); - Hashtable set = channels.get(channelType); - return set.get(channelId); + Hashtable set = channels.get(channelType); + return set.get(channelId.toString()); } } diff --git a/src/sneps/network/classes/setClasses/VariableSet.java b/src/sneps/network/classes/setClasses/VariableSet.java index ac1c6799..1d62b766 100644 --- a/src/sneps/network/classes/setClasses/VariableSet.java +++ b/src/sneps/network/classes/setClasses/VariableSet.java @@ -43,4 +43,17 @@ public boolean isEmpty() { return variables.isEmpty(); } + @Override + public String toString() { + String variablesString = "[ "; + for (Variable variable : this.variables) { + variablesString += variable.getIdentifier() + ", "; + } + if (variablesString.length() > 2) + variablesString = variablesString.substring(0, variablesString.length() - 2) + " ]"; + else + variablesString += "]"; + return variablesString; + } + } diff --git a/src/sneps/snip/Runner.java b/src/sneps/snip/Runner.java index b8a21000..59911a5a 100644 --- a/src/sneps/snip/Runner.java +++ b/src/sneps/snip/Runner.java @@ -31,16 +31,14 @@ 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 "); + System.out.println("In HighQueue"); Node toRunNext = highQueue.poll(); System.out.println(toRunNext); - System.out.println("\n\n"); toRunNext.processReports(); sequence += 'H'; } while (!lowQueue.isEmpty()) { - System.out.println("in"); + System.out.println("In LowQueue"); Node toRunNext = lowQueue.poll(); toRunNext.processRequests(); sequence += 'L'; diff --git a/src/sneps/snip/Test.java b/src/sneps/snip/Test.java index 8660a25f..b1dd414a 100644 --- a/src/sneps/snip/Test.java +++ b/src/sneps/snip/Test.java @@ -6,6 +6,7 @@ import java.util.Hashtable; import java.util.LinkedList; +import sneps.exceptions.ContextNameDoesntExistException; import sneps.exceptions.IllegalIdentifierException; import sneps.exceptions.NodeNotFoundInNetworkException; import sneps.exceptions.NotAPropositionNodeException; @@ -29,45 +30,62 @@ import sneps.snip.matching.Substitutions; public class Test { - + /* Report sending (support ) */ + /* switch changing report's subs */ + /* deduce */ + /* add */ + /* RuleResponse returns M4's channel ma3 el report el mafroud ytb3t always */ public static void main(String[] args) throws Exception { Semantic.createDefaultSemantics(); + /* Case frame creation - [member, class] */ LinkedList relationSet = new LinkedList(); relationSet.add(Network.defineRelation("member", "Proposition")); relationSet.add(Network.defineRelation("class", "Proposition")); - CaseFrame caseFrame = Network.defineCaseFrame("Proposition", relationSet); + CaseFrame classMemberCF = Network.defineCaseFrame("Proposition", relationSet); Node leo = Network.buildBaseNode("Leo", SemanticHierarchy.getSemantic("Proposition")); + Node roger = Network.buildBaseNode("Roger", SemanticHierarchy.getSemantic("Proposition")); Node fido = Network.buildBaseNode("Fido", SemanticHierarchy.getSemantic("Proposition")); Node dog = Network.buildBaseNode("Dog", SemanticHierarchy.getSemantic("Proposition")); VariableNode X = Network.buildVariableNode("X"); + VariableNode Y = Network.buildVariableNode("Y"); ArrayList wires = new ArrayList(); wires.add(new Wire(Network.getRelation("member"), fido)); wires.add(new Wire(Network.getRelation("class"), dog)); - Node fidoIsADog = Network.buildMolecularNode(wires, caseFrame); + Node fidoIsADog = Network.buildMolecularNode(wires, classMemberCF); + try { + Controller.addPropToContext("default", fidoIsADog.getId()); + } catch (ContextNameDoesntExistException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } wires.clear(); wires.add(new Wire(Network.getRelation("member"), leo)); wires.add(new Wire(Network.getRelation("class"), dog)); + Node leoIsADog = Network.buildMolecularNode(wires, classMemberCF); + wires.clear(); + wires.add(new Wire(Network.getRelation("member"), roger)); + wires.add(new Wire(Network.getRelation("class"), dog)); + Node rogerIsADog = Network.buildMolecularNode(wires, classMemberCF); wires.clear(); wires.add(new Wire(Network.getRelation("member"), X)); wires.add(new Wire(Network.getRelation("class"), dog)); + Node xIsADog = Network.buildMolecularNode(wires, classMemberCF); + wires.clear(); + wires.add(new Wire(Network.getRelation("member"), Y)); + wires.add(new Wire(Network.getRelation("class"), dog)); + Node yIsADog = Network.buildMolecularNode(wires, classMemberCF); + /* + * Knowledge Base established : [Dog(Leo), Dog(Fido), Dog(Roger), Dog(X), + * Dog(Y)] + */ Substitutions filterSubs = new LinearSubstitutions(); filterSubs.insert(new Binding(X, fido)); -// Node leoIsADog = Network.buildMolecularNode(wires, caseFrame); - Node xIsADog = Network.buildMolecularNode(wires, caseFrame); - Channel channel = ((PropositionNode) xIsADog).establishChannel(ChannelTypes.MATCHED, fidoIsADog, null, - filterSubs, Controller.getCurrentContextName(), 0); - - Report report = new Report(filterSubs, new PropositionSet(), true, InferenceTypes.BACKWARD); - channel.testReportToSend(report); +// Report report = new Report(filterSubs, new PropositionSet(), true, InferenceTypes.BACKWARD); +// channel.testReportToSend(report); ((PropositionNode) fidoIsADog).deduce(); - ArrayList wires1 = new ArrayList(); - wires1.add(new Wire(Network.getRelation("member"), X)); - wires1.add(new Wire(Network.getRelation("class"), dog)); - - Node XIsADog = Network.buildMolecularNode(wires1, caseFrame); } } diff --git a/src/sneps/snip/channels/ChannelIdentifier.java b/src/sneps/snip/channels/ChannelIdentifier.java index 9019e0c9..eb9e8b03 100644 --- a/src/sneps/snip/channels/ChannelIdentifier.java +++ b/src/sneps/snip/channels/ChannelIdentifier.java @@ -72,4 +72,8 @@ public void setSwitchSubstitutions(Substitutions switchSubstututions) { this.switchSubstitutions = switchSubstututions; } + public String toString() { + return requesterId + "" + reporterId + contextName + filterSubstitutions.toString() + + switchSubstitutions.toString(); + } } diff --git a/src/sneps/snip/classes/VariableNodeStats.java b/src/sneps/snip/classes/VariableNodeStats.java index 2947b3c1..1162fae0 100644 --- a/src/sneps/snip/classes/VariableNodeStats.java +++ b/src/sneps/snip/classes/VariableNodeStats.java @@ -2,6 +2,7 @@ import java.util.Vector; +import sneps.network.classes.setClasses.VariableSet; import sneps.snip.matching.Binding; import sneps.snip.matching.LinearSubstitutions; import sneps.snip.matching.Substitutions; @@ -11,6 +12,7 @@ public class VariableNodeStats { private Substitutions referenceSubs; private int nodeId; private Substitutions variableNodeSubs; + private VariableSet nodeFreeVariables; public VariableNodeStats(boolean variablesBound, Substitutions extractedFilterRelevantToVariables, Substitutions refSubs, int id) { @@ -27,6 +29,14 @@ public VariableNodeStats(boolean variablesBound, Substitutions extractedFilterRe referenceSubs = refSubs; } + public VariableNodeStats(boolean variablesBound, Substitutions extractedFilterRelevantToVariables, + Substitutions refSubs, VariableSet freeVariables) { + allVariablesBound = variablesBound; + variableNodeSubs = extractedFilterRelevantToVariables; + referenceSubs = refSubs; + nodeFreeVariables = freeVariables; + } + public Substitutions getReferenceSubs() { return referenceSubs; } @@ -69,4 +79,19 @@ public boolean isSubSet(Substitutions variableSubstitutions) { return variableNodeSubs.isSubSet(variableSubstitutions); } + public String toString() { + return "Test results for Node id: " + nodeId + "\n- Node Free Variables: " + nodeFreeVariables.toString() + + "\n- All Variables Bound: " + allVariablesBound + "\n- Reference Substitutions: " + + referenceSubs.toString() + "\n- Extracted Substitutions according to the node's free variables: " + + variableNodeSubs.toString(); + } + + public VariableSet getNodeFreeVariables() { + return nodeFreeVariables; + } + + public void setNodeFreeVariables(VariableSet nodeVariables) { + this.nodeFreeVariables = nodeVariables; + } + } diff --git a/src/sneps/snip/matching/LinearSubstitutions.java b/src/sneps/snip/matching/LinearSubstitutions.java index 8891fb8a..241595e1 100644 --- a/src/sneps/snip/matching/LinearSubstitutions.java +++ b/src/sneps/snip/matching/LinearSubstitutions.java @@ -432,12 +432,16 @@ public boolean sub(String x, String y) { * Print the substitutions list */ public String toString() { - String res = ""; + String res = "{ "; for (int i = 0; i < sub.size(); i++) { res += sub.get(i).getNode().getIdentifier() + " substitutes " + sub.get(i).getVariableNode().getIdentifier() - + '\n'; + + ", "; } - return res; + if (res.length() > 2) + res = res.substring(0, res.length() - 2) + " }"; + else + res += "}"; + return res.length() == 0 ? "{ }" : res; } public int termID(int variableID) { @@ -457,7 +461,7 @@ public void insertOrUpdate(Binding mb) { } /*** - * Method checking the freeVariables Set making sure each has a compatible + * Method checking the freeVariables Set, making sure each has a compatible * Binding in the instance Vector * * @param freeVariables VariableSet @@ -465,7 +469,7 @@ public void insertOrUpdate(Binding mb) { * @return VariableNodeStats */ public VariableNodeStats extractBoundStatus(VariableSet freeVariables) { - boolean forAllCondition = true; + boolean forAllCondition = sub.size() > 0; Vector extractedFilterRelevantToVariables = new Vector(); for (Binding binding : sub) { VariableNode bindingVariableNode = binding.getVariableNode(); @@ -478,7 +482,7 @@ public VariableNodeStats extractBoundStatus(VariableSet freeVariables) { forAllCondition &= bindingFound; } Substitutions extractedFilterSubs = new LinearSubstitutions(extractedFilterRelevantToVariables); - return new VariableNodeStats(forAllCondition, extractedFilterSubs, this); + return new VariableNodeStats(forAllCondition, extractedFilterSubs, this, freeVariables); } @Override diff --git a/src/sneps/snip/matching/Matcher.java b/src/sneps/snip/matching/Matcher.java index ab4b4a32..598946a4 100644 --- a/src/sneps/snip/matching/Matcher.java +++ b/src/sneps/snip/matching/Matcher.java @@ -30,6 +30,7 @@ public static List match(PropositionNode toBeDeduced) { try { Node leo; Hashtable nodes = Network.getNodes(); + System.out.println(nodes); leo = Network.getNode("Leo"); VariableNode X = (VariableNode) Network.getNode("X"); @@ -48,16 +49,24 @@ public static List match(PropositionNode toBeDeduced) { public static List match(PropositionNode propositionNode, Substitutions currentReportSubs) { List listOfMatches = new ArrayList(); try { - Node leo; + Node nodeMatch; + Match newMatch; + VariableNode variableNode; Hashtable nodes = Network.getNodes(); - leo = Network.getNode("M1"); + System.out.println("Nodes in the Network\n" + nodes + "\n"); - VariableNode X = (VariableNode) Network.getNode("X"); - Substitutions filterSubs = new LinearSubstitutions(); - filterSubs.insert(new Binding(X, leo)); - Match newMatch = new Match(filterSubs, new LinearSubstitutions(), leo, 0); + if (propositionNode.getIdentifier().equals("M1")) { + nodeMatch = Network.getNode("M2"); + newMatch = new Match(new LinearSubstitutions(), new LinearSubstitutions(), nodeMatch, 0); + listOfMatches.add(newMatch); + nodeMatch = Network.getNode("P1"); + variableNode = (VariableNode) Network.getNode("X"); + Substitutions filterSubs = new LinearSubstitutions(); + filterSubs.putIn(new Binding(variableNode, nodeMatch)); + newMatch = new Match(filterSubs, new LinearSubstitutions(), nodeMatch, 0); + listOfMatches.add(newMatch); + } - listOfMatches.add(newMatch); } catch (NodeNotFoundInNetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); From dd85045a62bd24ae740da7b9652fb41f66cef05a Mon Sep 17 00:00:00 2001 From: Youssef Date: Wed, 5 Jun 2019 12:13:21 +0200 Subject: [PATCH 21/22] fixed incorrect algorithm for computing VariableNodeStats in LinearSubstitutions and added more tests --- src/sneps/network/PropositionNode.java | 40 +++++++++--- src/sneps/snip/Filter.java | 2 +- src/sneps/snip/KnownInstances.java | 3 + src/sneps/snip/Runner.java | 7 ++- src/sneps/snip/Switch.java | 8 +-- src/sneps/snip/Test.java | 62 ++++++++++++++----- src/sneps/snip/channels/Channel.java | 4 +- .../snip/matching/LinearSubstitutions.java | 24 ++++--- src/sneps/snip/matching/Matcher.java | 9 ++- 9 files changed, 115 insertions(+), 44 deletions(-) diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 28663836..8ca5ded6 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -108,14 +108,14 @@ protected Channel establishChannel(ChannelTypes type, Object currentElement, Sub Channel extractedChannel = incomingChannels.getChannel(newChannel); if (extractedChannel == null) { /* BEGIN - Helpful Prints */ - System.out.println("Channel successfully created"); + System.out.println("Channel is successfully created and used for further operations"); /* END - Helpful Prints */ ((PropositionNode) evaluatedReporter).addToOutgoingChannels(newChannel); addToIncomingChannels(newChannel); return newChannel; } /* BEGIN - Helpful Prints */ - System.out.println("Channel was already created"); + System.out.println("Channel is already established and retrieved for further operations"); /* END - Helpful Prints */ return extractedChannel; @@ -131,10 +131,13 @@ protected Channel establishChannel(ChannelTypes type, Object currentElement, Sub public boolean sendReport(Report report, Channel channel) { try { if (channel.testReportToSend(report)) { - System.out.println("Report instance (" + report + ") was successfuly sent over (" + channel + ")"); + System.out.println("\nReport instance:" + "\n~~~~\n" + report + "\n~~~~\n" + + "was successfuly sent from " + channel.getReporter().getIdentifier() + " to " + + channel.getRequester().getIdentifier() + "\n"); } } catch (NotAPropositionNodeException | NodeNotFoundInNetworkException e) { - System.out.println("Report instance (" + report + ") could not be sent."); + System.out.println("\nReport instance:" + "\n~~~~\n" + report + "\n~~~~\n" + "could not be sent from " + + channel.getReporter().getIdentifier() + " to " + channel.getRequester().getIdentifier() + "\n"); e.printStackTrace(); } return false; @@ -251,6 +254,7 @@ protected void sendRequestsToNodeSet(NodeSet ns, Substitutions filterSubs, Strin Channel newChannel = establishChannel(channelType, sentTo, null, filterSubs, contextID, -1); sentTo.receiveRequest(newChannel); } + System.out.println("Sent requests to " + ns.size() + " dominating rule nodes"); } /*** @@ -297,19 +301,39 @@ public void receiveReport(Channel channel) { } public void deduce() { + /* BEGIN - Helpful Prints */ + System.out.println("deduce() method initated."); + System.out.println("-------------------------\n"); + /* END - Helpful Prints */ Runner.initiate(); String currentContextName = Controller.getCurrentContextName(); + /* BEGIN - Helpful Prints */ + System.out.println("\nSending to rule nodes during deduce()\n"); + /* END - Helpful Prints */ getNodesToSendRequest(ChannelTypes.RuleCons, currentContextName, null); + /* BEGIN - Helpful Prints */ + System.out.println("\nSending to matching nodes during deduce()\n"); + /* BEGIN - Helpful Prints */ getNodesToSendRequest(ChannelTypes.MATCHED, currentContextName, null); // what to return here ? System.out.println(Runner.run()); } public void add() { + /* BEGIN - Helpful Prints */ + System.out.println("add() method initated.\n"); + System.out.println("-------------------------"); + /* END - Helpful Prints */ Runner.initiate(); String currentContextName = Controller.getCurrentContextName(); boolean reportSign = Controller.isNegated(this); + /* BEGIN - Helpful Prints */ + System.out.println("\nSending to rule nodes during add()\n"); + /* END - Helpful Prints */ getNodesToSendReport(ChannelTypes.RuleAnt, currentContextName, null, reportSign, InferenceTypes.FORWARD); + /* BEGIN - Helpful Prints */ + System.out.println("\nSending to matching nodes during add()\n"); + /* END - Helpful Prints */ getNodesToSendReport(ChannelTypes.MATCHED, currentContextName, null, reportSign, InferenceTypes.FORWARD); System.out.println(Runner.run()); } @@ -666,9 +690,11 @@ public boolean isWhQuestion(Substitutions filterSubs) { VariableNodeStats currentNodeStats = computeNodeStats(filterSubs); /* BEGIN - Helpful Prints */ System.out.println("\n\u2022 Testing if " + getIdentifier() + " is a Wh-Question:"); - System.out.println(currentNodeStats.toString() + "\n"); + System.out.println(currentNodeStats.toString()); + System.out.println("> Result: " + + (currentNodeStats.getNodeFreeVariables().size() > 0 && !currentNodeStats.areAllVariablesBound())); /* END - Helpful Prints */ - return !currentNodeStats.areAllVariablesBound(); + return currentNodeStats.getNodeFreeVariables().size() > 0 && !currentNodeStats.areAllVariablesBound(); } /*** @@ -746,7 +772,7 @@ protected void processSingleRequestsChannel(Channel currentChannel) // TODO change the subs to hashsubs int propNodeId = getId(); PropositionSet supportPropSet = new PropositionSet(); - supportPropSet.add(propNodeId); + supportPropSet = supportPropSet.add(propNodeId); boolean reportSign = Controller.isNegated(this); Report reply = new Report(new LinearSubstitutions(), supportPropSet, reportSign, InferenceTypes.BACKWARD); sendReport(reply, currentChannel); diff --git a/src/sneps/snip/Filter.java b/src/sneps/snip/Filter.java index 31e4759a..3abfdd54 100644 --- a/src/sneps/snip/Filter.java +++ b/src/sneps/snip/Filter.java @@ -33,7 +33,7 @@ public boolean canPass(Report report) { Binding currentFilterBinding = substitutions.getBinding(i); VariableNode currentFilterVariableNode = currentFilterBinding.getVariableNode(); Binding currentReportBinding = report.getSubstitutions().getBindingByVariable(currentFilterVariableNode); - System.out.println("Bindings " + currentFilterBinding + " " + report.getSubstitutions()); +// System.out.println("Bindings " + currentFilterBinding + " " + report.getSubstitutions()); if (currentReportBinding != null && currentFilterBinding.getNode() != currentReportBinding.getNode()) return false; } diff --git a/src/sneps/snip/KnownInstances.java b/src/sneps/snip/KnownInstances.java index 3de754ef..7b56e354 100644 --- a/src/sneps/snip/KnownInstances.java +++ b/src/sneps/snip/KnownInstances.java @@ -1,5 +1,6 @@ package sneps.snip; +import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; @@ -19,6 +20,8 @@ public KnownInstances() { public void addReport(Report report) { Substitutions reportSubs = report.getSubstitutions(); Set reportsSet = instances.remove(reportSubs); + if (reportsSet == null) + reportsSet = new HashSet(); reportsSet.add(report); instances.put(reportSubs, reportsSet); } diff --git a/src/sneps/snip/Runner.java b/src/sneps/snip/Runner.java index 59911a5a..8771ac72 100644 --- a/src/sneps/snip/Runner.java +++ b/src/sneps/snip/Runner.java @@ -31,15 +31,16 @@ public static String run() { String sequence = ""; main: while (!highQueue.isEmpty() || !lowQueue.isEmpty() || !actQueue.isEmpty()) { while (!highQueue.isEmpty()) { - System.out.println("In HighQueue"); + System.out.println("\n\u2202 Runner: In HighQueue"); Node toRunNext = highQueue.poll(); - System.out.println(toRunNext); + System.out.println("Processing " + toRunNext.getIdentifier() + " reports."); toRunNext.processReports(); sequence += 'H'; } while (!lowQueue.isEmpty()) { - System.out.println("In LowQueue"); + System.out.println("\n\u2202 Runner: In LowQueue"); Node toRunNext = lowQueue.poll(); + System.out.println("Processing " + toRunNext.getIdentifier() + " requests."); toRunNext.processRequests(); sequence += 'L'; if (!highQueue.isEmpty()) diff --git a/src/sneps/snip/Switch.java b/src/sneps/snip/Switch.java index e626b6fd..4e44bb8f 100644 --- a/src/sneps/snip/Switch.java +++ b/src/sneps/snip/Switch.java @@ -32,13 +32,13 @@ public void switchReport(Report r) { if (b != null) { b.setVariable((VariableNode) this.substitutions.getBinding(i).getNode()); } else { - System.out.println("there u go " + this.substitutions.getBinding(i)); + System.out.println("There u go " + this.substitutions.getBinding(i)); r.getSubstitutions().putIn(this.substitutions.getBinding(i)); - System.out.println("size now " + r.getSubstitutions().cardinality()); + System.out.println("Size now " + r.getSubstitutions().cardinality()); } } - System.out.println(r.getSubstitutions().isNew()); - System.out.println("Done Switching:\n" + r.getSubstitutions()); + System.out.println("No substitutions are done, brand new report: " + r.getSubstitutions().isNew()); + System.out.println("Done Switching:" + r.getSubstitutions()); // {a/X, b/Y}, {X/W, Y/Z, K/C} => {a/W, b/Z, K/C} // r.getSubstitutions().unionIn(s); } diff --git a/src/sneps/snip/Test.java b/src/sneps/snip/Test.java index b1dd414a..c8db17af 100644 --- a/src/sneps/snip/Test.java +++ b/src/sneps/snip/Test.java @@ -14,13 +14,18 @@ import sneps.network.Node; import sneps.network.PropositionNode; import sneps.network.VariableNode; +import sneps.network.cables.DownCable; +import sneps.network.cables.DownCableSet; import sneps.network.classes.CaseFrame; import sneps.network.classes.Relation; +import sneps.network.classes.RelationsRestrictedCaseFrame; import sneps.network.classes.Semantic; import sneps.network.classes.SemanticHierarchy; import sneps.network.classes.Wire; +import sneps.network.classes.setClasses.NodeSet; import sneps.network.classes.setClasses.PropositionSet; import sneps.network.classes.term.Molecular; +import sneps.network.classes.term.Open; import sneps.network.classes.term.Variable; import sneps.snebr.Controller; import sneps.snip.channels.Channel; @@ -28,6 +33,7 @@ import sneps.snip.matching.Binding; import sneps.snip.matching.LinearSubstitutions; import sneps.snip.matching.Substitutions; +import sneps.snip.rules.AndEntailment; public class Test { /* Report sending (support ) */ @@ -36,37 +42,49 @@ public class Test { /* add */ /* RuleResponse returns M4's channel ma3 el report el mafroud ytb3t always */ public static void main(String[] args) throws Exception { + Network.defineDefaults(); Semantic.createDefaultSemantics(); - + Relation.createDefaultRelations(); /* Case frame creation - [member, class] */ LinkedList relationSet = new LinkedList(); relationSet.add(Network.defineRelation("member", "Proposition")); relationSet.add(Network.defineRelation("class", "Proposition")); CaseFrame classMemberCF = Network.defineCaseFrame("Proposition", relationSet); + + LinkedList relationSet1 = new LinkedList(); + relationSet1.add(Network.defineRelation("object", "Proposition")); + relationSet1.add(Network.defineRelation("property", "Proposition")); + CaseFrame objectPropertyCF = Network.defineCaseFrame("Proposition", relationSet1); + LinkedList relationSet2 = new LinkedList(); + relationSet2.add(Network.defineRelation("ant", "ant")); + relationSet2.add(Network.defineRelation("cq", "cq")); + relationSet2.add(Network.defineRelation("quant", "quant")); + CaseFrame antConsQuantCF = Network.defineCaseFrame("AntsCons", relationSet1); + Node leo = Network.buildBaseNode("Leo", SemanticHierarchy.getSemantic("Proposition")); Node roger = Network.buildBaseNode("Roger", SemanticHierarchy.getSemantic("Proposition")); Node fido = Network.buildBaseNode("Fido", SemanticHierarchy.getSemantic("Proposition")); Node dog = Network.buildBaseNode("Dog", SemanticHierarchy.getSemantic("Proposition")); + Node loyal = Network.buildBaseNode("Loyal", SemanticHierarchy.getSemantic("Proposition")); + VariableNode X = Network.buildVariableNode("X"); VariableNode Y = Network.buildVariableNode("Y"); ArrayList wires = new ArrayList(); wires.add(new Wire(Network.getRelation("member"), fido)); wires.add(new Wire(Network.getRelation("class"), dog)); Node fidoIsADog = Network.buildMolecularNode(wires, classMemberCF); + wires.clear(); + wires.add(new Wire(Network.getRelation("member"), leo)); + wires.add(new Wire(Network.getRelation("class"), dog)); + Node leoIsADog = Network.buildMolecularNode(wires, classMemberCF); try { Controller.addPropToContext("default", fidoIsADog.getId()); + Controller.addPropToContext("default", leoIsADog.getId()); } catch (ContextNameDoesntExistException e) { // TODO Auto-generated catch block e.printStackTrace(); } - wires.clear(); - wires.add(new Wire(Network.getRelation("member"), leo)); - wires.add(new Wire(Network.getRelation("class"), dog)); - Node leoIsADog = Network.buildMolecularNode(wires, classMemberCF); - wires.clear(); - wires.add(new Wire(Network.getRelation("member"), roger)); - wires.add(new Wire(Network.getRelation("class"), dog)); - Node rogerIsADog = Network.buildMolecularNode(wires, classMemberCF); + wires.clear(); wires.add(new Wire(Network.getRelation("member"), X)); wires.add(new Wire(Network.getRelation("class"), dog)); @@ -75,17 +93,29 @@ public static void main(String[] args) throws Exception { wires.add(new Wire(Network.getRelation("member"), Y)); wires.add(new Wire(Network.getRelation("class"), dog)); Node yIsADog = Network.buildMolecularNode(wires, classMemberCF); + wires.clear(); + wires.add(new Wire(Network.getRelation("object"), X)); + wires.add(new Wire(Network.getRelation("property"), loyal)); + Node xIsLoyal = Network.buildMolecularNode(wires, objectPropertyCF); /* * Knowledge Base established : [Dog(Leo), Dog(Fido), Dog(Roger), Dog(X), * Dog(Y)] */ - - Substitutions filterSubs = new LinearSubstitutions(); - filterSubs.insert(new Binding(X, fido)); - -// Report report = new Report(filterSubs, new PropositionSet(), true, InferenceTypes.BACKWARD); -// channel.testReportToSend(report); - ((PropositionNode) fidoIsADog).deduce(); + wires.clear(); + wires.add(new Wire(Relation.andAnt, xIsADog)); + wires.add(new Wire(Relation.cq, xIsLoyal)); + Node ifXIsADogThenXIsLoyal = Network.buildMolecularNode(wires, RelationsRestrictedCaseFrame.andRule); +// wires.clear(); +// wires.add(new Wire(Network.getRelation("member"), roger)); +// wires.add(new Wire(Network.getRelation("class"), dog)); +// Node rogerIsADog = Network.buildMolecularNode(wires, classMemberCF); + Hashtable nodes = Network.getNodes(); + System.out.println("Nodes in the Network\n" + nodes + "\n"); +// Substitutions filterSubs = new LinearSubstitutions(); +// filterSubs.putIn(new Binding(X, nodes.get("Leo"))); +// filterSubs.putIn(new Binding(Y, nodes.get("Roger"))); +// ((PropositionNode) leoIsADog).isWhQuestion(filterSubs); + ((PropositionNode) xIsLoyal).deduce(); } } diff --git a/src/sneps/snip/channels/Channel.java b/src/sneps/snip/channels/Channel.java index afe9d08f..d8ee8984 100644 --- a/src/sneps/snip/channels/Channel.java +++ b/src/sneps/snip/channels/Channel.java @@ -55,7 +55,8 @@ public void setFilter(Filter filter) { public boolean testReportToSend(Report report) throws NotAPropositionNodeException, NodeNotFoundInNetworkException { boolean passTest = filter.canPass(report); // TODO te be reviewed if (passTest && report.anySupportAssertedInContext(getContextName())) { - System.out.println("\nThe switcher data:\n" + switcher); + + System.out.println("The switcher data:" + switcher); switcher.switchReport(report); PropositionNode requesterNode = (PropositionNode) getRequester(); requesterNode.receiveReport(this); @@ -158,4 +159,5 @@ public boolean equals(Object obj) { return super.equals(obj); } + } diff --git a/src/sneps/snip/matching/LinearSubstitutions.java b/src/sneps/snip/matching/LinearSubstitutions.java index 241595e1..b1c31574 100644 --- a/src/sneps/snip/matching/LinearSubstitutions.java +++ b/src/sneps/snip/matching/LinearSubstitutions.java @@ -469,17 +469,21 @@ public void insertOrUpdate(Binding mb) { * @return VariableNodeStats */ public VariableNodeStats extractBoundStatus(VariableSet freeVariables) { - boolean forAllCondition = sub.size() > 0; + boolean forAllCondition = freeVariables.size() > 0 && sub.size() > 0; Vector extractedFilterRelevantToVariables = new Vector(); - for (Binding binding : sub) { - VariableNode bindingVariableNode = binding.getVariableNode(); - boolean bindingFound = false; - Variable bindingVariable = (Variable) bindingVariableNode.getTerm(); - for (Variable variable : freeVariables) - bindingFound |= variable.getIdentifier().equals(bindingVariable.getIdentifier()); - if (bindingFound) - extractedFilterRelevantToVariables.add(binding); - forAllCondition &= bindingFound; + for (Variable variable : freeVariables) { + boolean variableFound = false; + for (Binding binding : sub) { + VariableNode bindingVariableNode = binding.getVariableNode(); + Variable bindingVariable = (Variable) bindingVariableNode.getTerm(); + variableFound |= variable.getIdentifier().equals(bindingVariable.getIdentifier()); + if (variableFound) { + extractedFilterRelevantToVariables.add(binding); + break; + } + } + forAllCondition &= variableFound; + } Substitutions extractedFilterSubs = new LinearSubstitutions(extractedFilterRelevantToVariables); return new VariableNodeStats(forAllCondition, extractedFilterSubs, this, freeVariables); diff --git a/src/sneps/snip/matching/Matcher.java b/src/sneps/snip/matching/Matcher.java index 598946a4..dfb07abf 100644 --- a/src/sneps/snip/matching/Matcher.java +++ b/src/sneps/snip/matching/Matcher.java @@ -52,8 +52,6 @@ public static List match(PropositionNode propositionNode, Substitutions c Node nodeMatch; Match newMatch; VariableNode variableNode; - Hashtable nodes = Network.getNodes(); - System.out.println("Nodes in the Network\n" + nodes + "\n"); if (propositionNode.getIdentifier().equals("M1")) { nodeMatch = Network.getNode("M2"); @@ -65,6 +63,13 @@ public static List match(PropositionNode propositionNode, Substitutions c filterSubs.putIn(new Binding(variableNode, nodeMatch)); newMatch = new Match(filterSubs, new LinearSubstitutions(), nodeMatch, 0); listOfMatches.add(newMatch); + } else { + nodeMatch = Network.getNode("M2"); + newMatch = new Match(new LinearSubstitutions(), new LinearSubstitutions(), nodeMatch, 0); + listOfMatches.add(newMatch); + nodeMatch = Network.getNode("M1"); + newMatch = new Match(new LinearSubstitutions(), new LinearSubstitutions(), nodeMatch, 0); + listOfMatches.add(newMatch); } } catch (NodeNotFoundInNetworkException e) { From 699b5ccbd30716356453fe018f37a81c0178ab4c Mon Sep 17 00:00:00 2001 From: Youssef Date: Sat, 8 Jun 2019 20:04:20 +0200 Subject: [PATCH 22/22] added toString methods for data structures for visual content during testing --- src/sneps/network/PropositionNode.java | 110 ++++++++++++----------- src/sneps/network/RuleNode.java | 83 ++++++++++------- src/sneps/snip/KnownInstances.java | 14 +++ src/sneps/snip/Test.java | 28 +++--- src/sneps/snip/classes/RuleResponse.java | 2 +- src/sneps/snip/matching/Matcher.java | 16 ++-- 6 files changed, 152 insertions(+), 101 deletions(-) diff --git a/src/sneps/network/PropositionNode.java b/src/sneps/network/PropositionNode.java index 8ca5ded6..29daa7a4 100644 --- a/src/sneps/network/PropositionNode.java +++ b/src/sneps/network/PropositionNode.java @@ -91,24 +91,26 @@ protected Channel establishChannel(ChannelTypes type, Object currentElement, Sub System.out.println("Trying to establish a channel from " + requesterIdent + " to " + reporterIdent); /* END - Helpful Prints */ Substitutions switchLinearSubs = switchSubs == null ? new LinearSubstitutions() : switchSubs; + Substitutions filterLinearSubs = filterSubs == null ? new LinearSubstitutions() : filterSubs; Channel newChannel; switch (type) { case MATCHED: - newChannel = new MatchChannel(switchLinearSubs, filterSubs, contextName, this, evaluatedReporter, true, - matchType); + newChannel = new MatchChannel(switchLinearSubs, filterLinearSubs, contextName, this, evaluatedReporter, + true, matchType); break; case RuleAnt: - newChannel = new AntecedentToRuleChannel(switchLinearSubs, filterSubs, contextName, this, evaluatedReporter, - true); + newChannel = new AntecedentToRuleChannel(switchLinearSubs, filterLinearSubs, contextName, this, + evaluatedReporter, true); default: - newChannel = new RuleToConsequentChannel(switchLinearSubs, filterSubs, contextName, this, evaluatedReporter, - true); + newChannel = new RuleToConsequentChannel(switchLinearSubs, filterLinearSubs, contextName, this, + evaluatedReporter, true); } ChannelSet incomingChannels = getIncomingChannels(); Channel extractedChannel = incomingChannels.getChannel(newChannel); if (extractedChannel == null) { /* BEGIN - Helpful Prints */ - System.out.println("Channel is successfully created and used for further operations"); + System.out.println("Channel of type " + newChannel.getClass() + + " is successfully created and used for further operations"); /* END - Helpful Prints */ ((PropositionNode) evaluatedReporter).addToOutgoingChannels(newChannel); addToIncomingChannels(newChannel); @@ -179,11 +181,13 @@ protected void sendReportToNodeSet(NodeSet ns, Report toBeSent, String contextNa Channel newChannel = establishChannel(channelType, sentTo, null, reportSubs, contextName, -1); sendReport(toBeSent, newChannel); } + System.out.println("Sent report to " + ns.size() + " nodes"); } protected void sendReportsToNodeSet(NodeSet ns, ReportSet toBeSent, String contextName, ChannelTypes channelType) { for (Report report : toBeSent) sendReportToNodeSet(ns, report, contextName, channelType); + System.out.println("Sent reports to " + ns.size() + " nodes"); } /*** @@ -204,12 +208,14 @@ protected void sendReportToMatches(List list, Report toBeSent, String con matchType); sendReport(toBeSent, newChannel); } + System.out.println("Sent report to " + list.size() + " matched nodes"); } protected void sendReportsToMatches(List list, ReportSet reports, String contextId) { for (Report report : reports) { sendReportToMatches(list, report, contextId); } + System.out.println("Sent reports to " + list.size() + " matched nodes"); } protected void sendReportToChannelSet(ChannelSet filteredNodeSet, Report toBeSent) { @@ -300,50 +306,13 @@ public void receiveReport(Channel channel) { channel.setReportProcessed(true); } - public void deduce() { - /* BEGIN - Helpful Prints */ - System.out.println("deduce() method initated."); - System.out.println("-------------------------\n"); - /* END - Helpful Prints */ - Runner.initiate(); - String currentContextName = Controller.getCurrentContextName(); - /* BEGIN - Helpful Prints */ - System.out.println("\nSending to rule nodes during deduce()\n"); - /* END - Helpful Prints */ - getNodesToSendRequest(ChannelTypes.RuleCons, currentContextName, null); - /* BEGIN - Helpful Prints */ - System.out.println("\nSending to matching nodes during deduce()\n"); - /* BEGIN - Helpful Prints */ - getNodesToSendRequest(ChannelTypes.MATCHED, currentContextName, null); - // what to return here ? - System.out.println(Runner.run()); - } - - public void add() { - /* BEGIN - Helpful Prints */ - System.out.println("add() method initated.\n"); - System.out.println("-------------------------"); - /* END - Helpful Prints */ - Runner.initiate(); - String currentContextName = Controller.getCurrentContextName(); - boolean reportSign = Controller.isNegated(this); - /* BEGIN - Helpful Prints */ - System.out.println("\nSending to rule nodes during add()\n"); - /* END - Helpful Prints */ - getNodesToSendReport(ChannelTypes.RuleAnt, currentContextName, null, reportSign, InferenceTypes.FORWARD); - /* BEGIN - Helpful Prints */ - System.out.println("\nSending to matching nodes during add()\n"); - /* END - Helpful Prints */ - getNodesToSendReport(ChannelTypes.MATCHED, currentContextName, null, reportSign, InferenceTypes.FORWARD); - System.out.println(Runner.run()); - } - protected void getNodesToSendReport(ChannelTypes channelType, String currentContextName, Substitutions substitutions, boolean reportSign, InferenceTypes inferenceType) { try { PropositionSet supportPropSet = new PropositionSet(); supportPropSet.add(getId()); - Report toBeSent = new Report(substitutions, supportPropSet, reportSign, inferenceType); + Substitutions substitutionsLinear = substitutions == null ? new LinearSubstitutions() : substitutions; + Report toBeSent = new Report(substitutionsLinear, supportPropSet, reportSign, inferenceType); switch (channelType) { case MATCHED: List matchesReturned = Matcher.match(this, substitutions); @@ -745,6 +714,45 @@ protected PropositionNode buildNodeSubstitutions(Substitutions subs) { // TODO nawar } + public void deduce() { + /* BEGIN - Helpful Prints */ + System.out.println("deduce() method initated."); + System.out.println("-------------------------\n"); + /* END - Helpful Prints */ + Runner.initiate(); + String currentContextName = Controller.getCurrentContextName(); + /* BEGIN - Helpful Prints */ + System.out.println("\nSending to rule nodes during deduce()\n"); + /* END - Helpful Prints */ + getNodesToSendRequest(ChannelTypes.RuleCons, currentContextName, null); + /* BEGIN - Helpful Prints */ + System.out.println("\nSending to matching nodes during deduce()\n"); + /* BEGIN - Helpful Prints */ + getNodesToSendRequest(ChannelTypes.MATCHED, currentContextName, null); + // what to return here ? + Runner.run(); + System.out.println(knownInstances.toString()); + } + + public void add() { + /* BEGIN - Helpful Prints */ + System.out.println("add() method initated.\n"); + System.out.println("-------------------------"); + /* END - Helpful Prints */ + Runner.initiate(); + String currentContextName = Controller.getCurrentContextName(); + boolean reportSign = Controller.isNegated(this); + /* BEGIN - Helpful Prints */ + System.out.println("\nSending to rule nodes during add()\n"); + /* END - Helpful Prints */ + getNodesToSendReport(ChannelTypes.RuleAnt, currentContextName, null, reportSign, InferenceTypes.FORWARD); + /* BEGIN - Helpful Prints */ + System.out.println("\nSending to matching nodes during add()\n"); + /* END - Helpful Prints */ + getNodesToSendReport(ChannelTypes.MATCHED, currentContextName, null, reportSign, InferenceTypes.FORWARD); + System.out.println(Runner.run()); + } + public void processRequests() { for (Channel outChannel : outgoingChannels) try { @@ -827,10 +835,12 @@ protected void processSingleReportsChannel(Channel currentChannel) boolean forwardReportType = reportToBeBroadcasted.getInferenceType() == InferenceTypes.FORWARD; if (currentChannel instanceof RuleToConsequentChannel) { PropositionNode supportNode = buildNodeSubstitutions(currentReport.getSubstitutions()); - supportNode.addJustificationBasedSupport(reportToBeBroadcasted.getSupport()); - PropositionSet reportSupportPropSet = new PropositionSet(); - reportSupportPropSet.add(supportNode.getId()); - reportToBeBroadcasted.setSupport(reportSupportPropSet); + if (supportNode != null) { + supportNode.addJustificationBasedSupport(reportToBeBroadcasted.getSupport()); + PropositionSet reportSupportPropSet = new PropositionSet(); + reportSupportPropSet.add(supportNode.getId()); + reportToBeBroadcasted.setSupport(reportSupportPropSet); + } } // TODO: GRADED PROPOSITIONS HANDLING REPORTS if (forwardReportType) { diff --git a/src/sneps/network/RuleNode.java b/src/sneps/network/RuleNode.java index 59c188e0..bd593235 100644 --- a/src/sneps/network/RuleNode.java +++ b/src/sneps/network/RuleNode.java @@ -1,6 +1,7 @@ package sneps.network; import java.io.Serializable; +import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; @@ -119,34 +120,53 @@ protected void processNodes(NodeSet antNodes) { } public Collection applyRuleHandler(Report report, Channel currentChannel) { - Node currentChannelReporter = currentChannel.getReporter(); - String contextID = currentChannel.getContextName(); - // Context context = SNeBR.getContextByID(contextID); - RuleUseInfo rui; - if (report.isPositive()) { - FlagNode fn = new FlagNode(currentChannelReporter, report.getSupport(), 1); - FlagNodeSet fns = new FlagNodeSet(); - fns.putIn(fn); - rui = new RuleUseInfo(report.getSubstitutions(), 1, 0, fns); - } else { - FlagNode fn = new FlagNode(currentChannelReporter, report.getSupport(), 2); - FlagNodeSet fns = new FlagNodeSet(); - fns.putIn(fn); - rui = new RuleUseInfo(report.getSubstitutions(), 0, 1, fns); - } - RuleUseInfoSet crtemp = null; - if (this.getContextRUISSet().hasContext(contextID)) { - crtemp = this.getContextRUISSet().getContextRUIS(contextID); - } else { - crtemp = addContextRUIS(contextID); - } - RuleUseInfoSet res = crtemp.add(rui); - if (res == null) - res = new RuleUseInfoSet(); - for (RuleUseInfo tRui : res) { - sendRui(tRui, contextID); - } - return null; +// Node currentChannelReporter = currentChannel.getReporter(); +// String contextID = currentChannel.getContextName(); +// // Context context = SNeBR.getContextByID(contextID); +// RuleUseInfo rui; +// if (report.isPositive()) { +// FlagNode fn = new FlagNode(currentChannelReporter, report.getSupport(), 1); +// FlagNodeSet fns = new FlagNodeSet(); +// fns.putIn(fn); +// rui = new RuleUseInfo(report.getSubstitutions(), 1, 0, fns); +// } else { +// FlagNode fn = new FlagNode(currentChannelReporter, report.getSupport(), 2); +// FlagNodeSet fns = new FlagNodeSet(); +// fns.putIn(fn); +// rui = new RuleUseInfo(report.getSubstitutions(), 0, 1, fns); +// } +// RuleUseInfoSet crtemp = null; +// if (this.getContextRUISSet().hasContext(contextID)) { +// crtemp = this.getContextRUISSet().getContextRUIS(contextID); +// } else { +// crtemp = addContextRUIS(contextID); +// } +// RuleUseInfoSet res = crtemp.add(rui); +// if (res == null) +// res = new RuleUseInfoSet(); +// for (RuleUseInfo tRui : res) { +// sendRui(tRui, contextID); +// } +// return null; + Hashtable nodes = Network.getNodes(); + Collection toBeReturned = new ArrayList(); + RuleResponse value1 = new RuleResponse(); + Substitutions reportSubs1 = new LinearSubstitutions(); + reportSubs1.putIn(new Binding((VariableNode) nodes.get("X"), nodes.get("Leo"))); + value1.addReport(new Report(reportSubs1, new PropositionSet(), true, InferenceTypes.BACKWARD)); + value1.addChannel(((PropositionNode) nodes.get("P3")).establishChannel(ChannelTypes.RuleCons, this, + new LinearSubstitutions(), new LinearSubstitutions(), Controller.getCurrentContextName(), -1)); + toBeReturned.add(value1); + + RuleResponse value2 = new RuleResponse(); + Substitutions reportSubs2 = new LinearSubstitutions(); + reportSubs2.putIn(new Binding((VariableNode) nodes.get("X"), nodes.get("Fido"))); + value2.addReport(new Report(reportSubs2, new PropositionSet(), true, InferenceTypes.BACKWARD)); + value2.addChannel(((PropositionNode) nodes.get("P3")).establishChannel(ChannelTypes.RuleCons, this, + new LinearSubstitutions(), new LinearSubstitutions(), Controller.getCurrentContextName(), -1)); + toBeReturned.add(value2); + return toBeReturned; + } abstract protected void sendRui(RuleUseInfo tRui, String contextID); @@ -409,8 +429,10 @@ protected void processSingleRequestsChannel(Channel currentChannel) /* Case 1 */ if (assertedInContext(currentContextName)) { requestAntecedentsNotAlreadyWorkingOn(currentChannel, false); - } else + } else { super.processSingleRequestsChannel(currentChannel); + return; + } } else { VariableNodeStats ruleNodeStats = computeNodeStats(filterSubs); boolean ruleNodeAllVariablesBound = ruleNodeStats.areAllVariablesBound(); @@ -431,6 +453,7 @@ protected void processSingleRequestsChannel(Channel currentChannel) } /* TODO instead of calling super we know it's the case of isWhQuestion */ super.processSingleRequestsChannel(currentChannel); + return; } } else super.processSingleRequestsChannel(currentChannel); @@ -500,7 +523,7 @@ protected void processSingleReportsChannel(Channel currentChannel) */ /* always sue the extracted report subs in the requests */ - + for (Report knownInstance : knownInstances) { Substitutions knownInstanceSubstitutions = knownInstance.getSubstitutions(); boolean subSetCheck = ruleNodeExtractedSubs.isSubSet(knownInstanceSubstitutions); diff --git a/src/sneps/snip/KnownInstances.java b/src/sneps/snip/KnownInstances.java index 7b56e354..ca7835e1 100644 --- a/src/sneps/snip/KnownInstances.java +++ b/src/sneps/snip/KnownInstances.java @@ -37,4 +37,18 @@ public Iterator iterator() { allMergedReports.addAll(set); return allMergedReports.iterator(); } + + @Override + public String toString() { + String res = "[ "; + for (Set iterable_element : instances.values()) { + res += iterable_element.toString() + ", "; + } + + if (res.length() > 2) + res = res.substring(0, res.length() - 2); + else + res += "]"; + return res; + } } diff --git a/src/sneps/snip/Test.java b/src/sneps/snip/Test.java index c8db17af..d35bf9a0 100644 --- a/src/sneps/snip/Test.java +++ b/src/sneps/snip/Test.java @@ -77,14 +77,6 @@ public static void main(String[] args) throws Exception { wires.add(new Wire(Network.getRelation("member"), leo)); wires.add(new Wire(Network.getRelation("class"), dog)); Node leoIsADog = Network.buildMolecularNode(wires, classMemberCF); - try { - Controller.addPropToContext("default", fidoIsADog.getId()); - Controller.addPropToContext("default", leoIsADog.getId()); - } catch (ContextNameDoesntExistException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - wires.clear(); wires.add(new Wire(Network.getRelation("member"), X)); wires.add(new Wire(Network.getRelation("class"), dog)); @@ -105,17 +97,27 @@ public static void main(String[] args) throws Exception { wires.add(new Wire(Relation.andAnt, xIsADog)); wires.add(new Wire(Relation.cq, xIsLoyal)); Node ifXIsADogThenXIsLoyal = Network.buildMolecularNode(wires, RelationsRestrictedCaseFrame.andRule); -// wires.clear(); -// wires.add(new Wire(Network.getRelation("member"), roger)); -// wires.add(new Wire(Network.getRelation("class"), dog)); -// Node rogerIsADog = Network.buildMolecularNode(wires, classMemberCF); + wires.clear(); + wires.add(new Wire(Network.getRelation("member"), roger)); + wires.add(new Wire(Network.getRelation("class"), dog)); + Node rogerIsADog = Network.buildMolecularNode(wires, classMemberCF); + try { + Controller.addPropToContext("default", fidoIsADog.getId()); + Controller.addPropToContext("default", leoIsADog.getId()); + Controller.addPropToContext("default", ifXIsADogThenXIsLoyal.getId()); + Controller.addPropToContext("default", rogerIsADog.getId()); + } catch (ContextNameDoesntExistException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } Hashtable nodes = Network.getNodes(); System.out.println("Nodes in the Network\n" + nodes + "\n"); // Substitutions filterSubs = new LinearSubstitutions(); // filterSubs.putIn(new Binding(X, nodes.get("Leo"))); // filterSubs.putIn(new Binding(Y, nodes.get("Roger"))); // ((PropositionNode) leoIsADog).isWhQuestion(filterSubs); - ((PropositionNode) xIsLoyal).deduce(); +// ((PropositionNode) xIsLoyal).deduce(); + ((PropositionNode) rogerIsADog).add(); } } diff --git a/src/sneps/snip/classes/RuleResponse.java b/src/sneps/snip/classes/RuleResponse.java index 93b9b14f..09a61418 100644 --- a/src/sneps/snip/classes/RuleResponse.java +++ b/src/sneps/snip/classes/RuleResponse.java @@ -21,7 +21,7 @@ public Report getReport() { return report; } - public void setReports(Report report) { + public void setReport(Report report) { this.report = report; } diff --git a/src/sneps/snip/matching/Matcher.java b/src/sneps/snip/matching/Matcher.java index dfb07abf..613cc85e 100644 --- a/src/sneps/snip/matching/Matcher.java +++ b/src/sneps/snip/matching/Matcher.java @@ -53,23 +53,25 @@ public static List match(PropositionNode propositionNode, Substitutions c Match newMatch; VariableNode variableNode; - if (propositionNode.getIdentifier().equals("M1")) { + if (propositionNode.getIdentifier().equals("P1")) { nodeMatch = Network.getNode("M2"); newMatch = new Match(new LinearSubstitutions(), new LinearSubstitutions(), nodeMatch, 0); listOfMatches.add(newMatch); - nodeMatch = Network.getNode("P1"); - variableNode = (VariableNode) Network.getNode("X"); - Substitutions filterSubs = new LinearSubstitutions(); - filterSubs.putIn(new Binding(variableNode, nodeMatch)); - newMatch = new Match(filterSubs, new LinearSubstitutions(), nodeMatch, 0); + nodeMatch = Network.getNode("M1"); + newMatch = new Match(new LinearSubstitutions(), new LinearSubstitutions(), nodeMatch, 0); listOfMatches.add(newMatch); - } else { + } else if (propositionNode.getIdentifier().equals("M3")) { nodeMatch = Network.getNode("M2"); newMatch = new Match(new LinearSubstitutions(), new LinearSubstitutions(), nodeMatch, 0); listOfMatches.add(newMatch); nodeMatch = Network.getNode("M1"); newMatch = new Match(new LinearSubstitutions(), new LinearSubstitutions(), nodeMatch, 0); listOfMatches.add(newMatch); + nodeMatch = Network.getNode("P1"); + variableNode = (VariableNode) Network.getNode("X"); + Substitutions filterSubs = new LinearSubstitutions(); + filterSubs.putIn(new Binding(variableNode, nodeMatch)); + newMatch = new Match(filterSubs, new LinearSubstitutions(), nodeMatch, 0); } } catch (NodeNotFoundInNetworkException e) {