/// <summary>Creates/replaces the override entry for the given color layer property with the given evaluatable numbers.</summary>
 /// <param name="layerPropertyName">The name of an color layer property (e.g. "_PrimaryColor").</param>
 /// <param name="a">The evaluatable number that will be used as the alpha property for this color.</param>
 /// <param name="r">The evaluatable number that will be used as the red property for this color.</param>
 /// <param name="g">The evaluatable number that will be used as the green property for this color.</param>
 /// <param name="b">The evaluatable number that will be used as the blue property for this color.</param>
 public OverrideLogicBuilder SetDynamicColor(string layerPropertyName, IEvaluatable <double> a, IEvaluatable <double> r, IEvaluatable <double> g, IEvaluatable <double> b)
 {
     overrideProperties[layerPropertyName] = new OverrideDynamicValue(typeof(System.Drawing.Color), new Dictionary <string, IEvaluatable> {
         { "Alpha", a }, { "Red", r }, { "Green", g }, { "Blue", b }
     });
     return(this);
 }
        public bool IsTrueInAtLeastTwo <WorldType>(IEvaluatable rule, IEnumerable <WorldType> worlds)
        {
            _metricService.IncrementMetric("IsTrueInAtLeastTwo");
            var positiveCount = worlds.Count(world => _ruleEvaluator.IsTrueIn(rule, world));

            return(positiveCount >= 2);
        }
Example #3
0
        public bool RelationallyEquivalentTo(IEvaluatable evaluatable)
        {
            if (evaluatable.GetType() != typeof(Disjunction))
            {
                return(false);
            }
            var scenario = evaluatable as Disjunction;

            foreach (var arg in Arguments)
            {
                if (!ScenarioContainsArgumentRelation(scenario.Arguments, arg))
                {
                    return(false);
                }
            }

            foreach (var arg in scenario.Arguments)
            {
                if (!ScenarioContainsArgumentRelation(Arguments, arg))
                {
                    return(false);
                }
            }

            return(true);
        }
 public NumericChangeDetector(IEvaluatable <double> eval, bool detectRising = true, bool detectFalling = true, double threshold = 0)
 {
     Evaluatable        = eval;
     DetectRising       = detectRising;
     DetectFalling      = detectFalling;
     DetectionThreshold = threshold;
 }
        public double Evaluate(IEvaluatable node, int a, int b)
        {
            _Parameters["a"] = a;
            _Parameters["b"] = b;

            return node.Evaluate(_Parameters);
        }
Example #6
0
 /// <summary>
 /// Interal helper function to simplify/shorten the public API methods.
 /// </summary>
 private OverrideLogicBuilder SetDynamic(Type type, string layerPropertyName, IEvaluatable evaluatable)
 {
     overrideProperties[layerPropertyName] = new OverrideDynamicValue(type, new Dictionary <string, IEvaluatable> {
         { "Value", evaluatable }
     });
     return(this);
 }
Example #7
0
        public VariableDefinition(Node node)
        {
            Node VariableIdNode = node.Attributes.GetNamedItem("VariableId");

            if (VariableIdNode != null)
            {
                this._variableId = VariableIdNode.NodeValue;
            }
            else
            {
                throw new Indeterminate(Indeterminate.IndeterminateSyntaxError);
            }
            this._evaluatable = null;
            NodeList children = node.ChildNodes;

            for (int i = 0; i < children.Length; i++)
            {
                Node child = children.Item(i);
                if (child.NodeType == Node.ELEMENT_NODE)
                {
                    IElement e = PolicyElementFactory.GetInstance(children.Item(i));
                    if (e is IEvaluatable)
                    {
                        this._evaluatable = (IEvaluatable)e;
                        break;
                    }
                }
            }
            if (this._evaluatable == null)
            {
                throw new Indeterminate(Indeterminate.IndeterminateSyntaxError);
            }
        }
Example #8
0
        public static Any Of(IEvaluatable argument)
        {
            var newJunction = new Disjunction();

            JunctionHelper.AddArgumentToJunction <Disjunction>(newJunction, argument);
            return(new Any(newJunction));
        }
Example #9
0
        private string FactToEasyRuleFormat(IEvaluatable construct)
        {
            var fact             = construct as Proposition;
            var friendlyOperator = _operatorSynonyms.First(m => m.Value == fact.Operator).Key;

            return($"{_attOpen}{fact.AttributeName}{_attClose} {friendlyOperator} {(fact.BinaryArgument? _binaryArgOpen:"")}{_valOpen}{fact.AttributeValue}{_valClose}{(fact.BinaryArgument ? _binaryArgClose : "")}");
        }
Example #10
0
        public static All Of(IEvaluatable argument)
        {
            var newJunction = new Conjunction();

            JunctionHelper.AddArgumentToJunction <Conjunction>(newJunction, argument);
            return(new All(newJunction));
        }
        public bool IsTrueInOnlyFew <WorldType>(IEvaluatable rule, IEnumerable <WorldType> worlds)
        {
            _metricService.IncrementMetric("IsTrueInOnlyFew");
            var positiveCount = worlds.Count(world => _ruleEvaluator.IsTrueIn(rule, world));

            return(positiveCount / worlds.Count() <= 0.34);
        }
        public void Context()
        {
            AGenome = "rx";
            Converter = new GenomeConverter();
            Ast = Converter.Convert(AGenome);

            Because();
        }
Example #13
0
        private string DisjunctionToEasyRuleFormat(IEvaluatable construct)
        {
            var scenario = construct as Disjunction;

            return(scenario.Arguments
                   .Select(x => Parenthesize(x, x.ToFormattedString(DymeConstructToFormattedString)))
                   .Aggregate((a, b) => $"{a} OR {b}"));
        }
Example #14
0
 private string Parenthesize(IEvaluatable construct, string argument)
 {
     if (construct.GetType() != typeof(Proposition))
     {
         return($"{_openEncapsulation}{argument}{_closeEncapsulation}");
     }
     return(argument);
 }
Example #15
0
        public static If When(IEvaluatable antecedant)
        {
            var implication = Implication.Create();

            implication.Antecedent = antecedant;
            var imply = new If(implication);

            return(imply);
        }
Example #16
0
 public bool RelationallyEquivalentTo(IEvaluatable evaluatable)
 {
     if (evaluatable.GetType() == typeof(Implication))
     {
         var implication = evaluatable as Implication;
         return(Antecedent.RelationallyEquivalentTo(implication.Antecedent) && Consequent.RelationallyEquivalentTo(implication.Consequent));
     }
     return(false);
 }
Example #17
0
 /// <summary>
 /// Obtains an array that describes what sets of criteria a data set has "cleared", and which they haven't.
 /// </summary>
 public static bool[] GetCriteriaResults(SportSettings settings, IEvaluatable toEvaluate)
 {
     return(new bool[]
     {
         (settings.MinAge <= toEvaluate.Edad && toEvaluate.Edad <= settings.MaxAge),
         (settings.MinHeight <= toEvaluate.Estatura && toEvaluate.Estatura <= settings.MaxHeight),
         (settings.MinIMC <= toEvaluate.IMC && toEvaluate.IMC <= settings.MaxIMC)
     });
 }
 public TrainingSession(INeuralNetwork nn, IEvaluatable evaluatable, int sessionNumber, bool isIdempotent = true)
 {
     NeuralNet = nn;
     _evaluatable = evaluatable;
     _sessionNumber = sessionNumber;
     _hasStoredSessionEval = false;
     _sessionEval = 0;
     _isIdempotent = isIdempotent;
 }
 public TrainingSession(INeuralNetwork nn, IEvaluatable evaluatable, int sessionNumber, bool isIdempotent = true)
 {
     NeuralNet             = nn;
     _evaluatable          = evaluatable;
     _sessionNumber        = sessionNumber;
     _hasStoredSessionEval = false;
     _sessionEval          = 0;
     _isIdempotent         = isIdempotent;
 }
Example #20
0
        public bool RelationallyEquivalentTo(IEvaluatable evaluatable)
        {
            if (evaluatable.GetType() != typeof(Proposition))
            {
                return(false);
            }
            var fact = evaluatable as Proposition;

            return(fact.AttributeName == AttributeName);
        }
Example #21
0
 public static void AddArgumentToJunction <T>(IJunction junction, IEvaluatable argument)
 {
     if (IsJunctionOfType <T>(argument))
     {
         junction.Arguments = MergeArgumentsReturnNewSet(junction, argument as IJunction);
     }
     else
     {
         junction.Arguments = AddArgumentReturnNewSet(junction, argument);
     }
 }
Example #22
0
 public static OverrideLogicBuilder InGameAnd(IEvaluatable <bool> eval)
 {
     return(new OverrideLogicBuilder().SetDynamicBoolean("_Enabled",
                                                         new BooleanAnd(
                                                             new IEvaluatable <bool>[] {
         new BooleanGSIBoolean("Match/InGame"),
         eval
     }
                                                             )
                                                         ));
 }
Example #23
0
 /// <summary>Attempts to get an evaluatable from the suppliied data object. Will return true/false indicating if data is of correct format
 /// (an <see cref="IEvaluatable{T}"/> where T matches the given type. If the eval type is null, no type check is performed, the returned
 /// evaluatable may be of any sub-type.</summary>
 internal static bool TryGetData(IDataObject @do, out IEvaluatable evaluatable, out Control_EvaluatablePresenter source, Type evalType)
 {
     if (@do.GetData(@do.GetFormats().FirstOrDefault(x => x != "SourcePresenter")) is IEvaluatable data && (evalType == null || Utils.TypeUtils.ImplementsGenericInterface(data.GetType(), typeof(IEvaluatable <>), evalType)))
     {
         evaluatable = data;
         source      = @do.GetData("SourcePresenter") as Control_EvaluatablePresenter;
         return(true);
     }
     evaluatable = null;
     source      = null;
     return(false);
 }
Example #24
0
        /// <summary>
        /// Инициализирует функцию на основе вычисляемого значения
        /// </summary>
        /// <param name="item">Вычисляемое значение</param>
        /// <exception cref="ParserException">Возникает при несоответствии переданных параметров требованиям</exception>
        public void Initialize(IEvaluatable <T> item)
        {
            // ReSharper disable once JoinNullCheckWithUsage
            if (item == null)
            {
                throw new ParserException($"Недостаточно параметров для функции \"{this}\"");
            }

            _item = item;

            Initialized = true;
        }
Example #25
0
        /// <summary>
        /// Инициализирует функцию на основании двух вычисляемых значений
        /// </summary>
        /// <param name="first">Первое вычисляемое значение</param>
        /// <param name="second">Второе вычисляемое значение</param>
        /// <exception cref="ParserException">Возникает при несоответствии переданных параметров требованиям</exception>
        public void Initialize(IEvaluatable <T> first, IEvaluatable <T> second)
        {
            if (first == null || second == null)
            {
                throw new ParserException($"Недостаточно параметров для функции \"{this}\"");
            }

            _first  = first;
            _second = second;

            Initialized = true;
        }
        public bool RemoveExpression(IEvaluatable expression)
        {
            int index = expressions.IndexOf(expression);

            if (index == -1)
            {
                return(false);
            }
            expressions.RemoveAt(index);
            expColors.RemoveAt(index);
            expVisible.RemoveAt(index);
            return(true);
        }
        public IEnumerable <int> IsTrueInWorldsReturnWorldIndexes <WorldType>(IEvaluatable rule, IEnumerable <WorldType> worlds)
        {
            _metricService.IncrementMetric("IsTrueInWorldsReturnWorldIndexes");
            var indexedWorlds = worlds.ToArray();
            var indexes       = new List <int>();

            for (var i = 0; i < indexedWorlds.Length; i++)
            {
                var world = indexedWorlds[i];
                if (_ruleEvaluator.IsTrueIn(rule, world))
                {
                    indexes.Add(i);
                }
            }
            return(indexes);
        }
        double _GetScoreByEvaluatingClosenessToRealDeal(IEvaluatable node)
        {
            var aggregateResult = 0.0;

            for(var a=100; a < 105; a++)
            {
                for(var b=100; b<105; b++)
                {
                    var geneResult = Evaluate(node, a, b);
                    var actualResult = Math.Sqrt(a.Squared() + b.Squared());

                    aggregateResult += - Math.Abs(geneResult - actualResult);
                }
            }

            return aggregateResult / 100;
        }
Example #29
0
        /// <summary>
        /// Analysiert ein gegebenes Szenario. Dabei werden verschiedene Leistungsmetriken
        /// quantifiziert. Die Rate der erfolgreichen Buchungen, überflüssige Auslastung,
        /// zusätzlicher Bedarf an Resourcen, Verteilung der Stecker akzeptierter Buchungen
        /// und Verteilung der Stecker abgelehnter Buchungen.
        /// </summary>
        /// <param name="_scenario">Das zu untersuchende Szenario.</param>
        /// <returns></returns>
        public static Evaluation analyze(IEvaluatable _scenario)
        {
            scenario = _scenario;
            List <List <double> > plugTypeDistribution = calcPlugTypeDistribution();

            evaluation = new Evaluation()
            {
                suggestions              = createSuggestion(),
                bookingSuccessRate       = calcBookingSuccessRate(),
                unneccessaryWorkload     = calcUnnecessaryWorkload(),
                neccessaryWorkload       = calcNecessaryWorkload(),
                plugDistributionAccepted = plugTypeDistribution[0],
                plugDistributionDeclined = plugTypeDistribution[1],
                scenario = (ExecutedScenario)_scenario
            };

            // Berechnungen.
            List <Booking>   declined = new List <Booking>();
            int              declinedBookingsInGeneratedBookings = 0;
            int              acceptedBookingsInGeneratedBookings = 0;
            ExecutedScenario s = (ExecutedScenario)scenario;

            foreach (Booking b in s.bookings)
            {
                if (!s.location.schedule.bookings.Contains(b))
                {
                    declined.Add(b);
                }
            }
            foreach (Booking b in s.location.schedule.bookings)
            {
                if (s.bookings.Contains(b))
                {
                    acceptedBookingsInGeneratedBookings++;
                }
            }
            foreach (Booking b in declined)
            {
                if (s.bookings.Contains(b))
                {
                    declinedBookingsInGeneratedBookings++;
                }
            }

            return(evaluation);
        }
Example #30
0
        private bool EvaluateAgainst <World>(IEvaluatable evaluatable, World world)
        {
            switch (evaluatable.GetType().Name)
            {
            case nameof(Conjunction):
                return(EvaluateConjunction(evaluatable as Conjunction, world));

            case nameof(Implication):
                return(EvaluateImplication(evaluatable as Implication, world));

            case nameof(Disjunction):
                return(EvaluateDisjunction(evaluatable as Disjunction, world));

            case nameof(Proposition):
                return(EvaluateProposition(evaluatable as Proposition, world));
            }
            throw new Exception("Unknown construct");
        }
Example #31
0
        public string DymeConstructToFormattedString(IEvaluatable construct)
        {
            var constructType = construct.GetType().Name.ToString();

            switch (constructType)
            {
            case nameof(Proposition):
                return(FactToEasyRuleFormat(construct));

            case nameof(Conjunction):
                return(ConjunctionToEasyRuleFormat(construct));

            case nameof(Disjunction):
                return(DisjunctionToEasyRuleFormat(construct));

            case nameof(Implication):
                return(ImplyToEasyRuleFormat(construct));
            }
            throw new ArgumentOutOfRangeException();
        }
Example #32
0
        public AttributeAssignmentExpression(Node node)
        {
            this._attributeId = this.GetNodeAttribute(node, "AttributeId", true);
            this._category    = this.GetNodeAttribute(node, "Category", false);
            this._issuer      = this.GetNodeAttribute(node, "Issuer", false);
            NodeList children = node.ChildNodes;

            for (int i = 0; i < children.Length; i++)
            {
                Node child = children.Item(i);
                if (child.NodeType == Node.ELEMENT_NODE)
                {
                    this._evaluatable = (IEvaluatable)PolicyElementFactory.GetInstance(child);
                }
            }
            if (this._evaluatable == null)
            {
                throw new Indeterminate(Indeterminate.IndeterminateSyntaxError);
            }
        }
Example #33
0
        public Match(Node node)
        {
            Node matchidnode = node.Attributes.GetNamedItem("MatchId");

            if (matchidnode != null)
            {
                this._matchId = new AnyURIDataType(matchidnode.NodeValue);
            }
            else
            {
                throw new Indeterminate(Indeterminate.IndeterminateSyntaxError);
            }

            this._evaluatable    = null;
            this._attributeValue = null;
            NodeList children = node.ChildNodes;

            for (int i = 0; i < children.Length; i++)
            {
                Node child = children.Item(i);
                if (child.NodeName.Trim().Equals(AttributeValue.stringIdentifer))
                {
                    this._attributeValue = new AttributeValue(child);
                }
                else if (this._evaluatable == null && child.NodeName.Trim().Equals(AttributeDesignator.stringIdentifer))
                {
                    this._evaluatable = new AttributeDesignator(child);
                }
                else if (this._evaluatable == null && child.NodeName.Trim().Equals(AttributeSelector.stringIdentifer))
                {
                    this._evaluatable = new AttributeSelector(child);
                }
            }

            if (this._evaluatable == null || this._attributeValue == null)
            {
                throw new Indeterminate(Indeterminate.IndeterminateSyntaxError);
            }
        }
Example #34
0
        public Condition(Node node)
        {
            this._evaluatable = null;
            NodeList children = node.ChildNodes;

            for (int i = 0; i < children.Length; i++)
            {
                Node child = children.Item(i);
                if (child.NodeType == Node.ELEMENT_NODE)
                {
                    IElement e = PolicyElementFactory.GetInstance(children.Item(i));
                    if (e != null && e is IEvaluatable)
                    {
                        this._evaluatable = (IEvaluatable)e;
                        break;
                    }
                }
            }
            if (this._evaluatable == null)
            {
                throw new Indeterminate(Indeterminate.IndeterminateSyntaxError);
            }
        }
Example #35
0
 public void AddKeybind(String contextName, IEnumerable<Keys> keys, IEvaluatable function, IDictionary<String, String> parameters)
 {
     this.Keybinds.Add(
         Tuple.Create(contextName, keys.ToArray()),
         Tuple.Create(function, parameters)
     );
 }
 public TwoInputGenomeEvaluator(string genome)
 {
     _GenomeAst = new GenomeConverter().Convert(genome);
 }
        double _GetScoreByInferenceOfRules(IEvaluatable genomeEvaluator)
        {
            var score = 0.0;

            {
                score += (.08)*(1 - genomeEvaluator.GetOperableGeneLength()/_MaxGeneLength);
            }

            // Hypoteneuse must be longer than leg a
            {
                var a = 6;
                var b = 9;
                var c = Evaluate(genomeEvaluator, a, b);

                score += c > a ? .16 : 0;
            }

            // Hypoteneuse must be longer than leg b
            {
                var a = 1;
                var b = 20;
                var c = Evaluate(genomeEvaluator, a, b);

                score += c > b ? .16 : 0;
            }

            // Hypoteneuse must be shorter than leg a + leg b
            {
                var a = 3;
                var b = 4;
                var c = Evaluate(genomeEvaluator, a, b);

                score += c < a + b ? .16 : 0;
            }

            // Hypoteneuse is a if b == 0
            {
                var a = 3;
                var b = 0;
                var c = Evaluate(genomeEvaluator, a, b);

                score += c == a ? .16 : 0;
            }

            // Hypoteneuse is b if a == 0
            {
                var a = 0;
                var b = 4;
                var c = Evaluate(genomeEvaluator, a, b);

                score += c == b ? .16 : 0;
            }

            // Hypoteneuse is 0 if a == 0 && b == 0
            {
                var a = 0;
                var b = 0;
                var c = Evaluate(genomeEvaluator, a, b);

                score += c == b ? .16 : 0;
            }

            // Hypoteneuse is a*sqrt(2) if a == b
            {
                var a = 1;
                var b = a;
                var c = Evaluate(genomeEvaluator, a, b);

                score += -Math.Abs(2*a.Squared() - c.Squared());
            }

            if (double.IsInfinity(score))
                score = double.MinValue;
            return score;
        }