public void testAskSafeRooms() { WumpusKnowledgeBase KB; int t = 0; KB = new WumpusKnowledgeBase(dpll, 2); step(KB, new AgentPercept(false, false, false, false, false), t); AreSetEqual(CollectionFactory.CreateSet <Room>( new Room(1, 1), new Room(1, 2), new Room(2, 1)), KB.askSafeRooms(t)); KB = new WumpusKnowledgeBase(dpll, 2); step(KB, new AgentPercept(true, false, false, false, false), t); AreSetEqual(CollectionFactory.CreateSet <Room>(new Room(1, 1)), KB.askSafeRooms(t)); KB = new WumpusKnowledgeBase(dpll, 2); step(KB, new AgentPercept(false, true, false, false, false), t); AreSetEqual(CollectionFactory.CreateSet <Room>(new Room(1, 1)), KB.askSafeRooms(t)); KB = new WumpusKnowledgeBase(dpll, 2); step(KB, new AgentPercept(true, true, false, false, false), t); AreSetEqual(CollectionFactory.CreateSet <Room>(new Room(1, 1)), KB.askSafeRooms(t)); }
public ProbabilityTable pointwiseProductPOS(ProbabilityTable multiplier, params IRandomVariable[] prodVarOrder) { ProbabilityTable product = new ProbabilityTable(prodVarOrder); if (!product.randomVarInfo.GetKeys() .SequenceEqual( SetOps.union(CollectionFactory.CreateSet <IRandomVariable>(randomVarInfo.GetKeys()), CollectionFactory.CreateSet <IRandomVariable>(multiplier.randomVarInfo.GetKeys())))) { throw new IllegalArgumentException("Specified list deatailing order of mulitplier is inconsistent."); } // If no variables in the product if (1 == product.getValues().Length) { product.getValues()[0] = getValues()[0] * multiplier.getValues()[0]; } else { // Otherwise need to iterate through the product // to calculate its values based on the terms. object[] term1Values = new object[randomVarInfo.Size()]; object[] term2Values = new object[multiplier.randomVarInfo.Size()]; ProbabilityTableIterator di = new ProbabilityTablecIteratorImpl3(term1Values, term2Values, product, multiplier, this); product.iterateOverTable(di); } return(product); }
// function ELIMINATION-ASK(X, e, bn) returns a distribution over X /** * The ELIMINATION-ASK algorithm in Figure 14.11. * * @param X * the query variables. * @param e * observed values for variables E. * @param bn * a Bayes net with variables {X} ∪ E ∪ Y /* Y = hidden * variables // * @return a distribution over the query variables. */ public ICategoricalDistribution eliminationAsk(IRandomVariable[] X, AssignmentProposition[] e, IBayesianNetwork bn) { ISet <IRandomVariable> hidden = CollectionFactory.CreateSet <IRandomVariable>(); ICollection <IRandomVariable> VARS = CollectionFactory.CreateQueue <IRandomVariable>(); calculateVariables(X, e, bn, hidden, VARS); // factors <- [] ICollection <IFactor> factors = CollectionFactory.CreateQueue <IFactor>(); // for each var in ORDER(bn.VARS) do foreach (IRandomVariable var in order(bn, VARS)) { // factors <- [MAKE-FACTOR(var, e) | factors] factors.Insert(0, makeFactor(var, e, bn)); // if var is hidden variable then factors <- SUM-OUT(var, factors) if (hidden.Contains(var)) { factors = sumOut(var, factors, bn); } } // return NORMALIZE(POINTWISE-PRODUCT(factors)) IFactor product = pointwiseProduct(factors); // Note: Want to ensure the order of the product matches the // query variables return(((ProbabilityTable)product.pointwiseProductPOS(_identity, X)).normalize()); }
public virtual ICategoricalDistribution jointDistribution(params IProposition[] propositions) { ProbabilityTable d = null; IProposition conjProp = ProbUtil.constructConjunction(propositions); ISet <IRandomVariable> vars = CollectionFactory.CreateSet <IRandomVariable>(conjProp.getUnboundScope()); if (vars.Size() > 0) { IRandomVariable[] distVars = new IRandomVariable[vars.Size()]; int i = 0; foreach (IRandomVariable rv in vars) { distVars[i] = rv; ++i; } ProbabilityTable ud = new ProbabilityTable(distVars); object[] values = new object[vars.Size()]; CategoricalDistributionIterator di = new CategoricalDistributionIteratorJointDistribution(conjProp, vars, ud, values); IRandomVariable[] X = conjProp.getScope().ToArray(); bayesInference.Ask(X, new AssignmentProposition[0], bayesNet).iterateOver(di); d = ud; } else { // No Unbound Variables, therefore just return // the singular probability related to the proposition. d = new ProbabilityTable(); d.setValue(0, prior(propositions)); } return(d); }
/** * Taken {@code weightedSampleWithReplacement} out of {@link ParticleFiltering} and extended by a minimum weight. * @param samples the samples to be re-sampled. * @param w the probability distribution on the samples. * @return the new set of samples. */ protected ISet <P> extendedWeightedSampleWithReplacement(ISet <P> samples, double[] w) { int i = 0; for (; i < samples.Size(); ++i) { if (w[i] > weightCutOff) { break; } } if (i >= samples.Size()) { return(generateCloud(samples.Size())); /*If all particleCloud are below weightCutOff, generate a new set of samples, as we are lost.*/ } /*WEIGHTED-SAMPLE-WITH-REPLACEMENT:*/ double[] normalizedW = Util.normalize(w); ISet <P> newSamples = CollectionFactory.CreateSet <P>(); P[] array = samples.ToArray(); for (i = 0; i < samples.Size(); ++i) { int selectedSample = (int)ProbUtil.sample(randomizer.NextDouble(), sampleIndexes, normalizedW); newSamples.Add((array[selectedSample]).Clone()); } return(newSamples); }
public void testAskPossibleWumpusRooms() { WumpusKnowledgeBase KB; int t = 0; KB = new WumpusKnowledgeBase(dpll, 2); step(KB, new AgentPercept(false, false, false, false, false), t); AreSetEqual(CollectionFactory.CreateSet <Room>(new Room(2, 2)), KB.askPossibleWumpusRooms(t)); KB = new WumpusKnowledgeBase(dpll, 2); step(KB, new AgentPercept(true, false, false, false, false), t); AreSetEqual(CollectionFactory.CreateSet <Room>( new Room(1, 2), new Room(2, 1)), KB.askPossibleWumpusRooms(t)); KB = new WumpusKnowledgeBase(dpll, 3); step(KB, new AgentPercept(false, false, false, false, false), t); AreSetEqual(CollectionFactory.CreateSet <Room>( new Room(1, 3), new Room(2, 2), new Room(2, 3), new Room(3, 1), new Room(3, 2), new Room(3, 3)), KB.askPossibleWumpusRooms(t)); KB.makeActionSentence(new Forward(new AgentPosition(1, 1, AgentPosition.Orientation.FACING_EAST)), t); // Move agent to [2,1] }
public DynamicBayesNet(IBayesianNetwork priorNetwork, IMap <IRandomVariable, IRandomVariable> X_0_to_X_1, ISet <IRandomVariable> E_1, params INode[] rootNodes) : base(rootNodes) { foreach (var x0_x1 in X_0_to_X_1) { IRandomVariable x0 = x0_x1.GetKey(); IRandomVariable x1 = x0_x1.GetValue(); this.X_0.Add(x0); this.X_1.Add(x1); this.X_0_to_X_1.Put(x0, x1); this.X_1_to_X_0.Put(x1, x0); } this.E_1.AddAll(E_1); // Assert the X_0, X_1, and E_1 sets are of expected sizes ISet <IRandomVariable> combined = CollectionFactory.CreateSet <IRandomVariable>(); combined.AddAll(X_0); combined.AddAll(X_1); combined.AddAll(E_1); if (SetOps.difference(CollectionFactory.CreateSet <IRandomVariable>(varToNodeMap.GetKeys()), combined).Size() != 0) { throw new IllegalArgumentException("X_0, X_1, and E_1 do not map correctly to the Nodes describing this Dynamic Bayesian Network."); } this.priorNetwork = priorNetwork; X_1_VariablesInTopologicalOrder.AddAll(GetVariablesInTopologicalOrder()); X_1_VariablesInTopologicalOrder.RemoveAll(X_0); X_1_VariablesInTopologicalOrder.RemoveAll(E_1); }
/** * <pre> * function INFER(clause, usable) returns clauses */ private ISet <Clause> infer(Clause clause, ISet <Clause> usable) { ISet <Clause> resultingClauses = CollectionFactory.CreateSet <Clause>(); // * resolve clause with each member of usable foreach (Clause c in usable) { ISet <Clause> resolvents = clause.binaryResolvents(c); foreach (Clause rc in resolvents) { resultingClauses.Add(rc); } // if using paramodulation to handle equality if (isUseParamodulation()) { ISet <Clause> paras = paramodulation.apply(clause, c, true); foreach (Clause p in paras) { resultingClauses.Add(p); } } } // * return the resulting clauses after applying filter return(getClauseFilter().filter(resultingClauses)); }
public ICategoricalDistribution jointDistribution(params IProposition[] propositions) { ProbabilityTable d = null; IProposition conjProp = ProbUtil.constructConjunction(propositions); ISet <IRandomVariable> vars = CollectionFactory.CreateSet <IRandomVariable>(conjProp.getUnboundScope()); if (vars.Size() > 0) { IRandomVariable[] distVars = vars.ToArray(); ProbabilityTable ud = new ProbabilityTable(distVars); object[] values = new object[vars.Size()]; ProbabilityTable.ProbabilityTableIterator di = new ProbabilityTableIterator(conjProp, ud, values, vars); distribution.iterateOverTable(di); d = ud; } else { // No Unbound Variables, therefore just return // the singular probability related to the proposition. d = new ProbabilityTable(); d.setValue(0, prior(propositions)); } return(d); }
public ProbabilityTable sumOut(params IRandomVariable[] vars) { ISet <IRandomVariable> soutVars = CollectionFactory.CreateSet <IRandomVariable>(this.randomVarInfo.GetKeys()); foreach (IRandomVariable rv in vars) { soutVars.Remove(rv); } ProbabilityTable summedOut = new ProbabilityTable(soutVars); if (1 == summedOut.getValues().Length) { summedOut.getValues()[0] = getSum(); } else { // Otherwise need to iterate through this distribution // to calculate the summed out distribution. object[] termValues = new object[summedOut.randomVarInfo.Size()]; ProbabilityTableIterator di = new ProbabilityTableIteratorImpl(summedOut, termValues); iterateOverTable(di); } return(summedOut); }
public ProbabilityTable pointwiseProduct(ProbabilityTable multiplier) { ISet <IRandomVariable> prodVars = SetOps.union(CollectionFactory.CreateSet <IRandomVariable>(randomVarInfo.GetKeys()), CollectionFactory.CreateSet <IRandomVariable>(multiplier.randomVarInfo.GetKeys())); return(pointwiseProductPOS(multiplier, prodVars.ToArray())); }
/** * Returns the specified sentence as a list of clauses, where each clause is * a disjunction of literals. * * @param aSentence * a sentence in first order logic (predicate calculus) * * @return the specified sentence as a list of clauses, where each clause is * a disjunction of literals. */ public CNF convertToCNF(Sentence aSentence) { // I)mplications Out: Sentence implicationsOut = (Sentence)aSentence.accept(new ImplicationsOut(), null); // N)egations In: Sentence negationsIn = (Sentence)implicationsOut.accept(new NegationsIn(), null); // S)tandardize variables: // For sentences like: // (FORALL x P(x)) V (EXISTS x Q(x)), // which use the same variable name twice, change the name of one of the // variables. Sentence saQuantifiers = (Sentence)negationsIn.accept( new StandardizeQuantiferVariables(substVisitor), CollectionFactory.CreateSet <Variable>()); // Remove explicit quantifiers, by skolemizing existentials // and dropping universals: // E)xistentials Out // A)lls Out: Sentence andsAndOrs = (Sentence)saQuantifiers.accept(new RemoveQuantifiers(parser), CollectionFactory.CreateSet <Variable>()); // D)istribution // V over ^: Sentence orDistributedOverAnd = (Sentence)andsAndOrs.accept(new DistributeOrOverAnd(), null); // O)perators Out return(new CNFConstructor().construct(orDistributedOverAnd)); }
public void testPlanShot() { HybridWumpusAgent hwa = new HybridWumpusAgent(4); // Should be just shoot as are facing the Wumpus Assert.AreEqual(CollectionFactory.CreateQueue <IAction>(new Shoot()), hwa.planShot(new AgentPosition(1, 1, AgentPosition.Orientation.FACING_EAST), CollectionFactory.CreateSet <Room>(new Room(3, 1)), allRooms(4) )); Assert.AreEqual(CollectionFactory.CreateQueue <IAction>( new TurnLeft(AgentPosition.Orientation.FACING_EAST), new Shoot() ), hwa.planShot(new AgentPosition(1, 1, AgentPosition.Orientation.FACING_EAST), CollectionFactory.CreateSet <Room>(new Room(1, 2)), allRooms(4) )); Assert.AreEqual(CollectionFactory.CreateQueue <IAction>( new Forward(new AgentPosition(1, 1, AgentPosition.Orientation.FACING_EAST)), new TurnLeft(AgentPosition.Orientation.FACING_EAST), new Shoot() ), hwa.planShot(new AgentPosition(1, 1, AgentPosition.Orientation.FACING_EAST), CollectionFactory.CreateSet <Room>(new Room(2, 2)), allRooms(4) )); }
/** * AIMA3e p.g. 260:<br> * <quote><i>Pure symbol heuristic:</i> A <b>pure symbol</b> is a symbol * that always appears with the same "sign" in all clauses. For example, in * the three clauses (A | ~B), (~B | ~C), and (C | A), the symbol A is pure * because only the positive literal appears, B is pure because only the * negative literal appears, and C is impure. It is easy to see that if a * sentence has a model, then it has a model with the pure symbols assigned * so as to make their literals true, because doing so can never make a * clause false. Note that, in determining the purity of a symbol, the * algorithm can ignore clauses that are already known to be true in the * model constructed so far. For example, if the model contains B=false, * then the clause (~B | ~C) is already true, and in the remaining clauses C * appears only as a positive literal; therefore C becomes pure.</quote> * * @param symbols * a list of currently unassigned symbols in the model (to be * checked if pure or not). * @param clauses * @param model * @return a proposition symbol and value pair identifying a pure symbol and * a value to be assigned to it, otherwise null if no pure symbol * can be identified. */ protected Pair <PropositionSymbol, bool?> findPureSymbol(ICollection <PropositionSymbol> symbols, ISet <Clause> clauses, Model model) { Pair <PropositionSymbol, bool?> result = null; ISet <PropositionSymbol> symbolsToKeep = CollectionFactory.CreateSet <PropositionSymbol>(symbols); // Collect up possible positive and negative candidate sets of pure // symbols ISet <PropositionSymbol> candidatePurePositiveSymbols = CollectionFactory.CreateSet <PropositionSymbol>(); ISet <PropositionSymbol> candidatePureNegativeSymbols = CollectionFactory.CreateSet <PropositionSymbol>(); foreach (Clause c in clauses) { // Algorithm can ignore clauses that are already known to be true if (true.Equals(model.determineValue(c))) { continue; } // Collect possible candidates, removing all candidates that are // not part of the input list of symbols to be considered. foreach (PropositionSymbol p in c.getPositiveSymbols()) { if (symbolsToKeep.Contains(p)) { candidatePurePositiveSymbols.Add(p); } } foreach (PropositionSymbol n in c.getNegativeSymbols()) { if (symbolsToKeep.Contains(n)) { candidatePureNegativeSymbols.Add(n); } } } // Determine the overlap/intersection between the positive and negative // candidates foreach (PropositionSymbol s in symbolsToKeep) { // Remove the non-pure symbols if (candidatePurePositiveSymbols.Contains(s) && candidatePureNegativeSymbols.Contains(s)) { candidatePurePositiveSymbols.Remove(s); candidatePureNegativeSymbols.Remove(s); } } // We have an implicit preference for positive pure symbols if (candidatePurePositiveSymbols.Size() > 0) { result = new Pair <PropositionSymbol, bool?>(Util.first(candidatePurePositiveSymbols), true); } // We have a negative pure symbol else if (candidatePureNegativeSymbols.Size() > 0) { result = new Pair <PropositionSymbol, bool?>(Util.first(candidatePureNegativeSymbols), false); } return(result); }
public ISet <Variable> collectAllVariables(Term term) { ISet <Variable> variables = CollectionFactory.CreateSet <Variable>(); term.accept(this, variables); return(variables); }
/** * Find the disjoint set that an element belongs to. * * @param element * the element whose disjoint set is being sought. * @return the disjoint set for the element or null if makeSet(element) was * not previously called. */ public ISet <E> find(E element) { // Note: Instantiate normal sets to ensure IdentityHashSet // is not exposed outside of this class. // This also ensures the internal logic cannot // be corrupted externally due to changing sets. return(CollectionFactory.CreateSet <E>(elementToSet.Get(element))); }
protected void addChild(INode childNode) { children = CollectionFactory.CreateSet <INode>(children); children.Add(childNode); children = CollectionFactory.CreateReadOnlySet <INode>(children); }
// Note: The set guarantees the order in which they were // found. public ISet <Variable> collectAllVariables(Sentence sentence) { ISet <Variable> variables = CollectionFactory.CreateSet <Variable>(); sentence.accept(this, variables); return(variables); }
public void addClause(Clause c, ISet <Clause> sos, ISet <Clause> usable) { // Perform forward subsumption elimination bool addToSOS = true; for (int i = minNoLiterals; i < c.getNumberLiterals(); i++) { ISet <Clause> fs = clausesGroupedBySize.Get(i); if (null != fs) { foreach (Clause s in fs) { if (s.subsumes(c)) { addToSOS = false; break; } } } if (!addToSOS) { break; } } if (addToSOS) { sos.Add(c); lightestClauseHeuristic.addedClauseToSOS(c); indexClause(c); // Have added clause, therefore // perform backward subsumption elimination ISet <Clause> subsumed = CollectionFactory.CreateSet <Clause>(); for (int i = c.getNumberLiterals() + 1; i <= maxNoLiterals; i++) { subsumed.Clear(); ISet <Clause> bs = clausesGroupedBySize.Get(i); if (null != bs) { foreach (Clause s in bs) { if (c.subsumes(s)) { subsumed.Add(s); if (sos.Contains(s)) { sos.Remove(s); lightestClauseHeuristic .removedClauseFromSOS(s); } usable.Remove(s); } } bs.RemoveAll(subsumed); } } } }
static BooleanDomain() { // Keep consistent order _possibleValues = CollectionFactory.CreateSet <bool>(); _possibleValues.Add(true); _possibleValues.Add(false); // Ensure cannot be modified _possibleValues = CollectionFactory.CreateReadOnlySet <bool>(_possibleValues); }
static CellWorldAction() { _actions = CollectionFactory.CreateSet <CellWorldAction>(); _actions.Add(Up); _actions.Add(Down); _actions.Add(Left); _actions.Add(Right); _actions.Add(None); }
public ISet <CellWorldAction> actions(Cell <double> s) { // All actions can be performed in each cell // (except terminal states) if (terminals.Contains(s)) { return(CollectionFactory.CreateSet <CellWorldAction>()); } return(CellWorldAction.Actions()); }
//ISet<bool> getPossibleValues() //{ // return _possibleValues; //} public override ISet <object> GetPossibleValues() { ISet <object> obj = CollectionFactory.CreateSet <object>(); foreach (bool value in _possibleValues) { obj.Add(value); } return(obj); }
public override ISet <object> GetPossibleValues() { ISet <object> obj = CollectionFactory.CreateSet <object>(); foreach (int i in possibleValues) { obj.Add(i); } return(obj); }
/** * Applies a move to the samples, creating a new {@link Set}. * @param samples the samples the move will be applied to. * @param move the move to be applied to the samples. * @return a new set of size N containing the moved samples. */ protected ISet <P> applyMove(ISet <P> samples, M move) { ISet <P> newSamples = CollectionFactory.CreateSet <P>(); foreach (P sample in samples) { newSamples.Add(sample.ApplyMovement(move.GenerateNoise())); } return(newSamples); }
public static ISet <Literal> getLiterals(Sentence disjunctiveSentence) { ISet <Literal> result = CollectionFactory.CreateSet <Literal>(); LiteralCollector literalCollector = new LiteralCollector(); result = disjunctiveSentence.accept(literalCollector, result); return(result); }
/** * Create a set for the provided values. * @param values * the sets initial values. * @return a Set of the provided values. */ public static ISet <V> createSet <V>(params V[] values) { ISet <V> set = CollectionFactory.CreateSet <V>(); foreach (V value in values) { set.Add(value); } return(set); }
/** * Create a new conjunction of clauses by taking the clauses from the * current conjunction and adding additional clauses to it. * * @param additionalClauses * the additional clauses to be added to the existing set of * clauses in order to create a new conjunction. * @return a new conjunction of clauses containing the existing and * additional clauses passed in. */ public ConjunctionOfClauses extend(ICollection <Clause> additionalClauses) { ISet <Clause> extendedClauses = CollectionFactory.CreateSet <Clause>(); extendedClauses.AddAll(clauses); extendedClauses.AddAll(additionalClauses); ConjunctionOfClauses result = new ConjunctionOfClauses(extendedClauses); return(result); }
public ISet <Variable> collectAllVariables(Chain chain) { ISet <Variable> variables = CollectionFactory.CreateSet <Variable>(); foreach (Literal l in chain.getLiterals()) { l.getAtomicSentence().accept(this, variables); } return(variables); }
/** * PL-RESOLVE(C<sub>i</sub>, C<sub>j</sub>)<br> * Calculate the set of all possible clauses by resolving its two inputs. * * @param ci * clause 1 * @param cj * clause 2 * @return the set of all possible clauses obtained by resolving its two * inputs. */ public ISet <Clause> plResolve(Clause ci, Clause cj) { ISet <Clause> resolvents = CollectionFactory.CreateSet <Clause>(); // The complementary positive literals from C_i resolvePositiveWithNegative(ci, cj, resolvents); // The complementary negative literals from C_i resolvePositiveWithNegative(cj, ci, resolvents); return(resolvents); }