コード例 #1
0
        public override List <TmsConstraint> GetTmsConstraints(ConfigurationConstraint constraint, Edge edge)
        {
            List <TmsConstraint> result    = new List <TmsConstraint>();
            RelationFamily       relFamily = constraint.AllowedRelations[0].RelationFamily;

            if (!(edge is MetricEdge))
            {
                edge.Network.SturcturalReasonerLog.AddItem(LogType.Warning, string.Format("Edge {0} is not a metric edge. The requested TMS constraints will not be added.", edge.GetUId()));
            }
            else if (!edge.Constraints.Contains(constraint))
            {
                edge.Network.SturcturalReasonerLog.AddItem(LogType.Warning, string.Format("The constraint {0} is not found in the edge {1}. The requested TMS constraints will not be added.", constraint.DomainConstraint.Name, edge.GetUId()));
            }
            else if (relFamily != StructuralRelationsManager.GetRelationFamily(RelationFamilyNames.MetricRelationsName))
            {
                edge.Network.SturcturalReasonerLog.AddItem(LogType.Warning, string.Format("The constraint {0} is qualitative while the needed relation for edge {1} is metric. The requested TMS constraints will not be added.", constraint.DomainConstraint.Name, edge.GetUId()));
            }
            else
            {
                string        dVarA         = edge.EndNode.GetDVarName();
                string        dVarMetric    = (constraint.RelationParts[1] as MetricRelationPart).GetDVarName();
                TmsConstraint tmsConstraint = new TmsConstraint();

                tmsConstraint.ConstraintType = TmsManager.CTNameGreaterThan;
                tmsConstraint.VariableTuple  = new List <string>()
                {
                    dVarA, dVarMetric, constraint.GetSatDVarName()
                };

                result.Add(tmsConstraint);
            }

            return(result);
        }
コード例 #2
0
        /// <summary>
        /// Finds the index of the set which includes a set of relations from a calculus
        /// </summary>
        /// <param name="calculus">The calculus</param>
        /// <param name="relations">The set of relations included in the set</param>
        /// <returns>The index of the set of relations in the powerset<returns>
        public static int GetPowersetIndex(this RelationFamily calculus, List <BinaryRelation> relations)
        {
            int setIx = 0;

            foreach (var rel in relations)
            {
                // The IdInCalculus bit specifies whether the relation is included in the constraint
                setIx += (int)Math.Pow(2, rel.IdInCalculus);
            }

            return(setIx);
        }
コード例 #3
0
        /// <summary>
        /// Creates a domain constraint restricting that the self edge of a node is restricted to use the equals relation of the family
        /// </summary>
        /// <returns></returns>
        public static DomainConstraint SelfEqualsConstraint(RelationFamily calculus)
        {
            DomainConstraint equalsConstraint = new DomainConstraint("Self equals", calculus.EqualsRelation, false);

            equalsConstraint.DomainRelationParts.Add(new ComponentDomainRelationPart(new ComponentFilter()));
            equalsConstraint.DomainRelationParts.Add(new ComponentDomainRelationPart(new ComponentFilter()
            {
                SameAsDomainRelationPartNr = 1
            }));

            return(equalsConstraint);
        }
コード例 #4
0
 public static string GetTmsCompositionConstraintName(this RelationFamily calculus)
 {
     return(string.Format("{0}_{1}", calculus.Name, TmsManager.CTNamePostfixCalculusComposition));
 }
コード例 #5
0
 public static string GetTmsRelationsDomainName(this RelationFamily calculus)
 {
     return(string.Format("{0}_{1}", calculus.Name, TmsManager.DomainNameCalculusPostfix));
 }
コード例 #6
0
 /// <summary>
 /// Finds the name of the constraint type which includes information for the powerset of the calculus
 /// </summary>
 /// <param name="calculus">The current calculus</param>
 /// <returns>The TMS name of the constraint type</returns>
 public static string GetPwSetCTName(this RelationFamily calculus)
 {
     return(string.Format("Calculus_{0}-Powerset", calculus.Name));
 }
コード例 #7
0
        public string PerformEvaluation(RelationFamily relFamily, bool includeSoftConstraints, bool allowZeroIntervals, int combinationConstraintsPercentage, int maxCombinationParts)
        {
            RandomProblemGenerator problemGenerator = new RandomProblemGenerator();
            StructuralReasoner     reasoner         = new StructuralReasoner();
            string                scenario;
            string                result;
            long                  configuringTmsTime;
            long                  solvingTime;
            Stopwatch             stopwatch  = new Stopwatch();
            List <List <string> > reportData = new List <List <string> >();
            List <string>         reportDataRow;

            problemGenerator.AllowZeroIntervals = allowZeroIntervals;
            problemGenerator.CombinationConstraintsPercentage = combinationConstraintsPercentage;
            problemGenerator.ConstraintsToComponentsRatio     = ConstraintsToComponentsRatio;
            problemGenerator.MaxCombinationParts    = maxCombinationParts;
            problemGenerator.SoftConstraintsEnabled = includeSoftConstraints;
            problemGenerator.RelationFamily         = relFamily;

            // Setting the scenario text
            scenario = string.Format("Scenarion: {0} relation family | Allow zero-length intervals: {1} | Min number of components: {2} | Maximum number of components: {3} | Constraints to components ratio: {4} | Iterations per component level: {5} | Soft constraints enabled: {6} | Maximum branches in combination constraint: {7} | Combination constraint percentage: {8} ", problemGenerator.RelationFamily.Name, problemGenerator.AllowZeroIntervals, ComponentsMinCount, ComponentsMaxCount, problemGenerator.ConstraintsToComponentsRatio, IterationsPerComponentLevel, problemGenerator.SoftConstraintsEnabled, problemGenerator.MaxCombinationParts, problemGenerator.CombinationConstraintsPercentage);

            stopwatch.Start();
            // The maximum maetric value that will be reached is equal to the maximum number of components that will be generated
            reasoner.Options.MaxMetricValue = ComponentsMaxCount;
            // The TMS has to be initially configured
            reasoner.ConfigureTms();
            stopwatch.Stop();
            configuringTmsTime = stopwatch.ElapsedMilliseconds;

            stopwatch.Restart();

            // Setting the headers row in the report data
            reportDataRow = new List <string>()
            {
                "Number of components", "(Expected) All constraints count", "(Actual) All constraints count", "(Expected) Combination constraints count", "(Actual) Combination constraints count", "Number of networks", "Error occurred", "Solution found", "Solving time in ms"
            };

            reportData.Add(reportDataRow);

            //try
            //{
            // For each component level...
            for (int i = ComponentsMinCount; i < ComponentsMaxCount + 1; i++)
            {
                problemGenerator.NumberOfComponents = i;

                // Solve the specified number of problems
                for (int j = 1; j < IterationsPerComponentLevel + 1; j++)
                {
                    ConfigurationStructure solution;
                    reportDataRow = new List <string>();

                    problemGenerator.GenerateProblem();
                    solution = reasoner.Solve(problemGenerator.GeneratedProblem);

                    // Log the qualitative case
                    reportDataRow.Add(problemGenerator.NumberOfComponents.ToString());
                    reportDataRow.Add(problemGenerator.NumberOfConstraints.ToString());
                    reportDataRow.Add(problemGenerator.NumberOfActualConstraints.ToString());
                    reportDataRow.Add(problemGenerator.NumberOfCombinationConstraints.ToString());
                    reportDataRow.Add(problemGenerator.NumberOfActualCombinationConstraints.ToString());

                    if (problemGenerator.RelationFamily != StructuralRelationsManager.MetricRelationsFamily)
                    {
                        reportDataRow.Add(solution.QualitativeStructure.Count.ToString());
                        reportDataRow.Add(solution.QualitativeStructure.Any(x => x.SolutionData.ErrorOccurred).ToString());
                        reportDataRow.Add(solution.QualitativeStructure.All(x => x.SolutionData.SolutionFound).ToString());
                        reportDataRow.Add(solution.QualitativeStructure.Sum(x => (x.SolutionData.EndTime - x.SolutionData.StartTime).Milliseconds).ToString());
                    }
                    else
                    {
                        reportDataRow.Add(solution.MetricStructure.SolutionsData.Count.ToString());
                        reportDataRow.Add(solution.MetricStructure.SolutionsData.Any(x => x.ErrorOccurred).ToString());
                        reportDataRow.Add(solution.MetricStructure.SolutionsData.All(x => x.SolutionFound).ToString());
                        reportDataRow.Add(solution.MetricStructure.SolutionsData.Sum(x => (x.EndTime - x.StartTime).Milliseconds).ToString());
                    }

                    reportData.Add(reportDataRow);
                }
            }

            result = "No exceptions";
            //}
            //catch (Exception ex)
            //{
            //    result = "Exception: " + ex.ToString();
            //}

            stopwatch.Stop();
            solvingTime = stopwatch.ElapsedMilliseconds;

            return(WriteToFile(scenario, result, configuringTmsTime, solvingTime, reportData));
        }
コード例 #8
0
        public string PerformTemporalQualitativeToMetricEvaluation(RelationFamily temporalFamily, bool includeSoftConstraints, bool includeTCSP)
        {
            RandomProblemGenerator problemGenerator = new RandomProblemGenerator();
            StructuralReasoner     reasoner         = new StructuralReasoner();
            string                scenario;
            string                result;
            long                  configuringTmsTime;
            long                  solvingTime;
            Stopwatch             stopwatch  = new Stopwatch();
            List <List <string> > reportData = new List <List <string> >();
            List <string>         reportDataRow;

            if (temporalFamily != StructuralRelationsManager.IntervalAlgebra && temporalFamily != StructuralRelationsManager.PointAlgebra)
            {
                throw new ArgumentException("The relation family can be only IA or PA");
            }

            // TCSP can be solved only for hard constraints
            if (includeSoftConstraints)
            {
                includeTCSP = false;
            }

            // The IA intervals have non-zero length
            problemGenerator.AllowZeroIntervals = false;
            // No combination constraints are generated
            problemGenerator.CombinationConstraintsPercentage = 0;
            // The number of constraints is based on the ratio specified by the property of this instance
            problemGenerator.ConstraintsToComponentsRatio = ConstraintsToComponentsRatio;
            // Not really relevant
            problemGenerator.MaxCombinationParts = 2;
            // Soft constraints are enabled/disabled based on the used argument
            problemGenerator.SoftConstraintsEnabled = includeSoftConstraints;

            // Setting the scenario text
            scenario = string.Format("Scenarion: {0} to metric evaluation | Allow zero-length intervals: {1} | Min number of components: {2} | Maximum number of components: {3} | Constraints to components ratio: {4} | Iterations per component level: {5} | Soft constraints enabled: {6} | Solve as TCSP: {7}", problemGenerator.RelationFamily.Name, problemGenerator.AllowZeroIntervals, ComponentsMinCount, ComponentsMaxCount, problemGenerator.ConstraintsToComponentsRatio, IterationsPerComponentLevel, problemGenerator.SoftConstraintsEnabled, includeTCSP);

            stopwatch.Start();
            // The maximum maetric value that will be reached is equal to the maximum number of components that will be generated
            reasoner.Options.MaxMetricValue = ComponentsMaxCount;
            // The TMS has to be initially configured
            reasoner.ConfigureTms();
            stopwatch.Stop();
            configuringTmsTime = stopwatch.ElapsedMilliseconds;

            stopwatch.Restart();

            // Setting the headers row in the report data
            reportDataRow = new List <string>()
            {
                "Number of components", "(Qual) All constraints count", "(Qual) Combination constraints count", "(Qual) Number of networks", "(Qual) Error occurred", "(Qual) Solution found", "(Qual) Solving time in ms", "(Metric) All constraints count", "(Metric) Combination constraints count", "(CDA*) Number of networks", "(CDA*) Error occurred", "(CDA*) Solution found", "(CDA*) Solving time in ms"
            };
            if (includeTCSP)
            {
                reportDataRow.AddRange(new List <string>()
                {
                    "(TCSP) Number of networks", "(TCSP) Error occurred", "(TCSP) Solution found", "(TCSP) Solving time in ms"
                });
            }

            reportData.Add(reportDataRow);

            //try
            //{
            // For each component level...
            for (int i = ComponentsMinCount; i < ComponentsMaxCount + 1; i++)
            {
                problemGenerator.NumberOfComponents = i;

                // Solve the specified number of problems
                for (int j = 1; j < IterationsPerComponentLevel + 1; j++)
                {
                    ConfigurationStructure solution;
                    reportDataRow = new List <string>();

                    // Generate and solve the IA problem
                    // No combination constraints should be generated
                    problemGenerator.CombinationConstraintsPercentage = 0;
                    // The problem family is set
                    problemGenerator.RelationFamily = temporalFamily;
                    problemGenerator.GenerateProblem();
                    solution = reasoner.Solve(problemGenerator.GeneratedProblem);

                    // Log the qualitative case
                    reportDataRow.Add(problemGenerator.NumberOfComponents.ToString());
                    reportDataRow.Add(problemGenerator.NumberOfActualConstraints.ToString());
                    reportDataRow.Add(problemGenerator.NumberOfActualCombinationConstraints.ToString());
                    reportDataRow.Add(solution.QualitativeStructure.Count.ToString());
                    reportDataRow.Add(solution.QualitativeStructure.Any(x => x.SolutionData.ErrorOccurred).ToString());
                    reportDataRow.Add(solution.QualitativeStructure.All(x => x.SolutionData.SolutionFound).ToString());
                    reportDataRow.Add(solution.QualitativeStructure.Sum(x => (x.SolutionData.EndTime - x.SolutionData.StartTime).Milliseconds).ToString());

                    // Generate and solve the equal metric problem with CDA*
                    problemGenerator.TransformToMetric();
                    reasoner.Options.MetricReasoningAlgorithm = MetricReasoningAlgorithm.CdaStar;
                    solution = reasoner.Solve(problemGenerator.GeneratedProblem);

                    // Lof the metric case
                    reportDataRow.Add(problemGenerator.NumberOfActualConstraints.ToString());
                    reportDataRow.Add(problemGenerator.NumberOfActualCombinationConstraints.ToString());
                    reportDataRow.Add(solution.MetricStructure.SolutionsData.Count.ToString());
                    reportDataRow.Add(solution.MetricStructure.SolutionsData.Any(x => x.ErrorOccurred).ToString());
                    reportDataRow.Add(solution.MetricStructure.SolutionsData.All(x => x.SolutionFound).ToString());
                    reportDataRow.Add(solution.MetricStructure.SolutionsData.Sum(x => (x.EndTime - x.StartTime).Milliseconds).ToString());

                    if (includeTCSP)
                    {
                        // Solve the metric problem as TCSP
                        reasoner.Options.MetricReasoningAlgorithm = MetricReasoningAlgorithm.Tcsp;
                        solution = reasoner.Solve(problemGenerator.GeneratedProblem);

                        // Log the TCSP case
                        reportDataRow.Add(solution.MetricStructure.SolutionsData.Count.ToString());
                        reportDataRow.Add(solution.MetricStructure.SolutionsData.Any(x => x.ErrorOccurred).ToString());
                        reportDataRow.Add(solution.MetricStructure.SolutionsData.All(x => x.SolutionFound).ToString());
                        reportDataRow.Add(solution.MetricStructure.SolutionsData.Sum(x => (x.EndTime - x.StartTime).Milliseconds).ToString());
                    }

                    reportData.Add(reportDataRow);
                }
            }

            result = "No exceptions";
            //}
            //catch (Exception ex)
            //{
            //    result = "Exception: " + ex.ToString();
            //}

            stopwatch.Stop();
            solvingTime = stopwatch.ElapsedMilliseconds;

            return(WriteToFile(scenario, result, configuringTmsTime, solvingTime, reportData));
        }
コード例 #9
0
 public QualitativeSolution GetQualitativeSolution(GKOStructuringContext structuredComponent, RelationFamily calculus)
 {
     return(QualitativeStructure.SingleOrDefault(x => x.StructuredComponent.Id == structuredComponent.Id && x.StructuringCalculus.Name == calculus.Name));
 }
コード例 #10
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="uId">The unique identifier of the network</param>
 internal ConstraintNetwork(RelationFamily relFamily, string uId, Log sturcturalReasonerLog)
     : this(relFamily, sturcturalReasonerLog)
 {
     this.UId = uId;
 }
コード例 #11
0
 /// <summary>
 /// Use with caution. The UId should always be assigned in the end
 /// </summary>
 /// <param name="relFamily">The relation family for which is the network</param>
 private ConstraintNetwork(RelationFamily relFamily, Log sturcturalReasonerLog)
 {
     Nodes = new List <Node>();
     Edges = new Dictionary <Tuple <Node, Node>, Edge>();
     this.RelationFamily = relFamily;
 }
コード例 #12
0
        internal static ConstraintNetwork GenerateQualitativeConstraintNetwork(GKOStructuringContext strContext, RelationFamily calculus, Log log)
        {
            ConstraintNetwork resultNetwork = new ConstraintNetwork(calculus, strContext.Id + "_" + calculus.Name, log);
            List <ConfigurationConstraintTree> constraintTrees = strContext.StructuralConstraints.Where(x => x.RelationFamily == calculus).ToList();

            // Creating the constraints restricting that self edges should be labeled with the Equals relation from the calculus
            DomainConstraint            equalsDomainConstraint = DomainConstraint.SelfEqualsConstraint(calculus);
            ConfigurationConstraintTree equalsConstraint       = new ConfigurationConstraintTree(null, equalsDomainConstraint, strContext.Components.Where(x => x.Active).ToList(), log);

            // Adding the constraints restricting that self edges should be labeled with the Equals relation from the calculus
            constraintTrees.Add(equalsConstraint);

            resultNetwork.Context = strContext;
            // Adding all components as nodes in the constraint network
            strContext.Components.Where(x => x.Active).ToList().ForEach(x => resultNetwork.Nodes.Add(new Node(x)));

            // Creating all edges in the constraint network, so it is a complete graph
            foreach (var startNode in resultNetwork.Nodes)
            {
                foreach (var endNode in resultNetwork.Nodes)
                {
                    QualitativeEdge edge = new QualitativeEdge(resultNetwork, startNode, endNode);
                    resultNetwork.Edges.Add(new Tuple <Node, Node>(startNode, endNode), edge);
                }
            }

            // Each constraint tree has a number of configuration constraints
            foreach (var constraintTree in constraintTrees)
            {
                List <ConfigurationConstraint> constraints = constraintTree.GetAllConfigurationConstraints();

                // ToDo: Add check for equal constraints to avoid redundancy

                // Adding all constraints as edges in the networks
                constraints.ForEach(x =>
                {
                    // Hack: this uses the fact that each constraint has at least one allowed relation and all have the same signature and logic (i.e. start and end node)
                    Node startNode             = x.AllowedRelations[0].GetStartNode(x);
                    Node endNode               = x.AllowedRelations[0].GetEndNode(x);
                    Tuple <Node, Node> edgeKey = new Tuple <Node, Node>(startNode, endNode);
                    QualitativeEdge edge       = resultNetwork.Edges[edgeKey] as QualitativeEdge;

                    // Adding the constraint to the edge
                    edge.Constraints.Add(x);
                });
            }

            return(resultNetwork);
        }
コード例 #13
0
        /// <summary>
        /// Solves the current problem given the configuration and the domain constraints
        /// </summary>
        /// <param name="configuration">The configuration to be structured</param>
        /// <param name="constraintsSource">The source for the domain constraints</param>
        /// <returns>The best found configuration structure given the constraints</returns>
        public ConfigurationStructure Solve(GKOConfiguration configuration, DomainConstraintsSource constraintsSource)
        {
            ConfigurationStructure       structure = new ConfigurationStructure();
            List <GKOStructuringContext> metricStructuredComponents;
            List <GKOStructuringContext> qualitativeStructuredComponents;
            List <ConstraintNetwork>     problemNetworks = new List <ConstraintNetwork>();
            RelationFamily metricRelations = StructuralRelationsManager.MetricRelationsFamily;
            Stopwatch      totalTime       = new Stopwatch();
            Stopwatch      stopwatch       = new Stopwatch();

            if (!this.Options.TmsConfigured)
            {
                throw new NotSupportedException("The TMS has to be configured before a structuring operation!");
            }
            if (configuration == null)
            {
                throw new InvalidOperationException("The configuration must be set before the solving process can start!");
            }
            if (constraintsSource == null)
            {
                throw new InvalidOperationException("The domain constraints source must be set before the solving process can start!");
            }

            constraintsSource.LoadDomainConstraints();

            totalTime.Start();

            stopwatch.Start();
            GenerateConfigurationConstraints(configuration, constraintsSource);
            stopwatch.Stop();

            ProcessLog.AddItem(LogType.Info, String.Format("Generating configuration constraints finished ({0} ms)", stopwatch.ElapsedMilliseconds));

            // Finding all structured conmponents which include metric reasoning...
            metricStructuredComponents = configuration.StructuringContexts.Where(x => x.Active && x.IncludedRelationFamilies.Contains(metricRelations)).ToList();
            // ... and qualitative reasoning
            qualitativeStructuredComponents = configuration.StructuringContexts.Where(x => x.Active && x.IncludedRelationFamilies.Any(y => y != metricRelations)).ToList();

            // Generating the metric constraint networks
            if (metricStructuredComponents.Count != 0)
            {
                List <ConstraintNetwork> metricNetworks = new List <ConstraintNetwork>();

                ProcessLog.AddItem(LogType.Info, String.Format("Generating metric constraint networks out of composite components starting"));
                stopwatch.Restart();

                metricNetworks = ConstraintNetwork.GenerateMetricConstraintNetworks(metricStructuredComponents, this.tms, this.Options, this.ProcessLog);
                problemNetworks.AddRange(metricNetworks);

                stopwatch.Stop();
                ProcessLog.AddItem(LogType.Info, String.Format("{0} metric constraint networks generated out of {1} composite components ({2} ms)", metricNetworks.Count, metricStructuredComponents.Count, stopwatch.ElapsedMilliseconds));
            }

            // Generating the qualitative constraint networks
            if (qualitativeStructuredComponents.Count != 0)
            {
                ProcessLog.AddItem(LogType.Info, String.Format("Generating qualitative constraint networks for the composite components starting"));
                stopwatch.Restart();
                foreach (var strComponent in qualitativeStructuredComponents)
                {
                    // Generating a new constraint network foreach qualitative calculus in a StructuredComponent
                    foreach (var calculus in strComponent.IncludedRelationFamilies.Where(x => x != metricRelations))
                    {
                        problemNetworks.Add(ConstraintNetwork.GenerateQualitativeConstraintNetwork(strComponent, calculus, this.ProcessLog));
                    }
                }
                stopwatch.Stop();
                ProcessLog.AddItem(LogType.Info, String.Format("Generating qualitative constraint networks for the composite components finished ({0} ms)", stopwatch.ElapsedMilliseconds));
            }

            foreach (var network in problemNetworks)
            {
                ProcessLog.AddItem(LogType.Info, String.Format("Starting structuring of constraint network {0}", network.UId));
                stopwatch.Restart();

                structure.AddSolutionInformation(network.Solve(this.Options, tms));

                stopwatch.Stop();
                ProcessLog.AddItem(LogType.Info, String.Format("Structuring of constraint network {0} finished ({1} ms)", network.UId, stopwatch.ElapsedMilliseconds));
            }

            totalTime.Stop();
            ProcessLog.AddItem(LogType.Info, String.Format("Structuring configuration finished - {0} constraint networks processed ({1} ms)", problemNetworks.Count, totalTime.ElapsedMilliseconds));

            return(structure);
        }