private double GetScore(Goal goal, IPropagator propagator, HashSet <string> selection)
        {
            double maxSatRate;
            var    r = _model.Resolutions().Where(x => selection.Contains(x.ResolvingGoalIdentifier));

            // Integrate the selection
            foreach (var resolution in r)
            {
                integrator.Integrate(resolution);
            }

            var satRate = (DoubleSatisfactionRate)propagator.GetESR(goal);
            //var all_goals_satisfied = (satRate.SatisfactionRate > goal.RDS);

            //if (all_goals_satisfied) {
            var cost = selection.Count();

            maxSatRate = satRate.SatisfactionRate;

            foreach (var resolution in r)
            {
                integrator.Remove(resolution);
            }

            return(maxSatRate);
        }
        private double GetScore(IEnumerable <Goal> goals, IPropagator propagator, HashSet <string> selection, out IEnumerable <string> rootsSatisfied)
        {
            var r = _model.Resolutions().Where(x => selection.Contains(x.ResolvingGoalIdentifier));
            var rootGoalsSatisfied = new HashSet <string> ();

            integrator = new SoftResolutionIntegrator(_model);
            Console.WriteLine("---- Computing score for " + string.Join(",", selection) + ".");
            // Integrate the selection
            foreach (var resolution in r)
            {
                Console.WriteLine("Integrate " + resolution.ResolvingGoalIdentifier);
                integrator.Integrate(resolution);
            }

            var p2 = new BDDBasedPropagator(_model);

            //var all_goals_satisfied = true;
            var avg_sat_rate = 0.0;

            foreach (var goal in goals)
            {
                var satRate = ((DoubleSatisfactionRate)p2.GetESR(goal));
                avg_sat_rate += satRate.SatisfactionRate;
                if (satRate.SatisfactionRate >= goal.RDS)
                {
                    rootGoalsSatisfied.Add(goal.Identifier);
                }

                Console.WriteLine("Cost " + selection.Count);
                Console.WriteLine("Selected cm: " + string.Join(",", selection));
                Console.WriteLine($"{goal.Identifier} : {satRate.SatisfactionRate} >= {goal.RDS}.");
            }

            //var all_goals_satisfied = (satRate.SatisfactionRate > goal.RDS);


            var cost = selection.Count();


            foreach (var resolution in r)
            {
                integrator.Remove(resolution);
            }

            //if (!all_goals_satisfied)
            //{
            //	Console.WriteLine("---- not all goal satisfied, returning score = 0");
            //	return 0;
            //}

            rootsSatisfied = rootGoalsSatisfied;

            //if (satRate > goal.RDS) {
            Console.WriteLine("---- returning score = " + (avg_sat_rate / goals.Count()));
            return(avg_sat_rate / goals.Count());
            //} else {
            //	return 0;
            //}
        }
        /// <summary>
        /// Returns the minimal cost ensuring the goals respective RDSs. Returns -1 if no
        /// selection satisfy the RDS.
        /// </summary>
        /// <param name="goals">The goals</param>
        /// <returns>The minimal cost.</returns>
        public double GetMinimalCost(HashSet <Goal> goals, IPropagator propagator)
        {
            var timer   = Stopwatch.StartNew();
            int minCost = -1;

            var sr = new Dictionary <string, DoubleSatisfactionRate>();

            bool all_goals_satisfied = true;

            foreach (var goal in goals)
            {
                sr.Add(goal.Identifier, (DoubleSatisfactionRate)propagator.GetESR(goal));
                all_goals_satisfied &= (sr[goal.Identifier].SatisfactionRate > goal.RDS);
            }

            if (all_goals_satisfied)
            {
                return(0);
            }

            int count        = 0;
            int tested_count = 0;
            int safe_count   = 0;

            var countermeasure_goals = _model.Resolutions().Select(x => x.ResolvingGoalIdentifier).Distinct();

            foreach (var cg in GetAllCombinations(countermeasure_goals.ToList()))
            {
                count++;
                var cost = cg.Count();
                //if (minCost >= 0 && cost > minCost) continue;
                tested_count++;

                var r = _model.Resolutions().Where(x => cg.Contains(x.ResolvingGoalIdentifier));

                foreach (var resolution in r)
                {
                    integrator.Integrate(resolution);
                }

                sr = new Dictionary <string, DoubleSatisfactionRate>();
                all_goals_satisfied = true;
                foreach (var goal in goals)
                {
                    sr.Add(goal.Identifier, (DoubleSatisfactionRate)propagator.GetESR(goal));
                    all_goals_satisfied &= (sr[goal.Identifier].SatisfactionRate > goal.RDS);
                }

                if (all_goals_satisfied)
                {
                    safe_count++;
                    stats.MaxSafeCost = Math.Max(stats.MaxSafeCost, cost);

                    if (minCost == -1 || cost < minCost)
                    {
                        minCost = cost;
                    }
                }

                Console.WriteLine("Selection: "
                                  + string.Join(",", r.Select(x => x.ResolvingGoalIdentifier))
                                  + " cost: " + cost
                                  + " " + string.Join(" ", goals.Select(x => x.Identifier + ": " + sr[x.Identifier].SatisfactionRate)));

                foreach (var resolution in r)
                {
                    integrator.Remove(resolution);
                }
            }
            timer.Stop();
            stats.TimeToComputeMinimalCost = timer.Elapsed;
            stats.NbResolvingGoals         = countermeasure_goals.Count();
            stats.NbSelections             = count;
            stats.NbTestedSelections       = tested_count;
            stats.NbSafeSelections         = safe_count;

            return(minCost);
        }
Example #4
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!");
                        }
                    }
                }
        }
Example #5
0
        /// <summary>
        /// Returns the minimal cost ensuring the goal RDS. Returns -1 if no
        /// selection satisfy the RDS.
        /// </summary>
        /// <param name="goal">The goal</param>
        /// <returns>The minimal cost.</returns>
        public double GetMinimalCost(Goal goal, BDDBasedUncertaintyPropagator propagator)
        {
            var timer   = Stopwatch.StartNew();
            int minCost = -1;

            var sr = (SimulatedSatisfactionRate)propagator.GetESR(goal);

            if (sr.ViolationUncertainty(goal.RDS) < threshold)
            {
                return(0);
            }

            int count        = 0;
            int tested_count = 0;
            int safe_count   = 0;

            var countermeasure_goals = _model.Resolutions().Select(x => x.ResolvingGoalIdentifier).Distinct();

            foreach (var cg in GetAllCombinations(countermeasure_goals.ToList()))
            {
                count++;
                var cost = cg.Count();
                //if (minCost >= 0 && cost > minCost) continue;
                tested_count++;

                var r = _model.Resolutions().Where(x => cg.Contains(x.ResolvingGoalIdentifier));

                foreach (var resolution in r)
                {
                    integrator.Integrate(resolution);
                }

                sr = (SimulatedSatisfactionRate)propagator.GetESR(goal);

                // Console.WriteLine ( new OptimalSelection (r, cost, sr.SatisfactionRate) );

                foreach (var resolution in r)
                {
                    integrator.Remove(resolution);
                }

                if (sr.ViolationUncertainty(goal.RDS) < threshold)
                {
                    safe_count++;
                    stats.MaxSafeCost = Math.Max(stats.MaxSafeCost, cost);

                    if (minCost == -1 || cost < minCost)
                    {
                        minCost = cost;
                    }
                }
            }
            timer.Stop();
            stats.TimeToComputeMinimalCost = timer.Elapsed;
            stats.NbResolvingGoals         = countermeasure_goals.Count();
            stats.NbSelections             = count;
            stats.NbTestedSelections       = tested_count;
            stats.NbSafeSelections         = safe_count;

            return(minCost);
        }