Пример #1
0
 public string init(params object[] esParams)
 {
     engine = new PrologEngine();
     dom = new XmlDocument();
     dom.Load((string)esParams[0]);
     XmlNodeList nl = dom.SelectNodes("//Predicate");
     foreach (XmlNode n in nl)
     {
         execProlog("retractall(" + ((XmlElement)n).InnerText + ").");
         execProlog("assert(" + ((XmlElement)n).InnerText + ").");
     }
     return null;
 }
Пример #2
0
        public override string ToProlog()
        {
            var queries = base.GetQueries("typically");
            var result  = false;

            foreach (var query in queries)
            {
                result = PrologEngine.ExecuteQuery(query);
                if (result)
                {
                    break;
                }
            }
            return(result.ToString());
        }
Пример #3
0
        static void Main(string[] args)
        {
            var prolog = new PrologEngine(persistentCommandHistory: false);

//            prolog.ConsultFromString(@"
//human(aaa).
//human(bbb).
//animals(ccc).
//droid(ddd).
//droid(eee).
//droid(ccc).
//life(X) :- human(X).
//life(X) :- animals(X).
//died(X) :- droid(X).
//kiborg(X) :- life(X), died(X).
//kiborg(kkk).
//");


            prolog.ConsultFromString(@"
parent(m1,m2).
parent(m2,m3).
parent(m3,m4).
parent(m4,m5).
all(X,Y):-parent(X,Y),X\=Y.
all(X,Y):-parent(X,A),parent(A,Y),X\=Y.
all(X,Y):-parent(X,A),parent(A,B),parent(B,Y),X\=Y.

main :- 
    setof([X, Y], all(X, Y), L),
    write(L),
    halt.
");

            //var solutionSet = prolog.GetAllSolutions(null, "kiborg(H)");
            var solutionSet = prolog.GetAllSolutions(null, "main");

            foreach (var s in solutionSet.NextSolution)
            {
                var ss = string.Empty;
                foreach (var v in s.NextVariable)
                {
                    ss += v.Value + "  ";
                }
                Console.WriteLine(ss);
            }
        }
Пример #4
0
        public bool checkIfDirectionOnBoard(string direction, int row, int col)
        {
            string prologQuery = "";

            pEngine = new PrologEngine(persistentCommandHistory: false);
            pEngine.ConsultFromString(prologCode);
            if (direction == "North" || direction == "South")
            {
                prologQuery = "guess" + direction + "(" + row + ").";
            }
            if (direction == "East" || direction == "West")
            {
                prologQuery = "guess" + direction + "(" + col + ").";
            }
            var solution = pEngine.GetFirstSolution(prologQuery);

            return(solution.Solved);
        }
Пример #5
0
    static void Main(string[] args)
    {
        // Prolog initialisieren
        var prolog           = new PrologEngine(persistentCommandHistory: false);
        var wissensdatenbank = Environment.CurrentDirectory + @"\stammbaum.pl";

        // Frage stellen und Antwort ausgeben
        SolutionSet result = prolog.GetAllSolutions(wissensdatenbank, query: "tochter(X,theodwyn).");

        Console.WriteLine("Frage: tochter(X,theodwyn).: ");
        Console.WriteLine(result.ToString());

        result = prolog.GetAllSolutions(@"C:\Prog\stammbaum.pl", "tochter(theodwyn,X).");
        Console.WriteLine("Frage: tochter(theodwyn,X).: ");
        Console.WriteLine(result.ToString());

        // Konsole offen halten
        Console.ReadLine();
    }
Пример #6
0
        private List <string> opensCourse(string a)
        {
            List <string> mylist = new List <string>();
            var           prolog = new PrologEngine(persistentCommandHistory: false);

            prolog.Consult("courses.pl");
            SolutionSet solution2 = prolog.GetAllSolutions("courses.pl", "prereq(ZZZ," + a + ").");

            for (int i = 0; i < solution2.Count; i++)
            {
                Solution s   = solution2[i];
                Variable abc = s.NextVariable.ToList()[0];
                if (abc.Value == "ZZZ")
                {
                    continue;
                }
                mylist.Add(abc.Value);
                //Console.WriteLine(abc.Value);
            }
            return(mylist);
        }
Пример #7
0
        public void ConsultFromString_GetOneSolution()
        {
            var prolog = new PrologEngine(persistentCommandHistory: false);

            // 'socrates' is human.
            prolog.ConsultFromString("human(socrates).");
            // 'R2-D2' is droid.
            prolog.ConsultFromString("droid(r2d2).");
            // human is bound to die.
            prolog.ConsultFromString("mortal(X) :- human(X).");

            // Question: Shall 'socrates' die?
            var solution1 = prolog.GetFirstSolution(query: "mortal(socrates).");

            Assert.True(solution1.Solved); // = "True" (Yes)

            // Question: Shall 'R2-D2' die?
            var solution2 = prolog.GetFirstSolution(query: "mortal(r2d2).");

            Assert.False(solution2.Solved); // = "False" (No)
        }
Пример #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GreetingDialog"/> class.
        /// </summary>
        /// <param name="botServices">Connected services used in processing.</param>
        /// <param name="botState">The <see cref="UserState"/> for storing properties at user-scope.</param>
        /// <param name="loggerFactory">The <see cref="ILoggerFactory"/> that enables logging and tracing.</param>
        public GreetingDialog(IStatePropertyAccessor <GreetingState> userProfileStateAccessor, ILoggerFactory loggerFactory)
            : base(nameof(GreetingDialog))
        {
            UserProfileAccessor = userProfileStateAccessor ?? throw new ArgumentNullException(nameof(userProfileStateAccessor));

            // Add control flow dialogs
            var waterfallSteps = new WaterfallStep[]
            {
                InitializeStateStepAsync,
                PromptForNameStepAsync,
                PromptForGenreStepAsync,
                DisplayGreetingStateStepAsync,
            };

            AddDialog(new WaterfallDialog(ProfileDialog, waterfallSteps));
            AddDialog(new TextPrompt(NamePrompt, ValidateName));
            AddDialog(new TextPrompt(GenrePrompt, ValidateGenre));

            _prologEngine = new PrologEngine(persistentCommandHistory: false);
            _prologEngine.Consult("db.pl");
            _prologBookService = new PrologBookService(_prologEngine);
        }
Пример #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BasicBot"/> class.
        /// </summary>
        /// <param name="botServices">Bot services.</param>
        /// <param name="accessors">Bot State Accessors.</param>
        public BasicBot(BotServices services, UserState userState, ConversationState conversationState, ILoggerFactory loggerFactory)
        {
            _services          = services ?? throw new ArgumentNullException(nameof(services));
            _userState         = userState ?? throw new ArgumentNullException(nameof(userState));
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));

            _greetingStateAccessor = _userState.CreateProperty <GreetingState>(nameof(GreetingState));
            _dialogStateAccessor   = _conversationState.CreateProperty <DialogState>(nameof(DialogState));

            // Verify LUIS configuration.
            if (!_services.LuisServices.ContainsKey(LuisConfiguration))
            {
                throw new InvalidOperationException($"The bot configuration does not contain a service type of `luis` with the id `{LuisConfiguration}`.");
            }

            Dialogs = new DialogSet(_dialogStateAccessor);
            Dialogs.Add(new GreetingDialog(_greetingStateAccessor, loggerFactory));

            _prologEngine = new PrologEngine(persistentCommandHistory: false);
            _prologEngine.Consult("db.pl");
            _prologBookService = new PrologBookService(_prologEngine);
        }
Пример #10
0
        public async Task <ActionResult> GetOperationsAsync()
        {
            List <string> ls = new List <string>();
            //IEnumerable<OutOperationDTO> lstOperationsDtos = new List<OutOperationDTO>();
            var prolog = new PrologEngine(persistentCommandHistory: false);

            // 'socrates' is human.
            prolog.Consult("sprint2_final.pl");
            //prolog.ConsultFromString("clientes([clA,clB,clC]).");

            // human is bound to die.
            //prolog.ConsultFromString("mortal(X) :- human(X).");

            // Question: Shall 'socrates' die?

            /*foreach (var sol in solutions.NextSolution)
             * {
             *  ls.Add(sol.ToString());
             * }*/

            return(Ok(ls));
        }
Пример #11
0
        public void UseMemImpl()
        {
            var prolog = new PrologEngine(persistentCommandHistory: false);

            prolog.ConsultFromString("mem(X,[X|List]). mem(X,[Y|List]) :- mem(X,List).");

            var sol1 = prolog.GetFirstSolution(query: "mem(a,[a,g,t,b]).");

            Assert.True(!prolog.Error & sol1.Solved);
            var sol2 = prolog.GetFirstSolution(query: "mem(z,[a,g,t,b]).");

            Assert.True(!prolog.Error);
            Assert.False(sol2.Solved);
            var sol3 = prolog.GetFirstSolution(query: "mem(g,[a,g,t,b]).");

            Assert.True(!prolog.Error & sol3.Solved);
            var sol4 = prolog.GetFirstSolution(query: "mem(a,[a]).");

            Assert.True(!prolog.Error & sol4.Solved);
            var sol5 = prolog.GetFirstSolution(query: "mem(a,[a].");

            Assert.True(prolog.Error & sol5.Solved);
        }
Пример #12
0
        public MainWindow()
        {
            InitializeComponent();
            dbContext = new Database1Entities();
            updatePrologFile();
            var prolog = new PrologEngine(persistentCommandHistory: false);

            prolog.Consult("courses.pl");

            /*// 'socrates' is human.
             * prolog.ConsultFromString("human(socrates).");
             * // human is bound to die.
             * prolog.ConsultFromString("mortal(X) :- human(X).");*/

            // Question: Shall 'socrates' die?
            //var solution = prolog.GetFirstSolution(query: "prereq(ece462,ZZZ).");
            //SolutionSet solution2 = prolog.GetAllSolutions("courses.pl", "prereq(ece561,ZZZ).");
            //Console.WriteLine(solution2[0]); // = "True" (Yes!)
            //Console.WriteLine(string.Join(",", solution2));

            /* var contacts = (from c in dbContext.courses select c).ToList(); //read data
             * foreach (course myc in contacts) {
             *   List<string> mylist = prereqOf(myc.course_code);
             *   for (int i = 0; i < mylist.Count; i++) {
             *       string temp = mylist[i];
             *       var result = dbContext.courses.First(x => x.course_code == temp);
             *       var records = dbContext.Set<prereq>();
             *       prereq abb = new prereq {
             *           course_code = myc.course_code,
             *           prerequisite_code = result.course_code
             *       };
             *       records.Add(abb);
             *       dbContext.SaveChanges();
             *   }
             * }*/
            //Console.WriteLine(solution.Solved); // = "True" (Yes!)
        }
Пример #13
0
 public PrologBookService(PrologEngine prologEngine)
 {
     _prologEngine = prologEngine;
 }
        public string DeterminarEnfermedad(DiagnosticoCreateCommand notification)
        {
            var    prolog = new PrologEngine(persistentCommandHistory: false);
            string absPath;

            var filename = "enfermedad.pl";

            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "production")
            {
                absPath = Path.GetFullPath($"./pl/{filename}");
            }
            else if (!IsRunningFromUnitTest)
            {
                absPath = Path.GetFullPath($"./../Diagnosticos.Service.EventHandlers/{filename}");
            }
            else
            {
                absPath = Path.GetFullPath($"./../../../../Diagnosticos.Service.EventHandlers/{filename}");
            }

            _logger.LogInformation($"Ruta del archivo: {absPath}");

            var enfermedades = new List <Enfermedad>
            {
                new Enfermedad {
                    Nombre = "gripe", Cantidad = 0, Porcentaje = 0, CantSintomas = 5d
                },
                new Enfermedad {
                    Nombre = "gripeA", Cantidad = 0, Porcentaje = 0, CantSintomas = 6d
                },
                new Enfermedad {
                    Nombre = "anemia", Cantidad = 0, Porcentaje = 0, CantSintomas = 5d
                },
                new Enfermedad {
                    Nombre = "rubeola", Cantidad = 0, Porcentaje = 0, CantSintomas = 4d
                },
                new Enfermedad {
                    Nombre = "dengue", Cantidad = 0, Porcentaje = 0, CantSintomas = 5d
                },
                new Enfermedad {
                    Nombre = "neumonia", Cantidad = 0, Porcentaje = 0, CantSintomas = 4d
                },
                new Enfermedad {
                    Nombre = "covid", Cantidad = 0, Porcentaje = 0, CantSintomas = 7d
                }
            };

            if (notification.DetallesDiagnostico == null || notification.DetallesDiagnostico.Count <= 0)
            {
                throw new DiagnosticosDiagnosticoCreateCommandException($"No hay detalles de diagnostico en el diagnostico.");
            }

            foreach (var detalle in notification.DetallesDiagnostico)
            {
                var solution = prolog
                               .GetAllSolutions(absPath, $"enfermedadde(Z, {detalle.Sintoma})")
                               .NextSolution;

                foreach (var variable in solution)
                {
                    var coincidencia = variable.NextVariable.First().Value;

                    if (enfermedades.Select(x => x.Nombre).Contains(coincidencia))
                    {
                        enfermedades.Single(x => x.Nombre == coincidencia).Cantidad++;
                    }
                }
            }

            foreach (var enfermedad in enfermedades)
            {
                enfermedad.Porcentaje = enfermedad.Cantidad * 100 / enfermedad.CantSintomas;
            }

            var maxPorc = enfermedades.Max(x => x.Porcentaje);

            if (maxPorc <= 0)
            {
                throw new DiagnosticosDiagnosticoCreateCommandException($"No hay detalles de diagnostico con sintomas predefinidos en el diagnostico");
            }

            return(enfermedades.First(x => x.Porcentaje == maxPorc).Nombre);
        }
Пример #15
0
 public LogicService()
 {
     fEngine = new PrologEngine(false);
 }
Пример #16
0
 public LogicService(BasicIo io)
 {
     fEngine = new PrologEngine(io, false);
 }
 public Form1()
 {
     InitializeComponent();
     PrologEngine.Start("reciclar.pl");
 }
Пример #18
0
 public PrologQuery(PrologEngine engine)
 {
     InitializeComponent();
     Engine = engine;
 }
Пример #19
0
 private void resetEngine()
 {
     this.pe = new PrologEngine(new SpaceIO("[VS:csp] "));
     SpaceIO.loadSource(ref pe);
     VSAlgo.logProlog("---Engine reset---");
 }
Пример #20
0
 public CSPrologLogicService()
 {
     _engine = new PrologEngine();
 }
        public bool PlayFromHistoryFile(string filePath)
        {
            int currentTurnIndex = 0;
            int previousTurnIndex;

            IFormatter formatter = new BinaryFormatter();

            using (FileStream s = File.OpenRead(filePath))
            {
                TurnRecords = (List <TurnRecord>)formatter.Deserialize(s);
            }

            bool?goForward = null;

            while (true)
            {
                if (goForward != null)
                {
                    if (goForward.Value)
                    {
                        foreach (Move move in TurnRecords[currentTurnIndex].Moves)
                        {
                            // output the moves that got us to this new state
                            DebugAndTraceHelper.WriteTraceLine(move.Role + " makes move " + move.TheMove, DebugAndTraceHelper.ManagerChannelId);
                        }
                    }
                    else
                    {
                        foreach (Move move in TurnRecords[currentTurnIndex + 1].Moves)
                        {
                            // output the moves that we are undoing to get to this state
                            DebugAndTraceHelper.WriteTraceLine(move.Role + " makes move " + move.TheMove, DebugAndTraceHelper.ManagerChannelId);
                        }
                    }
                }

                DebugAndTraceHelper.WriteTraceLine(TurnRecords[currentTurnIndex].GameState.GameStateAsXML, DebugAndTraceHelper.StateChannelId);

                if (StartNextMoveEvent != null)
                {
                    DebugAndTraceHelper.WriteTraceLine("Please click prev/next turn button to go to prev/next turn...", DebugAndTraceHelper.StatusStripChannelId);

                    goForward = null;
                    while (goForward == null)
                    {
                        if (StartNextMoveEvent.WaitOne(5))
                        {
                            goForward = true;
                        }
                        else if (PrevMoveEvent.WaitOne(5))
                        {
                            goForward = false;
                        }
                    }
                }
                else
                {
                    if (MilliSecondsBetweenFreeRunningMoves > 0)
                    {
                        Thread.Sleep(MilliSecondsBetweenFreeRunningMoves);
                    }

                    goForward = true;
                }

                previousTurnIndex = currentTurnIndex;
                if (goForward.Value)
                {
                    currentTurnIndex = Math.Min(currentTurnIndex + 1, TurnRecords.Max(n => n.Turn));
                }
                else
                {
                    currentTurnIndex = Math.Max(currentTurnIndex - 1, 0);
                }

                if (currentTurnIndex != previousTurnIndex)
                {
                    TheGeneralGame.PrologEngine.Reset();
                    foreach (string gameStateLine in TurnRecords[currentTurnIndex].GameState.GameStateFromProlog)
                    {
                        var foo = PrologEngine.CleanUpExistingPrologClauseForAsserting(gameStateLine);
                        TheGeneralGame.PrologEngine.Assert(PrologEngine.CleanUpExistingPrologClauseForAsserting(gameStateLine));
                    }
                }
            }

            return(true);
        }