Beispiel #1
0
        void ComputeObstructionSets()
        {
            obstructions = new Dictionary <Goal, ObstructionSuperset>();

            var roots = model.Goals(x => x.CustomData.ContainsKey("log_cps")).ToArray();

            foreach (var root in roots)
            {
                var obstructionSuperset = root.GetObstructionSuperset();
                obstructions.Add(root, obstructionSuperset);
            }
        }
Beispiel #2
0
        public void Render(KAOSModel model)
        {
            //var goalsInRefinements = model.GoalRefinements ().SelectMany (x => x.SubGoals ().Union (new[] {
            //    x.ParentGoal ()
            //})).Distinct ();

            foreach (var g in model.Goals())
            {
                Render(g);
            }

            foreach (var d in model.GoalRefinements().SelectMany(x => x.DomainProperties()).Distinct())
            {
                Render(d);
            }

            foreach (var d in model.GoalRefinements().SelectMany(x => x.DomainHypotheses()).Distinct())
            {
                Render(d);
            }

            foreach (var r in model.GoalRefinements())
            {
                Render(r);
            }

            foreach (var r in model.GoalAgentAssignments())
            {
                Render(r, true);
            }
        }
Beispiel #3
0
 void ExportGoals(StringBuilder builder)
 {
     builder.AppendLine("\n# Goals\n");
     foreach (var g in _model.Goals())
     {
         ExportGoal(builder, g);
     }
 }
        public void TestParsedDeclareGoal()
        {
            var model   = new KAOSModel();
            var path    = new Uri("/tmp/fake");
            var builder = new FirstStageBuilder(model, path);

            builder.BuildDeclare(new ParsedGoal("my-goal"));
            model.Goals(x => x.Identifier == "my-goal").ShallBeSingle();
        }
        public void Render(KAOSModel model)
        {
            //var goalsInRefinements = model.GoalRefinements ().SelectMany (x => x.SubGoals ().Union (new[] {
            //    x.ParentGoal ()
            //})).Distinct ();

            foreach (var g in model.Goals())
            {
                Render(g);
            }

            foreach (var d in model.GoalRefinements().SelectMany(x => x.DomainProperties()).Distinct())
            {
                Render(d);
            }

            foreach (var r in model.GoalRefinements())
            {
                Render(r);
            }

            foreach (var o in model.Obstacles())
            {
                Render(o);
            }

            foreach (var o in model.ObstacleRefinements())
            {
                Render(o);
            }

            foreach (var o in model.Obstructions())
            {
                Render(o);
            }

            foreach (var o in model.Resolutions())
            {
                Render(o);
            }

            foreach (var r in model.GoalAgentAssignments())
            {
                Render(r, true);
            }

            foreach (var o in model.Resolutions())
            {
                RenderAnchorArrow(o);
            }
        }
        public void Export(string filename)
        {
            writer = new StreamWriter(filename);
            foreach (var g in _model.Goals())
            {
                ExportGoal(g);
            }

            foreach (var g in _model.Obstacles())
            {
                Export(g);
            }

            writer.Close();
        }
        public KAOSModel Generate()
        {
            if (_options.NbObstacles < _options.NbObstructions)
            {
                throw new ArgumentException("Cannot generate a model with more obstructions than obstacles.");
            }


            root = GenerateGoal();

            var goalToRefine     = new Stack <Tuple <Goal, int> > (new [] { new Tuple <Goal, int> (root, 0) });
            var obstacleToRefine = new Stack <Tuple <Obstacle, int> > ();
            var leafGoal         = new HashSet <string> ();
            var leafObstacles    = new HashSet <string> ();

            while (_model.Goals().Count() < _options.NbGoals)
            {
                var current = goalToRefine.Pop();
                leafGoal.Remove(current.Item1.Identifier);
                var r = GenerateGoalRefinement(current.Item1);
                foreach (var sg in r.SubGoals())
                {
                    goalToRefine.Push(new Tuple <Goal, int> (sg, current.Item2 + 1));
                    leafGoal.Add(sg.Identifier);
                }
            }

            var nbleafGoals    = _model.LeafGoals().Count();
            var maxObstruction = Math.Min(nbleafGoals, _options.NbObstructions);

            while (_model.ObstructedGoals().Count() < maxObstruction)
            {
                int randomIndex = _random.Next(0, nbleafGoals);
                var current     = _model.Goal(leafGoal.ElementAt(randomIndex));
                leafGoal.Remove(current.Identifier);
                nbleafGoals--;
                var r = GenerateObstruction(current);
                obstacleToRefine.Push(new Tuple <Obstacle, int> (r.Obstacle(), 0));
                leafObstacles.Add(r.ObstacleIdentifier);
            }

            while (_model.Obstacles().Count() < _options.NbObstacles)
            {
                var current = obstacleToRefine.Pop();
                leafObstacles.Remove(current.Item1.Identifier);
                var nbRefinement = _random.Next(_options.MinObstacleORBranchingFactor,
                                                _options.MaxObstacleORBranchingFactor);
                for (int i = 0; i < nbRefinement; i++)
                {
                    var r = GenerateObstacleRefinement(current.Item1);
                    foreach (var sg in r.SubObstacles())
                    {
                        obstacleToRefine.Push(new Tuple <Obstacle, int> (sg, current.Item2 + 1));
                        leafObstacles.Add(sg.Identifier);
                    }
                }
            }

            foreach (var current in leafObstacles)
            {
                _model.satisfactionRateRepository.AddObstacleSatisfactionRate(current,
                                                                              new DoubleSatisfactionRate(_random.NextDouble()));
            }

            return(_model);
        }
Beispiel #8
0
        static void OptimizeLoop()
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };
            var currentSelection = new HashSet <string> ();

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: kaos_cm_selection_queue_name,
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    var _propagator_optimization = new BDDBasedPropagator(model);
                    while (!stop)
                    {
                        Thread.Sleep(TimeSpan.FromMinutes(1));

                        bool optimization_required = false;
                        foreach (var root in roots)
                        {
                            var doubleSatisfactionRate = modelMonitor.RootSatisfactionRates[root.Identifier];
                            if (doubleSatisfactionRate == null)
                            {
                                logger.Info($"Ignoring '{root.Identifier}', no satisfaction rate monitored.");
                                continue;
                            }
                            logger.Info($"RSR = " + root.RDS);
                            if (doubleSatisfactionRate.SatisfactionRate >= root.RDS)
                            {
                                logger.Info("Current configuration is above RSR for " + root.FriendlyName + ".");
                            }
                            else
                            {
                                logger.Info("Current configuration is below RSR for " + root.FriendlyName + ".");
                                optimization_required = true;
                            }
                        }

                        if (!optimization_required)
                        {
                            continue;
                        }

                        //var minimalcost = optimizer.GetMinimalCost(roots, _propagator_optimization);
                        //var optimalSelections = optimizer.GetOptimalSelections(minimalcost, roots, _propagator_optimization).FirstOrDefault();

                        var optimizer = new MOCECountermeasureSelectionOptimizer(optimization_model);
                        optimization_model.satisfactionRateRepository = modelMonitor._model_running.satisfactionRateRepository;

                        Console.WriteLine("Computing optimization");


                        var propagator        = new BDDBasedPropagator(optimization_model);
                        var enumerable        = new HashSet <Goal> (optimization_model.Goals(x => roots.Select(y => y.Identifier).Contains(x.Identifier)));
                        var optimalSelections = optimizer.GetOptimalSelections(enumerable, propagator);

                        if (optimalSelections.Count() == 0)
                        {
                            Console.WriteLine("Optimal selections: No countermeasure to select.");
                            Console.WriteLine();
                        }
                        else
                        {
                            Console.WriteLine($"Optimal selections ({optimalSelections.Count()}):");
                            foreach (var o in optimalSelections.Distinct().OrderBy(x => x.Cost).ThenBy(x => x.SatisfactionRate))
                            {
                                Console.WriteLine("* " + o);
                            }
                        }

                        if (optimalSelections.Count() > 0)
                        {
                            var optimalSelection = optimalSelections
                                                   .Where(x => x.SatRoots.SetEquals(roots.Select(y => y.Identifier)))
                                                   .OrderBy(x => x.Cost)
                                                   .ThenByDescending(x => x.SatisfactionRate)
                                                   .FirstOrDefault();

                            if (optimalSelection == null)
                            {
                                optimalSelection = optimalSelections
                                                   .OrderByDescending(x => x.SatRoots.Count)
                                                   .ThenBy(x => x.Cost)
                                                   .ThenByDescending(x => x.SatisfactionRate)
                                                   .FirstOrDefault();
                            }

                            if (optimalSelection == null)
                            {
                                logger.Info("No optimal selection found!");
                                return;
                            }

                            // Update the model
                            var deployment_methods = new List <string>();
                            foreach (var resolution in optimalSelection.Resolutions.Except(_active_resolutions))
                            {
                                _integrator_model.Integrate(resolution);
                                deployment_methods.Add(resolution.ResolvingGoal().CustomData["ondeploy"]);
                            }
                            foreach (var resolution in optimalSelection.Resolutions.Intersect(_active_resolutions))
                            {
                                _integrator_model.Remove(resolution);
                                deployment_methods.Add(resolution.ResolvingGoal().CustomData["onwithold"]);
                            }
                            modelMonitor.ModelChanged();

                            _active_resolutions = optimalSelection.Resolutions.ToHashSet();

                            // Deploy the countermeasures in the running system
                            var json = new JavaScriptSerializer().Serialize(deployment_methods);
                            logger.Info(json);

                            var body = Encoding.UTF8.GetBytes(json);

                            channel.BasicPublish(exchange: "",
                                                 routingKey: kaos_cm_selection_queue_name,
                                                 basicProperties: null,
                                                 body: body);
                        }
                        else
                        {
                            logger.Info("No selection found!");
                        }
                    }
                }
        }
Beispiel #9
0
        public static void Main(string[] args)
        {
            //DeployAmbulanceAtStationAllocator();
            //Thread.Sleep(TimeSpan.FromSeconds(10));

            Console.WriteLine("Hello World!");
            var monitoringDelay = TimeSpan.FromSeconds(1);

            logger.Info("Connecting to database");
            var provider         = new PostgreSQLDatabaseProvider();
            var connectionString = ConfigurationManager.ConnectionStrings["postgres"].ConnectionString;

            var config = DatabaseConfiguration.Build()
                         .UsingConnectionString(connectionString)
                         .UsingProvider(provider)
                         .UsingDefaultMapper <ConventionMapper>();

            db = new Database(config);
            incidentRepository      = new IncidentRepository(db);
            ambulanceRepository     = new AmbulanceRepository(db);
            allocationRepository    = new AllocationRepository(db);
            hospitalRepository      = new HospitalRepository(db);
            configurationRepository = new ConfigurationRepository(db);
            logger.Info("Connected to database");

            logger.Info("Building KAOS model.");
            var filename = "./Models/simple.kaos";
            var parser   = new KAOSTools.Parsing.ModelBuilder();

            model = parser.Parse(File.ReadAllText(filename), filename);
            var model2 = parser.Parse(File.ReadAllText(filename), filename);

            ActiveResolutions = Enumerable.Empty <Resolution>();

            var declarations = parser.Declarations;

            logger.Info("(done)");

            logger.Info("Configuring monitors.");
            // Configure all the monitors (for all obstacles and domain properties).
            KAOSMetaModelElement[] goals     = model.Goals().ToArray();
            KAOSMetaModelElement[] obstacles = model.LeafObstacles().ToArray();
            var projection = new HashSet <string>(GetAllPredicates(goals));

            monitor = new GoalMonitor(model, goals.Union(obstacles), projection, HandleFunc,
                                      // new TimedStateInformationStorage(TimeSpan.FromMinutes(60), TimeSpan.FromMinutes(120)),
                                      monitoringDelay);
            logger.Info("(done)");

            foreach (var p in model.Predicates())
            {
                Console.WriteLine(p.FriendlyName);
            }

            // What goals and obstacles should appear in LOG
            cpsGoals     = model.Goals(x => x.CustomData.ContainsKey("log_cps"));
            cpsObstacles = model.Obstacles(x => x.CustomData.ContainsKey("log_cps"));

            // Initialize obstruction sets
            obstructionLock = new object();
            ComputeObstructionSets();

            Console.WriteLine("Waiting ...");
            Console.ReadKey();

            logger.Info("Launching monitors");
            monitor.Run(false);

            var goalMonitorProcessor = new GoalMonitorProcessor(monitor);

            csvExport = new CSVGoalExportProcessor("experiment-goal.csv", "experiment-obstacle.csv");
            // goalMonitorProcessor.AddProcessor(csvExport, monitoringDelay);

            new Timer((state) => UpdateCPS(), null, monitoringDelay, monitoringDelay);
            new Timer((state) => MonitorStep(), null, monitoringDelay, monitoringDelay);
            Thread.Sleep(TimeSpan.FromSeconds(5));
            logger.Info("Launching processors");
            //new Timer((state) => LogStatistic(), null, monitoringDelay, monitoringDelay);
            new Timer((state) => LogCSV(), null, monitoringDelay, monitoringDelay);

            // Configure optimization process.
            optimizer = new Optimizer(monitor, model2);
            new Timer((state) => Optimize(), null, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(60));

            while (true)
            {
                ;
            }
        }