Exemplo n.º 1
0
        /// <summary>
        /// Add KnowledgeBase data into the KnowledgeBase database
        /// </summary>
        /// <param name="KnowledgeList"></param>
        public void AddKnowledgeBase(List <KnowledgeBaseModel> KnowledgeList)
        {
            lock (collisionLock)
            {
                int status = database.Table <KnowledgeBase>().Delete(e => e.email == Settings.Email);
                //database.Query<KnowledgeBase>("Delete from KnowledgeBase");
                //database.Query<KnowledgeBase>("DELETE FROM SQLITE_SEQUENCE WHERE name = 'KnowledgeBase'");

                foreach (var k in KnowledgeList)
                {
                    KnowledgeBase knowledgeBase = new KnowledgeBase();

                    knowledgeBase.id            = k.id;
                    knowledgeBase.title         = k.title;
                    knowledgeBase.text          = k.text;
                    knowledgeBase.email         = Settings.Email;
                    knowledgeBase.share_message = k.share_message;
                    knowledgeBase.category      = k.category;

                    database.Insert(knowledgeBase);
                }

                foreach (var f in KnowledgeList)
                {
                    if (!(database.Table <FavouriteKnowledgeBase>().Any(x => x.id == f.id && x.email == Settings.Email)))
                    {
                        FavouriteKnowledgeBase favourite = new FavouriteKnowledgeBase();
                        favourite.id           = f.id;
                        favourite.is_favourite = "false";
                        favourite.email        = Settings.Email;
                        database.Insert(favourite);
                    }
                }
            }
        }
Exemplo n.º 2
0
        public void runRules(String[] rules, java.lang.Object[] facts)
        {
            KnowledgeBase    kbase    = KnowledgeBaseFactory.newKnowledgeBase();
            KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

            for (int i = 0; i < rules.Length; i++)
            {
                String ruleFile = rules[i];
                Console.WriteLine("Loading file: " + ruleFile);
                ruleFile = Path.GetFullPath(Path.Combine("rules", ruleFile));
                kbuilder.add(ResourceFactory.newFileResource(ruleFile), ResourceType.DRL);
            }

            java.util.Collection pkgs = kbuilder.getKnowledgePackages();
            kbase.addKnowledgePackages(pkgs);
            StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

            for (int i = 0; i < facts.Length; i++)
            {
                java.lang.Object fact = facts[i];
                //Console.WriteLine("Inserting fact: " + fact);
                ksession.insert(fact);
            }



            ksession.fireAllRules();
        }
Exemplo n.º 3
0
 public async Task GetInfo(IDialogContext context, LuisResult result)
 {
     if (!isReply(context, result))
     {
         EntityRecommendation InfoType;
         if (result.TryFindEntity("InfoType", out InfoType))
         {
             KnowledgeBase kb = new KnowledgeBase();
             if (InfoType.Entity.Contains("ox"))
             {
                 await context.PostAsync(kb.GetArticle("KB0010016"));
             }
             else if (InfoType.Entity.Contains("rive"))
             {
                 await context.PostAsync(kb.GetArticle("KB0010017"));
             }
             else if (InfoType.Entity.Contains("pproval"))
             {
                 Approvals approvals = new Approvals();
                 await approvals.GetPending(context);
             }
             else
             {
                 await context.PostAsync("Sorry. I couldn't find any article related to your question.");
             }
         }
         else
         {
             await context.PostAsync("Sorry. I couldn't find any article related to your question.");
         }
     }
     context.Wait(MessageReceived);
 }
Exemplo n.º 4
0
        public bool Ask(KnowledgeBase kb, string predicate)
        {
            switch (Procedure)
            {
            case PLInferenceProcedure.TTEntails:
                return(kb.askWithTTEntails(predicate));

            case PLInferenceProcedure.PLFCEntails:
                return(new PLFCEntails().plfcEntails(kb, new PropositionSymbol(predicate)));

            case PLInferenceProcedure.Resolve:
                return(new PLResolution().plResolution(kb, (Sentence)parser.parse(predicate)));

            case PLInferenceProcedure.DPLLEntails:
                return(new DPLLSatisfiable().isEntailed(kb, (Sentence)parser.parse(predicate)));

            case PLInferenceProcedure.DPLLSatisfiable:
                return(new DPLLSatisfiable().dpllSatisfiable((Sentence)parser.parse(predicate)));

            case PLInferenceProcedure.WalkSatPredicate:
                return(new WalkSAT().walkSAT(ConvertToConjunctionOfClauses.convert((Sentence)parser.parse(predicate)).getClauses(), WalkSatProbability, WalkSatMaxFlips) != null);

            case PLInferenceProcedure.WalkSatKb:
                return(new WalkSAT().walkSAT(kb.asCNF(), WalkSatProbability, WalkSatMaxFlips) != null);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 5
0
        public InferenceResult Ask(object owner, IContextLookup globalVars)
        {
            var kb        = KnowledgeBase.EvaluateTyped(owner, globalVars);
            var predicate = Predicate.GetValue(owner, globalVars);

            return(kb.ask(predicate));
        }
Exemplo n.º 6
0
        public async Task ResolveAMoreComplicatedGoal()
        {
            var knowledge = KnowledgeBase.New();

            var houseCat = Literal.NewFunctor(1);
            var feline   = Literal.NewFunctor(1);
            var small    = Literal.NewFunctor(1);
            var meows    = Literal.NewFunctor(1);
            var tom      = Literal.NewAtom();
            var X        = Literal.NewVariable();
            var Y        = Literal.NewVariable();

            // houseCat(X) :- small(X), feline(X)
            var houseCatsAreSmallFelines = Clause.If(feline.With(X), small.With(X)).Then(houseCat.With(X));
            var felinesMeow = Clause.If(meows.With(Y)).Then(feline.With(Y));
            var tomIsSmall  = Clause.Always(small.With(tom));
            var tomMeows    = Clause.Always(meows.With(tom));

            knowledge = knowledge
                        .Assert(houseCatsAreSmallFelines)
                        .Assert(tomIsSmall)
                        .Assert(felinesMeow)
                        .Assert(tomMeows);

            var solver = await Solver.NewSolver(knowledge);

            var result = solver.Query(houseCat.With(tom));

            Assert.IsTrue(result.Success);

            var allCats = solver.Query(houseCat.With(X));

            Assert.IsTrue(result.Success);
            Assert.AreEqual(tom, allCats.Bindings.GetValueForVariable(X));
        }
    /// <summary>
    /// Gathers the agents and assigns their agentinfo
    /// </summary>
    private void InitializeAgents()
    {
        GameObject[] agentObjs = GameObject.FindGameObjectsWithTag("Agent");

        for (int i = 0; i < agentObjs.Length; i++)
        {
            Debug.Log("found agent");
            GameObject    agentObj = agentObjs[i];
            Agent         agent    = agentObj.GetComponent <Agent>();
            KnowledgeBase kb       = agentObj.GetComponent <KnowledgeBase>();
            kb.InitKnowledgeBase();
            if (agent == null)
            {
                Debug.LogError("ERROR: No agent info component on gameobject tagged as agent NAME: " + agentObj.name);
                continue;
            }
            Debug.Log("valid agent");
            agents.Add(agent);
        }
        for (int i = 1; i < agents.Count; i++) //i starting at one since the player should be the first agent added
        {
            Agent info = agents[i];
            info.InitAgentInfo(i);
        }
    }
Exemplo n.º 8
0
        /// <inheritdoc/>
        public Task UpdateKnowledgeBaseAsync(KnowledgeBase knowledgeBase)
        {
            var cachedKnowledgeBase = this.dbContext.KnowledgeBases.Find(knowledgeBase.Id);

            // Throw if entity doesn't exist
            if (cachedKnowledgeBase == null)
            {
                throw new QBotException(HttpStatusCode.NotFound, ErrorCode.KnowledgeBaseNotFound, $"UpdateKnowledgeBaseAsync - KnowledgeBase {knowledgeBase.Id} not found!");
            }

            // Update if it exists.
            var knowledgeBaseEntity = this.mapper.Map <KnowledgeBaseEntity>(knowledgeBase);

            cachedKnowledgeBase.Name        = knowledgeBaseEntity.Name;
            cachedKnowledgeBase.OwnerUserId = knowledgeBaseEntity.OwnerUserId;

            try
            {
                this.dbContext.KnowledgeBases.Update(cachedKnowledgeBase);
                return(this.dbContext.SaveChangesAsync());
            }
            catch (DbUpdateException exception)
            {
                var message = $"Failed to update knowledge base: {knowledgeBase.Id}.";
                this.logger.LogError(exception, message);
                throw new QBotException(HttpStatusCode.InternalServerError, ErrorCode.Unknown, message, exception);
            }
        }
Exemplo n.º 9
0
        public bool verify(KnowledgeBase knowledge)
        {
            NTripleListVerifier verifier = new NTripleListVerifier();

            foreach (string nTriple in itsTriples)
            {
                verifier.Expect(nTriple);
            }

            StringWriter  received = new StringWriter();
            NTripleWriter writer   = new NTripleWriter(received);

            knowledge.Write(writer);

            StringReader receivedReader = new StringReader(received.ToString());
            string       receivedLine   = receivedReader.ReadLine();

            while (receivedLine != null)
            {
                string trimmed = receivedLine.Trim();
                if (trimmed.Length > 0 && !trimmed.StartsWith("#"))
                {
                    verifier.Receive(trimmed);
                }
                receivedLine = receivedReader.ReadLine();
            }

            bool verifyResult = verifier.Verify();

            lastFailureDescription = verifier.GetLastFailureDescription();
            return(verifyResult);
        }
Exemplo n.º 10
0
        public async Task ManyHouseCats()
        {
            var tom        = Literal.NewAtom();
            var heathcliff = Literal.NewAtom();
            var sylvester  = Literal.NewAtom();
            var houseCat   = Literal.NewFunctor(1);
            var any        = Literal.NewVariable();

            var knowledge = KnowledgeBase.New()
                            .Assert(Clause.Always(houseCat.With(tom)))
                            .Assert(Clause.Always(houseCat.With(heathcliff)))
                            .Assert(Clause.Always(houseCat.With(sylvester)));

            // Get all the cats
            var solver = new SimpleDispatchingSolver();
            await solver.LoadFromKnowledgeBase(knowledge);

            var allResults = new List <ILiteral>();

            for (var result = solver.Query(houseCat.With(any)); result != null && result.Success; result = await result.Next())
            {
                allResults.Add(result.Bindings.GetValueForVariable(any));
            }

            Assert.IsTrue(allResults.Contains(tom));
            Assert.IsTrue(allResults.Contains(heathcliff));
            Assert.IsTrue(allResults.Contains(sylvester));
            Assert.AreEqual(3, allResults.Count);
        }
        public async stt::Task UpdateKnowledgeBaseAsync()
        {
            moq::Mock <KnowledgeBases.KnowledgeBasesClient> mockGrpcClient = new moq::Mock <KnowledgeBases.KnowledgeBasesClient>(moq::MockBehavior.Strict);
            UpdateKnowledgeBaseRequest request = new UpdateKnowledgeBaseRequest
            {
                KnowledgeBase = new KnowledgeBase(),
                UpdateMask    = new wkt::FieldMask(),
            };
            KnowledgeBase expectedResponse = new KnowledgeBase
            {
                KnowledgeBaseName = KnowledgeBaseName.FromProjectKnowledgeBase("[PROJECT]", "[KNOWLEDGE_BASE]"),
                DisplayName       = "display_name137f65c2",
                LanguageCode      = "language_code2f6c7160",
            };

            mockGrpcClient.Setup(x => x.UpdateKnowledgeBaseAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <KnowledgeBase>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            KnowledgeBasesClient client = new KnowledgeBasesClientImpl(mockGrpcClient.Object, null);
            KnowledgeBase        responseCallSettings = await client.UpdateKnowledgeBaseAsync(request.KnowledgeBase, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));

            xunit::Assert.Same(expectedResponse, responseCallSettings);
            KnowledgeBase responseCancellationToken = await client.UpdateKnowledgeBaseAsync(request.KnowledgeBase, request.UpdateMask, st::CancellationToken.None);

            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            //Итак, очень простой пример: В базе создадим узел Горькосладкое яблоко и с известной ценой и количеством
            //Затем напишем простого агента, который будет создавать стоимость для любого узла, у которого есть цена и количество (собственно не только для яблок).
            //Можно сделать более универсального агента, который будет знать по каким правилам формировать стоимость, но это позже, после усвоения языка scs и основных концепций
            //я НЕ буду использовать врапера Tools, чтобы его необходимость осозналась
            // также я не буду использовать проверку на ошибки
            //Вообще вся логика работы с базой знаний строится на работе с конечным количеством отношений и классов.
            //Можно заметить, что я создал в папке scs класс яблоко и отношения цена, количество и стоимость,
            //а так же горько-сладкое яблоко, как экземпляр класса яблоко и задал его цену и количество
            //Необходимо с помощью утилиты sc-builder.exe транслировать их в базу
            //все остальные объяснения в классе  CostTest

            CostTest costTest = new CostTest("127.0.0.1", SctpProtocol.DefaultPortNumber);
            KnowledgeBase kb = new KnowledgeBase("127.0.0.1", SctpProtocol.DefaultPortNumber);
               // Console.WriteLine(kb.Nodes["nrel_cost"].ScAddress.Segment);

            // Ищем все яблоки, собстенно оно у нас одно
            var applesAddresses = costTest.FindApples();
            //для всех яблок создаем стоимость
            foreach (var appleAdr in applesAddresses)
            {
                double cost=costTest.FindValueByPredicate(appleAdr, costTest.Nrel_cost);
                if (double.IsNaN(cost))
                {
                    costTest.CreateCost(appleAdr);
                }
                //ну и тут же проверяем, создалось ли
                Console.WriteLine("Цена: {0}", costTest.FindValueByPredicate(appleAdr, costTest.Nrel_price));
                Console.WriteLine("Количество: {0}", costTest.FindValueByPredicate(appleAdr, costTest.Nrel_quantity));
                Console.WriteLine("Стоимость: {0}", costTest.FindValueByPredicate(appleAdr, costTest.Nrel_cost));
            }

              Console.ReadKey();
        }
        /// <summary>
        /// MAPPING FIELDS DATA OF KNOWLEDGE BASE
        /// </summary>
        /// <param name="request">KnowledgeBaseCreateRequest</param>
        /// <param name="knowledgeBase">KnowledgeBase</param>
        private static void UpdateKnowledgeBase(KnowledgeBaseCreateRequest request, KnowledgeBase knowledgeBase)
        {
            knowledgeBase.CategoryId = request.CategoryId;

            knowledgeBase.Title = request.Title;

            if (string.IsNullOrEmpty(request.SeoAlias))
            {
                knowledgeBase.SeoAlias = TextHelper.ToUnsignString(request.Title);
            }
            else
            {
                knowledgeBase.SeoAlias = request.SeoAlias;
            }

            knowledgeBase.Description = request.Description;

            knowledgeBase.Environment = request.Environment;

            knowledgeBase.Problem = request.Problem;

            knowledgeBase.StepToReproduce = request.StepToReproduce;

            knowledgeBase.ErrorMessage = request.ErrorMessage;

            knowledgeBase.Workaround = request.Workaround;

            knowledgeBase.Note = request.Note;

            if (request.Labels != null)
            {
                knowledgeBase.Labels = string.Join(',', request.Labels);
            }
        }
Exemplo n.º 14
0
        private List <InitialData> GetInitialNodes(KnowledgeBase knowledgeBase, List <InitialData> initialData)
        {
            var ifUnaryStatements = knowledgeBase.ImplicationRules
                                    .SelectMany(ir => ir.Value.IfStatement.SelectMany(ifs => ifs.UnaryStatements))
                                    .ToList();

            var activatedNodes = new List <InitialData>();

            foreach (var data in initialData)
            {
                var matchingVariable      = knowledgeBase.LinguisticVariables.SingleOrDefault(lv => lv.Value.VariableName == data.Name);
                var relatedStatementNames = knowledgeBase.LinguisticVariablesRelations
                                            .SingleOrDefault(lvr => lvr.LinguisticVariableNumber == matchingVariable.Key)
                                            ?.RelatedUnaryStatementNames;

                var membershipFunction = _fuzzyEngine.Fuzzify(matchingVariable.Value, data.Value);

                foreach (var relatedStatementName in relatedStatementNames)
                {
                    var matchingStatement = ifUnaryStatements.FirstOrDefault(ius =>
                                                                             ius.ToString() == relatedStatementName &&
                                                                             ius.RightOperand == membershipFunction.LinguisticVariableName);
                    if (matchingStatement != null)
                    {
                        activatedNodes.Add(new InitialData(relatedStatementName, data.Value, data.ConfidenceFactor));
                    }
                }
            }
            return(activatedNodes);
        }
Exemplo n.º 15
0
    // Use this for initialization
    void Start()
    {
        lastZone           = 0;
        talkingCooldown    = 0;
        agent              = gameObject.GetComponent <NavMeshAgent>();
        knowledgeBase      = gameObject.GetComponent <KnowledgeBase>();
        agent.speed        = speed;
        info               = gameObject.GetComponent <Agent>();
        behaviorController = gameObject.GetComponent <NPCController>();

        NPCNode behaviorTree = new NPCDecoratorLoop(new NPCSequence(
                                                        new NPCNode[] {
            new NPCAction(() => WanderAround()),
            new NPCSelector(new NPCNode[]
            {
                new NPCAction(() => IdleBehavior()),
                new NPCDecoratorLoop(new NPCSequence(
                                         new NPCNode[]
                {
                    new NPCAction(() => FollowAgent()),
                    new NPCAction(() => ExchangeInfo())
                }
                                         )),
                new NPCWait(1000, BEHAVIOR_STATUS.FAILURE),
                new NPCAction(() => FinishTalking())
            })
        })
                                                    );

        behaviorController.AI.AddBehavior(behaviorTree);
        behaviorController.AI.StartBehavior();
    }
Exemplo n.º 16
0
        void Awake()
        {
            decisionManager = new DecisionManager(this);
            knowledgeBase   = new KnowledgeBase();

            if (null == GetComponent <Rigidbody> ())
            {
                gameObject.AddComponent <Rigidbody>();
                gameObject.GetComponent <Rigidbody> ().freezeRotation = true;
            }
            if (null == GetComponent <NavMeshAgent> ())
            {
                gameObject.AddComponent <NavMeshAgent>();
            }

            if (null == GetComponent <PositionTracker> ())
            {
                gameObject.AddComponent <PositionTracker>();
            }
            if (null == target)
            {
                target = Instantiate(targetPrefab);
            }

            AddGoal(new Goal(new List <IRequirement> ()
            {
                new ExploreArea(50)
            }));
        }
Exemplo n.º 17
0
 /// <summary>
 /// Construct the object.
 /// </summary>
 public SimpleDecisionProblem(KnowledgeBase kb, CostManager cm, SensorModule sm, int MaxIterations)
     : base(MaxIterations)
 {
     this.kb           = kb;
     this.costManager  = cm;
     this.sensorModule = sm;
 }
Exemplo n.º 18
0
        private async Task ProcessLabel(KnowledgeBaseCreateRequest request, KnowledgeBase knowledgeBase)
        {
            foreach (var labelText in request.Labels)
            {
                var labelId       = TextHelper.ToUnsignString(labelText.ToString());
                var existingLabel = await _context.Labels.FindAsync(labelId);

                if (existingLabel == null)
                {
                    var labelEntity = new Label()
                    {
                        Id   = labelId,
                        Name = labelText.ToString()
                    };
                    _context.Labels.Add(labelEntity);
                }
                if (await _context.LabelInKnowledgeBases.FindAsync(labelId, knowledgeBase.Id) == null)
                {
                    _context.LabelInKnowledgeBases.Add(new LabelInKnowledgeBase()
                    {
                        KnowledgeBaseId = knowledgeBase.Id,
                        LabelId         = labelId
                    });
                }
            }
        }
Exemplo n.º 19
0
 //
 public static void CleanAllKBObjectVariables(KnowledgeBase KB, IOutputService output)
 {
     foreach (KBObject kbo in KB.DesignModel.Objects.GetAll())
     {
         CleanKB.CleanKBObjectVariables(kbo, output);
     }
 }
Exemplo n.º 20
0
        public static void Main(params string[] args)
        {
            System.Console.WriteLine("\nWalkSatDemo\n");
            KnowledgeBase kb = new KnowledgeBase();

            kb.tell("P => Q");
            kb.tell("L & M => P");
            kb.tell("B & L => M");
            kb.tell("A & P => L");
            kb.tell("A & B => L");
            kb.tell("A");
            kb.tell("B");

            System.Console.WriteLine("Example from  page 220 of AIMA 2nd Edition");
            System.Console.WriteLine("KnowledgeBsse consists of sentences");
            System.Console.WriteLine(kb.ToString());

            WalkSAT walkSAT = new WalkSAT();
            Model   m       = walkSAT.walkSAT(ConvertToConjunctionOfClauses.convert(kb.asSentence()).getClauses(), 0.5, 1000);

            if (m == null)
            {
                System.Console.WriteLine("failure");
            }
            else
            {
                m.print();
            }
        }
Exemplo n.º 21
0
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            KnowledgeBase knowledgeBase = db.KnowledgeBases.Find(id);

            if (knowledgeBase == null)
            {
                return(HttpNotFound());
            }
            KnowledgeBaseViewModel model = new KnowledgeBaseViewModel
            {
                Id                   = knowledgeBase.KnowledgeBaseId,
                Topic                = knowledgeBase.Topic,
                IncidentTitle        = knowledgeBase.IncidentTitle,
                IncidentDescription  = knowledgeBase.IncidentDescription,
                SolutionDescription  = knowledgeBase.SolutionDescription,
                EditedBy             = knowledgeBase.EditedBy,
                EditionDate          = knowledgeBase.EditionDate,
                KBAttachmentFilePath = knowledgeBase.KBAttachmentFilePath,
            };

            return(View(model));
        }
Exemplo n.º 22
0
            internal Clause Combine(Clause otherClause)
            {
                Clause combinedClause = new Clause()
                {
                    PositiveLiterals = new List <string>(otherClause.PositiveLiterals),
                    NegativeLiterals = new List <string>(otherClause.NegativeLiterals)
                };

                foreach (string s in PositiveLiterals)
                {
                    if (otherClause.NegativeLiterals.Contains(s))
                    {
                        combinedClause.NegativeLiterals.Remove(s);
                    }
                    else if (!combinedClause.PositiveLiterals.Contains(s))
                    {
                        combinedClause.PositiveLiterals.Add(s);
                    }
                }
                foreach (string s in NegativeLiterals)
                {
                    if (otherClause.PositiveLiterals.Contains(s))
                    {
                        combinedClause.PositiveLiterals.Remove(s);
                    }
                    else if (!combinedClause.NegativeLiterals.Contains(s))
                    {
                        combinedClause.NegativeLiterals.Add(s);
                    }
                }
                combinedClause.CombinedHow = combinedClause + "    [using rule " + this + "]";
                KnowledgeBase.Add(combinedClause);
                return(combinedClause);
            }
Exemplo n.º 23
0
        /// <summary>
        /// The main output of this engine
        /// </summary>
        /// <param name="kb"></param>
        /// <param name="ask"></param>
        /// <returns></returns>
        public virtual string GetResult(KnowledgeBase kb, string ask)
        {
            // could be extended to handle really big dataset with millions of symbols
            // example: List<List<Block>> contains 2 billion ^ 2 slots
            // here, it can only handle at most log2(2 billion)
            var clauses = new List <Block>();

            foreach (var normalClause in kb.Knowledges)
            {
                clauses.AddRange(new CNFClause(normalClause).Conjunctions);
            }

            ask = ask.ToLower();
            if (ask == "satisfiable" || ask == "unsatisfiable")
            {
                bool result = Main(clauses);
                return((ask == "satisfiable" && result) ||
                       (ask == "unsatisfiable" && !result) ? $"YES: {Path}" : "NO");
            }
            else if (ask == "rawoutput")
            {
                return(Main(clauses) ? $"SATISFIABLE: {Path}" : "UNSATISFIABLE");
            }

            throw new System.NotSupportedException(
                      "Wrong type of ask argument!\n" +
                      "Available ask argument: satisfiable, unsatisfiable or rawOutput");
        }
Exemplo n.º 24
0
        public static void Main(params string[] args)
        {
            System.Console.WriteLine("\nPlFcEntailsDemo\n");
            KnowledgeBase kb = new KnowledgeBase();

            kb.tell("P => Q");
            kb.tell("L & M => P");
            kb.tell("B & L => M");
            kb.tell("A & P => L");
            kb.tell("A & B => L");
            kb.tell("A");
            kb.tell("B");

            System.Console.WriteLine("Example from  page 220 of AIMA 2nd Edition");
            System.Console.WriteLine("KnowledgeBsse consists of sentences");
            System.Console.WriteLine("P => Q");
            System.Console.WriteLine("L & M => P");
            System.Console.WriteLine("B & L => M");
            System.Console.WriteLine("A & P => L");
            System.Console.WriteLine("A & B => L");
            System.Console.WriteLine("A");
            System.Console.WriteLine("B");

            displayPLFCEntailment(kb, "Q");
        }
Exemplo n.º 25
0
        void CmbKBsSelectedIndexChanged(object sender, EventArgs e)
        {
            string kbName = cmbKBs.Items[cmbKBs.SelectedIndex].ToString();

            _kb = SUMO.KnowledgeBases[kbName];
            PopulateManifest();
        }
Exemplo n.º 26
0
 public BandEnhancer(ILogger <BandEnhancer> logger, IKnowledgeBaseFactory knowledgeBaseFactory, string knowledgeBaseFileName, IWiki wikiSearch, IPersonsNameFinder personsNameFinder)
 {
     this.logger            = logger;
     this.knowledgeBase     = knowledgeBaseFactory.GetKnowledgeBase(knowledgeBaseFileName);
     this.wikiSearch        = wikiSearch;
     this.personsNameFinder = personsNameFinder;
 }
Exemplo n.º 27
0
 //TODO: convert all lists to arrays by index to improve performance
 public void CleanUp()
 {
     sender.CleanUp();
     sender       = null;
     canidateBid  = null;
     canidateTile = null;
     kb           = null;
     foreach (SearchTile s in openTiles)
     {
         s.CleanUp();
     }
     openTiles.Clear();
     openTiles = null;
     foreach (SearchTile s in tilesInAuction)
     {
         s.CleanUp();
     }
     tilesInAuction.Clear();
     tilesInAuction = null;
     foreach (SearchTile s in claimedTiles)
     {
         s.CleanUp();
     }
     claimedTiles.Clear();
     claimedTiles = null;
     foreach (SearchTile s in searchedTiles)
     {
         s.CleanUp();
     }
     searchedTiles.Clear();
     searchedTiles = null;
 }
Exemplo n.º 28
0
        //

        /**
         * function TT-CHECK-ALL(KB, &alpha; symbols, model) returns true or false
         *
         * @param kb
         *            KB, the knowledge base, a sentence in propositional logic
         * @param alpha
         *            &alpha;, the query, a sentence in propositional logic
         * @param symbols
         *            a list of currently unassigned propositional symbols in the
         *            model.
         * @param model
         *            a partially or fully assigned model for the given KB and
         *            query.
         * @return true if KB entails &alpha;, false otherwise.
         */
        public bool ttCheckAll(KnowledgeBase kb, Sentence alpha, ICollection <PropositionSymbol> symbols, Model model)
        {
            // if EMPTY?(symbols) then
            if (symbols.IsEmpty())
            {
                // if PL-TRUE?(KB, model) then return PL-TRUE?(&alpha;, model)
                if (model.isTrue(kb.asSentence()))
                {
                    return(model.isTrue(alpha));
                }
                else
                {
                    // else return true // when KB is false, always return true
                    return(true);
                }
            }

            // else do
            // P <- FIRST(symbols)
            PropositionSymbol p = Util.first(symbols);
            // rest <- REST(symbols)
            ICollection <PropositionSymbol> rest = Util.rest(symbols);

            // return (TT-CHECK-ALL(KB, &alpha;, rest, model &cup; { P = true })
            // and
            // TT-CHECK-ALL(KB, &alpha;, rest, model U { P = false }))
            return(ttCheckAll(kb, alpha, rest, model.union(p, true)) &&
                   ttCheckAll(kb, alpha, rest, model.union(p, false)));
        }
Exemplo n.º 29
0
 public bool UpLoading(KnowlegeDto newFile)
 {
     try
     {
         var mgdb = new MongoDbProvider <KnowledgeBaseFile>();
         using (var db = new BCEnterpriseContext())
         {
             var temp = new KnowledgeBase();
             temp.ID            = newFile.ID;
             temp.Name          = newFile.Name;
             temp.EnterpriseID  = newFile.EnterpriseID;
             temp.Deleted       = newFile.Deleted;
             temp.DocumentSize  = newFile.DocumentSize;
             temp.DocumentType  = (int)newFile.DocumentType;
             temp.KnowledgeType = newFile.KnowledgeType;
             temp.UpdateTime    = newFile.UpdateTime;
             temp.FileGUID      = newFile.FileGUID;
             temp.FileNumber    = newFile.FileNumber;
             temp.FileAllSize   = newFile.FileAllSize;
             db.KnowledgeBase.Add(temp);
             mgdb.SaveFileByStream(newFile.FileStream, newFile.ID, KnowlegeDbName);
             return(0 < db.SaveChanges());
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Exemplo n.º 30
0
        private static KnowledgeBase CreateKnowledgeBaseEntity(KnowledgeBaseCreateRequest request)
        {
            var entity = new KnowledgeBase()
            {
                CategoryId = request.CategoryId,

                Title = request.Title,

                SeoAlias = request.SeoAlias,

                Description = request.Description,

                Environment = request.Environment,

                Problem = request.Problem,

                StepToReproduce = request.StepToReproduce,

                ErrorMessage = request.ErrorMessage,

                Workaround = request.Workaround,

                Note = request.Note
            };

            if (request.Labels?.Length > 0)
            {
                entity.Labels = string.Join(',', request.Labels);
            }
            return(entity);
        }
Exemplo n.º 31
0
        public KnowledgeBase GetKnowledgeBaseDetail(int knowledgeBaseId, int districtId)
        {
            KnowledgeBase knowledgeBase = null;
            var           query         = from kb in _db.tblKnowledgeBases
                                          where kb.KnowledgeBaseId == knowledgeBaseId &&
                                          (kb.DistrictId == districtId || kb.DistrictId == null)
                                          select new KnowledgeBase
            {
                KnowledgeBaseId = kb.KnowledgeBaseId,
                Text            = kb.Text,
                Title           = kb.Title,
                CreatedDateTime = kb.CreateDatetime,
            };
            var dataKnowledgeBase = query.FirstOrDefault();

            knowledgeBase = dataKnowledgeBase;
            if (dataKnowledgeBase != null)
            {
                var attQuery = from kba in _db.tblKnowledgeBaseAttachments
                               join att in _db.tblAttachments on kba.AttachmentId equals att.AttachmentId
                               where kba.KnowledgeBaseId == dataKnowledgeBase.KnowledgeBaseId
                               select new FileDetail
                {
                    FileExtension    = att.FileExtension,
                    PhysicalFileName = att.FileName,
                    OriginalFileName = att.OriginalFileName
                };
                var attachments = attQuery.ToList();
                knowledgeBase.FileDetails = attachments;
            }
            return(knowledgeBase);
        }
Exemplo n.º 32
0
 protected virtual void Awake()
 {
     GetComponentInChildren<SpriteRenderer>().sprite = liveSprite;
     actions = GetComponent<Actions>();
     knowledgeBase = new KnowledgeBase(this);
     log = GameObject.Find("Log");
 }
Exemplo n.º 33
0
 private Playset(string path)
 {
     KnowledgeBase = new KnowledgeBase(Path.GetFileNameWithoutExtension(path), null);
     KnowledgeBase.Consult(Path.Combine(Application.dataPath, "Solver.prolog"));
     KnowledgeBase.Consult(path);
 }