// // PROTECTED: // // Note: Override this method if you wish to change the initial variable // ordering when dpllSatisfiable is called. protected ICollection <PropositionSymbol> getPropositionSymbolsInSentence(Sentence s) { ICollection <PropositionSymbol> result = CollectionFactory.CreateQueue <PropositionSymbol>( SymbolCollector.getSymbolsFrom(s)); return(result); }
public void ProgramsShouldProduceExpectedUserDeclaredSymbols(DataSet dataSet) { var compilation = new Compilation(TestResourceTypeProvider.CreateRegistrar(), SyntaxFactory.CreateFromText(dataSet.Bicep)); var model = compilation.GetSemanticModel(); var symbols = SymbolCollector .CollectSymbols(model) .OfType <DeclaredSymbol>(); var lineStarts = TextCoordinateConverter.GetLineStarts(dataSet.Bicep); string getLoggingString(DeclaredSymbol symbol) { (_, var startChar) = TextCoordinateConverter.GetPosition(lineStarts, symbol.DeclaringSyntax.Span.Position); return($"{symbol.Kind} {symbol.Name}. Type: {symbol.Type}. Declaration start char: {startChar}, length: {symbol.DeclaringSyntax.Span.Length}"); } var sourceTextWithDiags = OutputHelper.AddDiagsToSourceText(dataSet, symbols, symb => symb.NameSyntax.Span, getLoggingString); var resultsFile = FileHelper.SaveResultFile(this.TestContext !, Path.Combine(dataSet.Name, DataSet.TestFileMainSymbols), sourceTextWithDiags); sourceTextWithDiags.Should().EqualWithLineByLineDiffOutput( dataSet.Symbols, expectedLocation: OutputHelper.GetBaselineUpdatePath(dataSet, DataSet.TestFileMainSymbols), actualLocation: resultsFile); }
public HornClause(Sentence sentence, Stack <Symbol> agenda, Dictionary <HornClause, int> count, Dictionary <Symbol, bool?> inferred) { if (sentence is Symbol) { this.Head = (Symbol)sentence; agenda.Push(this.Head); premiseSymbols = new List <Symbol>(); count[this] = 0; inferred[this.Head] = false; } else if (!this.IsImpliedSentence(sentence)) { throw new ApplicationException("Sentence " + sentence + " is not a horn clause"); } else { BinarySentence bs = (BinarySentence)sentence; this.Head = (Symbol)bs.Second; inferred[this.Head] = false; ISet <Symbol> symbolsInPremise = new SymbolCollector().GetSymbolsIn(bs.First); foreach (var symbol in symbolsInPremise) { inferred[symbol] = false; } premiseSymbols = symbolsInPremise.ToList(); count[this] = premiseSymbols.Count; } }
IEnumerable <ISymbol> GetRelatedSymbols(ISymbol entity) { var typeGraph = new Lazy <TypeGraph>(() => new TypeGraph(new [] { compilation.MainAssembly })); var symbolCollector = new SymbolCollector(); return(symbolCollector.GetRelatedSymbols(typeGraph, entity)); }
public void ProgramsShouldProduceExpectedUserDeclaredSymbols(DataSet dataSet) { var compilation = dataSet.CopyFilesAndCreateCompilation(TestContext, out var outputDirectory); var model = compilation.GetEntrypointSemanticModel(); var symbols = SymbolCollector .CollectSymbols(model) .OfType <DeclaredSymbol>(); var lineStarts = compilation.SyntaxTreeGrouping.EntryPoint.LineStarts; string getLoggingString(DeclaredSymbol symbol) { (_, var startChar) = TextCoordinateConverter.GetPosition(lineStarts, symbol.DeclaringSyntax.Span.Position); return($"{symbol.Kind} {symbol.Name}. Type: {symbol.Type}. Declaration start char: {startChar}, length: {symbol.DeclaringSyntax.Span.Length}"); } var sourceTextWithDiags = DataSet.AddDiagsToSourceText(dataSet, symbols, symb => symb.NameSyntax.Span, getLoggingString); var resultsFile = Path.Combine(outputDirectory, DataSet.TestFileMainDiagnostics); File.WriteAllText(resultsFile, sourceTextWithDiags); sourceTextWithDiags.Should().EqualWithLineByLineDiffOutput( TestContext, dataSet.Symbols, expectedLocation: DataSet.GetBaselineUpdatePath(dataSet, DataSet.TestFileMainSymbols), actualLocation: resultsFile); }
public Model FindModelFor(String logicalSentence, int numberOfFlips, double probabilityOfRandomWalk) { this.myModel = new Model(); var s = (Sentence) new PEParser().Parse(logicalSentence); var transformer = new CNFTransformer(); var clauseGatherer = new CNFClauseGatherer(); var sc = new SymbolCollector(); var symbols = sc.GetSymbolsIn(s).ToList(); var r = new Random(); foreach (var sym in symbols) { this.myModel = this.myModel.Extend(sym, Util.RandomBoolean()); } IList <Sentence> clauses = clauseGatherer.GetClausesFrom(transformer.Transform(s)).ToList(); //IList<Sentence> ClauseSet = new Converter<Sentence>().ListToSet(clauses); lastClauses = clauses; lastClausesFlip = new List <Int64>(clauses.Count + 1); for (int i = 0; i < clauses.Count; i++) { lastClausesFlip.Add(0); } for (int i = 0; i < numberOfFlips; i++) { List <int> unsatList = new List <int>(); int numSat = this.GetNumberOfClausesSatisfiedIn(new Converter <Sentence>().ListToSet(clauses), myModel, unsatList); if (numSat == clauses.Count) { trials = i; return(myModel); } int probe = FindAnRandomUnsatisfiedClause(clauses, myModel, unsatList); //Sentence clause = clauses[random.Next(clauses.Count)]; Sentence clause = clauses[probe]; lastClausesFlip[probe]++; IList <Symbol> symbolsInClause = sc.GetSymbolsIn(clause).ToList(); if (random.NextDouble() >= probabilityOfRandomWalk) { Symbol randomSymbol = symbolsInClause[random.Next(symbolsInClause.Count)]; myModel = myModel.Flip(randomSymbol); } else { Symbol symbolToFlip = this.GetSymbolWhoseFlipMaximisesSatisfiedClauses( new Converter <Sentence>().ListToSet(clauses), symbolsInClause, myModel); myModel = myModel.Flip(symbolToFlip); } } trials = numberOfFlips; return(null); }
public class TT_Entails { // No podemos llamar a la clase igual que a uno de sus métodos... /** * La función TT-ENTAILS?(KB, α) devuelve cierto o falso. * * @param kb * KB, la base de conocimiento, una sentencia en lógica proposicional * @param alpha * α, la consulta, una sentencia en lógica proposicional * * @return cierto si α es consecuencia lógica de KB, falso en otro caso. */ public bool TTEntails(KnowledgeBase kb, Sentence alpha) { // symbols <- una lista de símbolos de proposición de KB y &alpha IList <PropositionSymbol> symbols = new List <PropositionSymbol>(SymbolCollector.GetSymbolsFrom(kb.AsSentence(), alpha)); // return TT-CHECK-ALL(KB, α symbols, {}) return(TTCheckAll(kb, alpha, symbols, new Model())); }
/** * Añade la sentencia específica a la BC. * * @param aSentence * hecho para ser añadido a la BC. */ public void Tell(Sentence aSentence) { if (!(sentences.Contains(aSentence))) { sentences.Add(aSentence); _asCNF = _asCNF.Extend(ConvertToConjunctionOfClauses.Convert(aSentence).GetClauses()); symbols.UnionWith(SymbolCollector.GetSymbolsFrom(aSentence)); // UnionWith de ISet en vez del método addAll de Set } }
/** * Adds the specified sentence to the knowledge base. * * @param aSentence * a fact to be added to the knowledge base. */ public void tell(Sentence aSentence) { if (!(sentences.Contains(aSentence))) { sentences.Add(aSentence); _asCNF = _asCNF.extend(ConvertToConjunctionOfClauses.convert(aSentence).getClauses()); symbols.AddAll(SymbolCollector.getSymbolsFrom(aSentence)); } }
public bool dpllSatisfiable(Sentence s, Model m) { List <Sentence> clauses = new CNFClauseGatherer() .getClausesFrom(new CNFTransformer().transform(s)); List <Symbol> symbols = new SymbolCollector() .getSymbolsIn(s); // System.Console.WriteLine(" numberOfSymbols = " + symbols.Count); return(dpll(clauses, symbols, m)); }
//TODO: Update this method with better name public bool TtEntails(KnowledgeBase kb, String alpha) { Sentence kbSentence = kb.AsSentence(); Sentence querySentence = (Sentence) new PEParser().Parse(alpha); SymbolCollector collector = new SymbolCollector(); ISet <Symbol> kbSymbols = collector.GetSymbolsIn(kbSentence); ISet <Symbol> querySymbols = collector.GetSymbolsIn(querySentence); IList <Symbol> symbolList = kbSymbols.Union(querySymbols).ToList(); return(ttCheckAll(kbSentence, querySentence, symbolList, new Model())); }
public bool ttEntails(KnowledgeBase kb, String alpha) { Sentence kbSentence = kb.asSentence(); Sentence querySentence = (Sentence) new PEParser().parse(alpha); SymbolCollector collector = new SymbolCollector(); List <Symbol> kbSymbols = collector.getSymbolsIn(kbSentence); List <Symbol> querySymbols = collector.getSymbolsIn(querySentence); List <Symbol> symbols = SetOps.union(kbSymbols, querySymbols); List <Symbol> symbolList = symbols; return(ttCheckAll(kbSentence, querySentence, symbolList, new Model())); }
public bool ttEntails(KnowledgeBase kb, string alpha) { Sentence kbSentence = kb.asSentence(); Sentence querySentence = (Sentence) new PEParser().parse(alpha); SymbolCollector collector = new SymbolCollector(); Hashtable kbSymbols = collector.getSymbolsIn(kbSentence); Hashtable querySymbols = collector.getSymbolsIn(querySentence); Hashtable symbols = new SetOps().union(kbSymbols, querySymbols); ArrayList symbolList = new Converter().setToList(symbols); return(ttCheckAll(kbSentence, querySentence, symbolList, new Model())); }
protected IMap <PropositionSymbol, bool?> initializeInferred(KnowledgeBase kb) { // inferred <- a table, where inferred[s] is initially false for all // symbols IMap <PropositionSymbol, bool?> inferred = CollectionFactory.CreateInsertionOrderedMap <PropositionSymbol, bool?>(); foreach (PropositionSymbol p in SymbolCollector.getSymbolsFrom(kb.asSentence())) { inferred.Put(p, false); } return(inferred); }
public void testCollectSymbolsFromComplexSentence() { Sentence sentence = (Sentence)parser.parse("(~B11 | P12 | P21) & (B11 | ~P12) & (B11 | ~P21)"); ISet <PropositionSymbol> s = SymbolCollector.getSymbolsFrom(sentence); Assert.AreEqual(3, s.Size()); Sentence b11 = parser.parse("B11"); Sentence p21 = parser.parse("P21"); Sentence p12 = parser.parse("P12"); Assert.IsTrue(s.Contains(b11 as PropositionSymbol)); Assert.IsTrue(s.Contains(p21 as PropositionSymbol)); Assert.IsTrue(s.Contains(p12 as PropositionSymbol)); }
public void testDPLLReturnsFalseWhenOneClauseFalseInModel() { Model model = new Model(); model = model.union(new PropositionSymbol("A"), true).union( new PropositionSymbol("B"), false); Sentence sentence = parser.parse("(A | B) & (A => B)"); ISet <Clause> clauses = ConvertToConjunctionOfClauses.convert(sentence) .getClauses(); ICollection <PropositionSymbol> symbols = CollectionFactory.CreateQueue <PropositionSymbol>( SymbolCollector.getSymbolsFrom(sentence)); bool satisfiable = dpll.dpll(clauses, symbols, model); Assert.AreEqual(false, satisfiable); }
public Model findModelFor(String logicalSentence, int numberOfFlips, double probabilityOfRandomWalk) { myModel = new Model(); Sentence s = (Sentence) new PEParser().parse(logicalSentence); CNFTransformer transformer = new CNFTransformer(); CNFClauseGatherer clauseGatherer = new CNFClauseGatherer(); SymbolCollector sc = new SymbolCollector(); List <Symbol> symbols = sc.getSymbolsIn(s); Random r = new Random(); for (int i = 0; i < symbols.Count; i++) { Symbol sym = (Symbol)symbols[i]; myModel = myModel.extend(sym, Util.randombool()); } List <Sentence> clauses = clauseGatherer.getClausesFrom(transformer .transform(s)); for (int i = 0; i < numberOfFlips; i++) { if (getNumberOfClausesSatisfiedIn(clauses, myModel) == clauses.Count) { return(myModel); } Sentence clause = clauses[random.Next(clauses.Count)]; List <Symbol> symbolsInClause = sc .getSymbolsIn(clause); if (random.NextDouble() >= probabilityOfRandomWalk) { Symbol randomSymbol = symbolsInClause[random .Next(symbolsInClause.Count)]; myModel = myModel.flip(randomSymbol); } else { Symbol symbolToFlip = getSymbolWhoseFlipMaximisesSatisfiedClauses( clauses, symbolsInClause, myModel); myModel = myModel.flip(symbolToFlip); } } return(null); }
public void testIssue66() { // http://code.google.com/p/aima-java/issues/detail?id=66 Model model = new Model(); model = model.union(new PropositionSymbol("A"), false) .union(new PropositionSymbol("B"), false) .union(new PropositionSymbol("C"), true); Sentence sentence = parser.parse("((A | B) | C)"); ISet <Clause> clauses = ConvertToConjunctionOfClauses.convert(sentence) .getClauses(); ICollection <PropositionSymbol> symbols = CollectionFactory.CreateQueue <PropositionSymbol>( SymbolCollector.getSymbolsFrom(sentence)); bool satisfiable = dpll.dpll(clauses, symbols, model); Assert.AreEqual(true, satisfiable); }
public void testDPLLFindsPurePositiveSymbolsWhenTheyExist() { Model model = new Model(); model = model.extend(new Symbol("A"), true).extend(new Symbol("B"), true); Sentence sentence = (Sentence)parser .parse("((A AND B) AND (B AND C))"); List <Sentence> clauseList = new CNFClauseGatherer() .getClausesFrom(new CNFTransformer() .transform(sentence)); List <Symbol> symbolList = new SymbolCollector().getSymbolsIn(sentence); DPLL.SymbolValuePair sv = dpll.findPureSymbolValuePair(clauseList, model, symbolList); Assert.IsNotNull(sv); Assert.AreEqual(new Symbol("C"), sv.symbol); Assert.AreEqual(true, sv.value); }
public HornClause(Sentence sentence, PLFCEntails plfcEntails) { this.plfcEntails = plfcEntails; if (sentence is Symbol) { _head = (Symbol)sentence; plfcEntails.agenda.Push(_head); premiseSymbols = new List <Symbol>(); plfcEntails.count.Add(this, 0); plfcEntails._inferred.Add(_head, false); } else if (!isImpliedSentence(sentence)) { throw new ApplicationException("Sentence " + sentence + " is not a horn clause"); } else { BinarySentence bs = (BinarySentence)sentence; _head = (Symbol)bs.getSecond(); if (plfcEntails._inferred.ContainsKey(_head)) { plfcEntails._inferred[_head] = false; } else { plfcEntails._inferred.Add(_head, false); } List <Symbol> symbolsInPremise = new SymbolCollector() .getSymbolsIn(bs.getFirst()); foreach (Symbol s in symbolsInPremise) { plfcEntails._inferred.Add(s, false); } premiseSymbols = symbolsInPremise; plfcEntails.count.Add(this, premiseSymbols.Count); } }
IList <AstNode> Rename(string fullyQualifiedName, string newName, bool includeOverloads) { var sym = GetSymbol(compilation, fullyQualifiedName); Assert.NotNull(sym); var graph = new TypeGraph(compilation.Assemblies); var col = new SymbolCollector(); col.IncludeOverloads = includeOverloads; col.GroupForRenaming = true; var scopes = findReferences.GetSearchScopes(col.GetRelatedSymbols(graph, sym)); List <AstNode> result = new List <AstNode>(); findReferences.RenameReferencesInFile( scopes, newName, new CSharpAstResolver(compilation, syntaxTree, unresolvedFile), delegate(RenameCallbackArguments obj) { result.Add(obj.NodeToReplace); }, delegate(Error obj) { }); return(result); }
public HornClause(Sentence sentence, Stack _agenda, Hashtable _count, Hashtable _inferred) { if (sentence is Symbol) { _head = (Symbol)sentence; _agenda.Push(_head); premiseSymbols = new ArrayList(); if (_count.Contains(this)) { _count[this] = 0; } else { _count.Add(this, 0); } if (_inferred.Contains(_head)) { _inferred[_head] = false; } else { _inferred.Add(_head, false); } } else if (!isImpliedSentence(sentence)) { throw new Exception("Sentence " + sentence + " is not a horn clause"); } else { BinarySentence bs = (BinarySentence)sentence; _head = (Symbol)bs.getSecond(); if (_inferred.Contains(_head)) { _inferred[_head] = false; } else { _inferred.Add(_head, false); } Hashtable symbolsInPremise = new SymbolCollector().getSymbolsIn(bs .getFirst()); // Iterator iter = symbolsInPremise.iterator(); // while (iter.hasNext()) foreach (object iter in symbolsInPremise.Keys) { if (_inferred.Contains(iter)) { _inferred[iter] = false; } else { _inferred.Add(iter, false); } } premiseSymbols = new Converter().setToList(symbolsInPremise); if (_count.Contains(this)) { _count[this] = premiseSymbols.Count; } else { _count.Add(this, premiseSymbols.Count); } } }
/** * function TT-ENTAILS?(KB, α) returns true or false. * * @param kb * KB, the knowledge base, a sentence in propositional logic * @param alpha * α, the query, a sentence in propositional logic * * @return true if KB entails α, false otherwise. */ public bool ttEntails(KnowledgeBase kb, Sentence alpha) { // symbols <- a list of proposition symbols in KB and &alpha ICollection <PropositionSymbol> symbols = CollectionFactory.CreateQueue <PropositionSymbol>(SymbolCollector.getSymbolsFrom(kb.asSentence(), alpha)); // return TT-CHECK-ALL(KB, α symbols, {}) return(ttCheckAll(kb, alpha, symbols, new Model())); }
private HomeItemViewModel Parse(string source, long timer, bool generateAssembly = false) { string error = null; var vm = new HomeItemViewModel { Source = source, Timer = timer }; var input = InputModule.create(vm.Source); var tokensResult = Lexer.tokenize(input); if (tokensResult.IsError) { error = tokensResult.ErrorValue; goto End; } var tokens = tokensResult.ResultValue; var programResult = Parser.parse(tokens); if (programResult.IsError) { error = programResult.ErrorValue; goto End; } var program = programResult.ResultValue; vm.Ast = JsonConvert.SerializeObject(_astBuilder.Build(program)); var symbolTableResult = SymbolCollector.create(program); if (symbolTableResult.IsError) { error = symbolTableResult.ErrorValue; goto End; } var symbolTable = symbolTableResult.ResultValue; var typeCheckerResult = TypeChecker.check(symbolTable, program); if (typeCheckerResult.IsError) { error = typeCheckerResult.ErrorValue; goto End; } var variableInitializationCheckerResult = VariableInitializationChecker.check(program); if (variableInitializationCheckerResult.IsError) { error = variableInitializationCheckerResult.ErrorValue; goto End; } var writeLineFunc = FuncConvert.ToFSharpFunc <int>(i => vm.PrintfnLog += i + "\n"); var environment = EnvironmentModule.create(symbolTable, program, writeLineFunc, vm.Timer); var interpreterResult = Interpreter.interpret(environment); if (interpreterResult.IsError) { error = interpreterResult.ErrorValue; goto End; } var assemblyResult = ILBuilder.build(symbolTable, program); if (assemblyResult.IsError) { error = assemblyResult.ErrorValue; goto End; } var assembly = assemblyResult.ResultValue; vm.Il = JsonConvert.SerializeObject(_ilBuilder.Build(assembly)); if (generateAssembly) { var applicationResult = CodeGenerator.generate(assembly); if (applicationResult.IsError) { error = applicationResult.ErrorValue; goto End; } vm.Application = applicationResult.ResultValue; } End: if (error != null) { vm.Error = error; } return(vm); }
// // SUPPORTING CODE // /** * Determine if KB |= α, i.e. alpha is entailed by KB. * * @param kb * a Knowledge Base in propositional logic. * @param alpha * a propositional sentence. * @return true, if α is entailed by KB, false otherwise. */ public bool isEntailed(KnowledgeBase kb, Sentence alpha) { // AIMA3e p.g. 260: kb |= alpha, can be done by testing // unsatisfiability of kb & ~alpha. ISet <Clause> kbAndNotAlpha = CollectionFactory.CreateSet <Clause>(); Sentence notQuery = new ComplexSentence(Connective.NOT, alpha); ISet <PropositionSymbol> symbols = CollectionFactory.CreateSet <PropositionSymbol>(); ICollection <PropositionSymbol> querySymbols = CollectionFactory.CreateQueue <PropositionSymbol>(SymbolCollector.getSymbolsFrom(notQuery)); kbAndNotAlpha.AddAll(kb.asCNF()); kbAndNotAlpha.AddAll(ConvertToConjunctionOfClauses.convert(notQuery).getClauses()); symbols.AddAll(querySymbols); symbols.AddAll(kb.getSymbols()); return(!dpll(kbAndNotAlpha, CollectionFactory.CreateQueue <PropositionSymbol>(symbols), new Model())); }
public void setUp() { parser = new PEParser(); collector = new SymbolCollector(); }