Ejemplo n.º 1
0
        private static async Task Render()
        {
            RenderStopWatch.Restart();

            if (_workerWindow == IntPtr.Zero && !DesktopHandler.TryGetWorkerWindow(out _workerWindow))
            {
                return;
            }

            if (!DesktopHandler.TryGetDeviceContext(_workerWindow, out var deviceContext))
            {
                return;
            }

            using (var bufferedGraphics = _bufferedGraphicsContext.Allocate(deviceContext, _area))
            {
                await _widgetService.Render(bufferedGraphics.Graphics);

                bufferedGraphics.Render(deviceContext);
                _bufferedGraphicsContext.Invalidate();
            }

            Native.ReleaseDC(_workerWindow, deviceContext);
            Debug.WriteLine($"Render() took: {RenderStopWatch.ElapsedMilliseconds}ms");
        }
Ejemplo n.º 2
0
        public static void Run(string csvFile, string solversDir, string inputFile, string optionFile)
        {
            FileManager.WriteToFile(csvFile, inputFile, true, true);

            foreach (string solver in SolverEnum.GetSolvers())
            {
                if (!FileManager.SolverPresent(solversDir, solver + ".solver"))
                {
                    continue;
                }

                ASPInputProgram       inputProgram = new ASPInputProgram();
                DesktopHandler        handler      = new DesktopHandler(SolverEnum.GetService(solversDir, solver));
                List <ISet <object> > answerSets   = new List <ISet <object> >();
                int optionID = handler.AddOption(new OptionDescriptor(SolverEnum.GetOutputOption(solver)));

                if (string.IsNullOrWhiteSpace(optionFile))
                {
                    FileManager.ReadFilters(optionFile, solver).ForEach(filter => handler.AddOption(new OptionDescriptor(" " + filter)));
                }

                handler.AddProgram(inputProgram);
                inputProgram.AddFilesPath(inputFile);

                List <string> sortedOutput = OutputManager.ProcessRawOutput(solver, ((AnswerSets)(handler.StartSync())).OutputString);

                handler.RemoveOption(optionID);

                var watch = System.Diagnostics.Stopwatch.StartNew();

                foreach (AnswerSet answerSet in ((AnswerSets)(handler.StartSync())).Answersets)
                {
                    answerSets.Add(answerSet.Atoms);
                }

                watch.Stop();
                FileManager.WriteToFile(csvFile, solver + ":" + watch.ElapsedMilliseconds.ToString(), null, true);

                if (answerSets.Count > 0)
                {
                    foreach (ISet <object> answerSet in answerSets)
                    {
                        string tmp = string.Join(" ", SortFacts(answerSet));

                        if (!sortedOutput.Contains(tmp))
                        {
                            Console.WriteLine("ERROR! Original " + solver + " output does not contain:\n" + tmp + "\n");
                        }
                        ;
                    }
                }
            }

            Console.WriteLine("END");
        }
Ejemplo n.º 3
0
        private static void Invalidate()
        {
            if (_workerWindow == IntPtr.Zero && !DesktopHandler.TryGetWorkerWindow(out _workerWindow))
            {
                return;
            }

            if (!DesktopHandler.TryGetDeviceContext(_workerWindow, out var deviceContext))
            {
                return;
            }

            var graphics = Graphics.FromHdc(deviceContext);

            using (graphics)
            {
                graphics.Clear(Color.Teal);
            }
        }
Ejemplo n.º 4
0
        public void TransitiveClosureTest()
        {
            try
            {
                DesktopHandler handler = new DesktopHandler(new IDLVDesktopService(GetPath()));

                DatalogMapper.Instance.RegisterClass(typeof(UnweightedPath));

                InputProgram input = new DatalogInputProgram();
                input.AddObjectInput(new UnweightedEdge(1, 2));
                input.AddObjectInput(new UnweightedEdge(2, 3));
                input.AddObjectInput(new UnweightedEdge(2, 4));
                input.AddObjectInput(new UnweightedEdge(3, 5));
                input.AddObjectInput(new UnweightedEdge(3, 6));

                input.AddProgram("path(X,Y) :- edge(X,Y).");
                input.AddProgram("path(X,Y) :- path(X,Z), path(Z,Y).");

                handler.AddProgram(input);

                IDLVMinimalModels minimalModels = (IDLVMinimalModels)handler.StartSync();

                Assert.IsNotNull(minimalModels);
                Assert.IsTrue(minimalModels.Minimalmodels.Count == 1);
                Assert.IsTrue(minimalModels.ErrorsString == "", "Found error:\n" + minimalModels.ErrorsString);

                foreach (MinimalModel m in minimalModels.Minimalmodels)
                {
                    foreach (object a in m.Atoms)
                    {
                        if (typeof(UnweightedPath).IsInstanceOfType(a))
                        {
                            Console.WriteLine(a);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Assert.Fail("Exception " + e.Message);
            }
        }
Ejemplo n.º 5
0
        public SymbolicConstant GetNextMove(InputProgram facts)
        {
            SymbolicConstant move             = new SymbolicConstant();
            string           encodingResource = @".\encodings\pacman.asp";
            //string encodingResource2 = @"encodings\min_distances_5.asp";
            //Debug.Log("DLV Started: " + numberOfSteps++);
            Handler      handler  = new DesktopHandler(new DLVDesktopService(@".\lib\dlv.exe"));
            InputProgram encoding = new ASPInputProgram();

            encoding.AddFilesPath(encodingResource);
            //InputProgram encoding2 = new ASPInputProgram();
            //encoding.AddFilesPath(encodingResource2);
            handler.AddProgram(encoding);
            //handler.AddProgram(encoding2);
            handler.AddProgram(facts);
            handler.AddOption(new OptionDescriptor("-filter=next"));
            Output o = handler.StartSync();
            //EmbaspCall++;



            AnswerSets answers = (AnswerSets)o;

            System.Random r      = new System.Random();
            int           answer = r.Next(answers.Answersets.Count);
            AnswerSet     a      = answers.Answersets[answer];

            foreach (object obj in a.Atoms)
            {
                //Debug.Log(obj.ToString());
                if (obj is Next)
                {
                    Next nextAction = (Next)obj;

                    move = nextAction.getAction();
                    return(move);
                    //Debug.Log("Next Action: " + move);
                }
            }
            return(move);
        }
Ejemplo n.º 6
0
        private static async Task Main(string[] args)
        {
            var displays = DisplayHandler.GetAll();

            var width  = 0;
            var height = 0;

            foreach (var display in displays)
            {
                width  += display.Width;
                height += display.Height;
            }

            _area = new Rectangle(
                0,
                0,
                width,
                height
                );

            _widgetService = new WidgetService();
            await _widgetService.Initialize();

            _bufferedGraphicsContext = new BufferedGraphicsContext();

            DesktopHandler.Initialize();

            var updateTimer = new QueuedTimer(async x => await Update(), UpdateInterval);
            var renderTimer = new QueuedTimer(async x => await Render(), RenderInterval);

            GC.KeepAlive(updateTimer);
            GC.KeepAlive(renderTimer);

            AppDomain.CurrentDomain.ProcessExit        += OnProcessExit;
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
            SystemEvents.SessionEnded += OnSessionEnded;

            new ManualResetEvent(false).WaitOne();
        }
Ejemplo n.º 7
0
        private void GenerateFacts(int dimension)
        {
            string encodingResource = @".\encodings\min_distances_" + dimension + ".asp";
            //Debug.Log("DLV Started: " + numberOfSteps++);
            Handler      handler  = new DesktopHandler(new DLVDesktopService(@".\lib\dlv.exe"));
            InputProgram encoding = new ASPInputProgram();

            encoding.AddFilesPath(encodingResource);
            handler.AddProgram(encoding);

            Output     o       = handler.StartSync();
            AnswerSets answers = (AnswerSets)o;

            //Debug.Log("Answers: " + o.OutputString);
            AnswerSet a = answers.Answersets[0];

            foreach (object obj in a.Atoms)
            {
                //Debug.Log(obj.ToString());
                if (obj is Distance)
                {
                    Distance d = (Distance)obj;
                    if (dimension == 10)
                    {
                        distances_10[d.getX1(), d.getY1()].Add(d);
                    }
                    else if (dimension == 5)
                    {
                        distances_5[d.getX1(), d.getY1()].Add(d);
                    }

                    //move = nextAction.getAction();
                    //Debug.Log("Next Action: " + move);
                }
            }
        }
Ejemplo n.º 8
0
        public void SudokuTest()
        {
            try
            {
                Handler      handler      = new DesktopHandler(new DLVDesktopService(GetPath()));
                InputProgram inputProgram = new ASPInputProgram();

                for (int i = 0; i < N; i++)
                {
                    for (int j = 0; j < N; j++)
                    {
                        if (sudokuMatrix[i, j] != 0)
                        {
                            inputProgram.AddObjectInput(new Cell(i, j, sudokuMatrix[i, j]));
                        }
                    }
                }

                inputProgram.AddFilesPath(".." + Path.DirectorySeparatorChar + ".." + Path.DirectorySeparatorChar + "test-resources" + Path.DirectorySeparatorChar + "asp" + Path.DirectorySeparatorChar + "sudoku");
                handler.AddProgram(inputProgram);
                handler.StartAsync(new CallbackAction(o =>
                {
                    if (!(o is AnswerSets))
                    {
                        return;
                    }

                    answerSets = (AnswerSets)o;

                    @lock.Signal();
                }));
                @lock.Wait(new TimeSpan(0, 0, 0, 0, 5000));
                Assert.IsNotNull(answerSets);
                Assert.IsTrue(String.IsNullOrEmpty(answerSets.ErrorsString), "Found error in the Plan\n" + answerSets.ErrorsString);

                if (answerSets.Answersets.Count == 0)
                {
                    return;
                }

                AnswerSet @as = answerSets.Answersets[0];

                foreach (object obj in @as.Atoms)
                {
                    Cell cell = (Cell)obj;
                    sudokuMatrix[cell.getRow(), cell.getColumn()] = cell.getValue();
                }

                for (int i = 0; i < N; i++)
                {
                    for (int j = 0; j < N; j++)
                    {
                        Console.Write(sudokuMatrix[i, j] + " ");

                        if (sudokuMatrix[i, j] == 0)
                        {
                            Assert.Fail("NumberNotValid");
                        }
                    }

                    Console.WriteLine();
                }
            }
            catch (Exception e)
            {
                Assert.Fail("Exception " + e.Message);
            }
        }
Ejemplo n.º 9
0
        public void Run()
        {
            reason = true;
            IMapper sensorMapper = mapper.getMapper(typeof(AdvancedSensor));

            while (reason)
            {
                if (!brain.executeReasonerOn.Equals("When Sensors are ready"))
                {
                    lock (brain.toLock)
                    {
                        MyDebugger.MyDebug("going to wait for pulse by brain");
                        brain.solverWaiting = true;
                        Monitor.Wait(brain.toLock);
                    }
                }
                try
                {
                    factsPath = Path.GetTempFileName();

                    using (StreamWriter fs = new StreamWriter(factsPath, true))
                    {
                        string toAppend = SensorsManager.GetSensorsMapping(brain);
                        if (!reason)
                        {
                            return;
                        }
                        fs.Write(toAppend);
                        fs.Close();
                    }
                }
                catch (Exception e)
                {
                    MyDebugger.MyDebug("CAUGHT EXECPTION!!!!");
                    MyDebugger.MyDebug(e.Message);
                    MyDebugger.MyDebug(e.StackTrace);
                }


                Handler handler = new DesktopHandler(new DLV2DesktopService(@".\lib\dlv2.exe"));
                //With DLV2DesktopService I get a Error during parsing: --> Invalid #show directive: setOnActuator/1--competition-output.
                //With DLVDesktopService the AS, obviously, are wrongly parsed
                InputProgram encoding = new ASPInputProgram();
                MyDebugger.MyDebug("adding encoding");
                encoding.AddFilesPath(Path.GetFullPath(brain.ASPFilePath));
                InputProgram facts = new ASPInputProgram();
                MyDebugger.MyDebug("adding facts");
                facts.AddFilesPath(factsPath);
                handler.AddProgram(encoding);
                handler.AddProgram(facts);
                handler.AddOption(new OptionDescriptor("--filter=setOnActuator/1 "));
                stopwatch.Restart();
                MyDebugger.MyDebug("starting sync");
                Output o = handler.StartSync();
                if (!o.ErrorsString.Equals(""))
                {
                    MyDebugger.MyDebug(o.ErrorsString + " " + o.OutputString);
                }
                AnswerSets answers = (AnswerSets)o;
                stopwatch.Stop();
                brain.asSteps++;
                brain.asTotalMS += stopwatch.ElapsedMilliseconds;
                MyDebugger.MyDebug("num of AS " + answers.Answersets.Count);
                if (answers.Answersets.Count > 0)
                {
                    lock (brain.toLock)
                    {
                        foreach (SimpleActuator actuator in brain.getActuators())
                        {
                            actuator.parse(answers.Answersets[0]);
                        }
                        brain.setActuatorsReady(true);
                    }
                }
                if (!brain.maintainFactFile)
                {
                    File.Delete(factsPath);
                }
            }
        }
        private void Test(int[] results_sizes, string instance_name)
        {
            string instance_path = base_path + instance_name + Path.DirectorySeparatorChar;

            Console.WriteLine("Testing " + results_sizes.Length + " files for " + instance_path);

            for (int i = 1; i <= results_sizes.Length; i++)
            {
                try
                {
                    plan  = null;
                    @lock = new CountdownEvent(1);
                    Handler handler = new DesktopHandler(new SPDDesktopService());

                    Console.WriteLine();

                    InputProgram inputProgramDomain = new PDDLInputProgram(PDDLProgramType.DOMAIN);

                    inputProgramDomain.AddFilesPath(instance_path + "domain.pddl");

                    InputProgram inputProgramProblem = new PDDLInputProgram(PDDLProgramType.PROBLEM);
                    string       problem             = instance_path + "p" + (i < 10 ? "0" : "") + i + ".pddl";

                    Console.WriteLine(problem);
                    Assert.IsTrue(File.Exists(problem), "File not found: " + problem);
                    inputProgramProblem.AddFilesPath(problem);
                    handler.AddProgram(inputProgramDomain);
                    handler.AddProgram(inputProgramProblem);
                    PDDLMapper.Instance.RegisterClass(typeof(PickUp));
                    Assert.IsNull(plan);
                    handler.StartAsync(new CallbackAction(o =>
                    {
                        if (!(o is Plan))
                        {
                            return;
                        }

                        plan = (Plan)o;

                        foreach (embasp.languages.pddl.Action action in plan.Actions)
                        {
                            Console.Write(action.Name + ",");
                        }

                        @lock.Signal();
                    }));
                    @lock.Wait(new TimeSpan(0, 0, 0, 0, 15000));
                    Assert.IsNotNull(plan);

                    if (results_sizes[i - 1] != 0)
                    {
                        Assert.IsTrue(String.IsNullOrEmpty(plan.ErrorsString) || plan.ErrorsString.ToLower().Contains("server busy"), "Found error in the Plan " + problem + "\n" + plan.ErrorsString);
                    }

                    if (plan.ErrorsString.ToLower().Contains("server busy."))
                    {
                        Console.WriteLine("[WARNING] Server busy occurred!");
                    }

                    Assert.AreEqual(results_sizes[i - 1], plan.Actions.Count);

                    foreach (object obj in plan.ActionsObjects)
                    {
                        if (obj is PickUp)
                        {
                            PickUp pickUp = (PickUp)obj;
                            Console.WriteLine(pickUp.getBlock());
                        }
                    }

                    Thread.Sleep(500);
                }
                catch (Exception e)
                {
                    Assert.Fail(e.Message);
                }
            }

            Console.WriteLine();
        }
        public void Run()
        {
            reason = true;
            IMapper sensorMapper = mapper.getMapper(typeof(AdvancedSensor));

            //Debug.Log("mapper " + sensorMapper);
            while (reason)
            {
                //Thread.Sleep(1000);
                //Debug.Log("executing thread");
                lock (brain.toLock)
                {
                    brain.solverWaiting = true;
                    Monitor.Wait(brain.toLock);
                    try
                    {
                        stopwatch.Restart();
                        factsPath = Path.GetTempFileName();

                        using (StreamWriter fs = new StreamWriter(factsPath, true))
                        {
                            //Debug.Log("creating file "+ factsPath);
                            string toAppend = "";
                            foreach (AdvancedSensor sensor in brain.getSensors())
                            {
                                //Stopwatch temp = new Stopwatch();
                                //temp.Start();
                                toAppend += sensor.Map();
                                //temp.Stop();
                                //Debug.Log(toAppend);
                                //Debug.Log(toAppend);
                            }
                            //Debug.Lof(fs.)
                            fs.Write(toAppend);
                            fs.Close();
                            //Debug.Log("closing stream");
                        }
                        stopwatch.Stop();
                        factsSteps++;
                        factsAvgTime += stopwatch.ElapsedMilliseconds;
                    }
                    catch (Exception e)
                    {
                        UnityEngine.Debug.LogError(e.Message);
                        UnityEngine.Debug.LogError(e.StackTrace);
                    }
                }
                //Debug.Log(Path.GetFullPath(@".\lib\dlv.exe"));
                Handler      handler  = new DesktopHandler(new DLVDesktopService(@".\lib\dlv2.exe"));
                InputProgram encoding = new ASPInputProgram();
                encoding.AddFilesPath(Path.GetFullPath(brain.ASPFilePath));
                InputProgram facts = new ASPInputProgram();
                facts.AddFilesPath(factsPath);
                handler.AddProgram(encoding);
                handler.AddProgram(facts);
                handler.AddOption(new OptionDescriptor("--filter=setOnActuator/1"));
                stopwatch.Restart();
                //Debug.Log("reasoning");
                Output o = handler.StartSync();
                if (!o.ErrorsString.Equals(""))
                {
                    Debug.Log(o.ErrorsString + " " + o.OutputString);
                }
                AnswerSets answers = (AnswerSets)o;
                stopwatch.Stop();
                asSteps++;
                asAvgTime += stopwatch.ElapsedMilliseconds;
                //Debug.Log("debugging answer set");
                //Debug.Log("there are "+answers.Answersets.Count);
                //Debug.Log("error: " + answers.ErrorsString);
                if (answers.Answersets.Count > 0)
                {
                    /*string asPath = Path.GetTempFileName();
                     * using (StreamWriter fs = new StreamWriter(asPath, true))
                     * {
                     *  fs.Write(o.OutputString);
                     *  fs.Close();
                     * }*/
                    lock (brain.toLock)
                    {
                        foreach (SimpleActuator actuator in brain.getActuators())
                        {
                            Debug.Log("input fact " + factsPath);
                            Debug.Log("parsing " + actuator.actuatorName);
                            if (answers.Answersets[0].GetAnswerSet().Count > 0)
                            {
                                Debug.Log(answers.Answersets[0].GetAnswerSet()[0]);
                            }
                            actuator.parse(answers.Answersets[0]);
                        }
                        brain.setActuatorsReady(true);
                    }
                }
                if (!brain.maintainFactFile)
                {
                    File.Delete(factsPath);
                }
            }
        }
        public void ShortestPathTest()
        {
            try
            {
                DesktopHandler handler = new DesktopHandler(new DLV2DesktopService(GetPath()));

                ASPMapper.Instance.RegisterClass(typeof(Edge));
                ASPMapper.Instance.RegisterClass(typeof(Path));

                InputProgram input = new ASPInputProgram();

                from = 0;   // source node
                to   = 7;   // destination node

                String rules = "from(" + from + ").to(" + to + ")." +
                               "path(X,Y,W) | notPath(X,Y,W) :- from(X), edge(X,Y,W)." +
                               "path(X,Y,W) | notPath(X,Y,W) :- path(_,X,_), edge(X,Y,W), not to(X)." +
                               "visited(X) :- path(_,X,_)." +
                               ":- to(X), not visited(X)." +
                               ":~ path(X,Y,W). [W@1 ,X,Y]";

                input.AddProgram(rules);

                foreach (Edge edge in getEdges())
                {
                    input.AddObjectInput(edge);
                }

                handler.AddProgram(input);

                DLV2AnswerSets answerSets = (DLV2AnswerSets)handler.StartSync();

                Assert.IsNotNull(answerSets);
                Assert.IsTrue(answerSets.GetOptimalAnswerSets().Count != 0);
                Assert.IsTrue(answerSets.ErrorsString == "", "Found error:\n" + answerSets.ErrorsString);

                AnswerSet answerSet = answerSets.GetOptimalAnswerSets()[0];

                List <Path> path = new List <Path>();  //  edges in the shortest path (unsorted)
                int         sum  = 0;                  //  total weight of the path

                foreach (object obj in answerSet.Atoms)
                {
                    if (typeof(Path).IsInstanceOfType(obj))
                    {
                        path.Add((Path)obj);
                        sum += ((Path)obj).getWeight();
                    }
                }

                sortedPath = new List <int>();     // edges in the shorted path (sorted)
                sortedPath.Add(from);

                join(from, path, sortedPath);     // sorts the edges
                print(sortedPath, sum);           // shows the result
            }
            catch (Exception e)
            {
                Assert.Fail("Exception " + e.Message);
            }
        }