Esempio n. 1
0
        //Note assignment 3 (06.09.17):
        //calculate the same hash for the simplified truth table
        //reverse simplification of table by looking at the stars
        //each star indicates 2^* lines need to be added.
        public string CalculateHash(ExpressionModel expressionModel)
        {
            char[] charArray = expressionModel.TruthTable.Binary.ToCharArray();
            Array.Reverse(charArray);
            expressionModel.TruthTable.Binary = new string(charArray);

            int rest = expressionModel.TruthTable.Binary.Length % 4;

            if (rest != 0)
            {
                expressionModel.TruthTable.Binary = new string('0', 4 - rest) + expressionModel.TruthTable.Binary;
            }

            string output = "";

            for (int i = 0; i <= expressionModel.TruthTable.Binary.Length - 4; i += 4)
            {
                output += $"{Convert.ToByte(expressionModel.TruthTable.Binary.Substring(i, 4), 2):X}";
            }
            expressionModel.TruthTable.Hexadecimal = output;
            expressionModel.TruthTable.Binary      = new string(charArray);
            return(output);
        }
Esempio n. 2
0
 public void TestCreateModel()
 {
     ExpressionModel.Create(MixLogicalOperatorKind.And)
     .AddExpression
     (
         ExpressionModel.Create(MixLogicalOperatorKind.And)
         .AddFunction(FunctionModel.Create(MixCompareOperatorKind.Equal, "ho_va_ten", "Tran Nhat Duy"))
         .AddFunction(FunctionModel.Create(MixCompareOperatorKind.Equal, "status", "open"))
     ).AddExpression
     (
         ExpressionModel.Create(MixLogicalOperatorKind.And)
         .AddExpression
         (
             ExpressionModel.Create(MixLogicalOperatorKind.Or)
             .AddFunction(FunctionModel.Create(MixCompareOperatorKind.Equal, "date", "2020/12/10", "2020/12/30"))
             .AddFunction(FunctionModel.Create(MixCompareOperatorKind.Equal, "address", "Nguyen thi Minh Khai"))
         ).AddExpression
         (
             ExpressionModel.Create(MixLogicalOperatorKind.And)
             .AddFunction(FunctionModel.Create(MixCompareOperatorKind.GreaterThan, "age", "18"))
             .AddFunction(FunctionModel.Create(MixCompareOperatorKind.Equal, "gender", "male"))
         )
     );
 }
Esempio n. 3
0
 public BasketRegionModel(
     EditableExpressionModel baseExpression,
     NullableExpressionModel baseActiveExpression,
     RegionBasketModel basket,
     ExpressionModel benchmarkExpression,
     IEnumerable <CountryModel> countries,
     ExpressionModel overlayExpression,
     EditableExpressionModel portfolioAdjustmentExpression,
     NullableExpressionModel portfolioScaledExpression,
     NullableExpressionModel trueActiveExpression,
     NullableExpressionModel trueExposureExpression
     )
 {
     this.Base                = baseExpression;
     this.BaseActive          = baseActiveExpression;
     this.Basket              = basket;
     this.Benchmark           = benchmarkExpression;
     this.Countries           = countries;
     this.Overlay             = overlayExpression;
     this.PortfolioAdjustment = portfolioAdjustmentExpression;
     this.PortfolioScaled     = portfolioScaledExpression;
     this.TrueActive          = trueActiveExpression;
     this.TrueExposure        = trueExposureExpression;
 }
Esempio n. 4
0
 public RegionModel(
     NullableExpressionModel baseExpression,
     NullableExpressionModel baseActiveExpression,
     ExpressionModel benchmarkExpression,
     String name,
     ExpressionModel overlayExpression,
     NullableExpressionModel portfolioAdjustmentExpression,
     NullableExpressionModel portfolioScaledExpression,
     IEnumerable <GlobeResident> residents,
     NullableExpressionModel trueActiveExpression,
     NullableExpressionModel trueExposureExpression
     ) : this()
 {
     this.Base                = baseExpression;
     this.BaseActive          = baseActiveExpression;
     this.Benchmark           = benchmarkExpression;
     this.Name                = name;
     this.Overlay             = overlayExpression;
     this.PortfolioAdjustment = portfolioAdjustmentExpression;
     this.PortfolioScaled     = portfolioScaledExpression;
     this.Residents.AddRange(residents);
     this.TrueActive   = trueActiveExpression;
     this.TrueExposure = trueExposureExpression;
 }
        public Questionnaire GetStoreModel()
        {
            // create store model questionnaire
            var questionnaire = new Questionnaire
            {
                Category      = _questionnairePostViewModel.Category,
                Version       = _questionnairePostViewModel.Version,
                Questions     = new Collection <Question>(),
                QuestionRules = new Collection <QuestionRule>()
            };

            // create stopre model questions and questionrules
            foreach (var viewModelQuestion in _questionnairePostViewModel.Questions)
            {
                var question = new Question
                {
                    QuestionTemplate = new Collection <Template>(),
                    Name             = viewModelQuestion.Key,
                    Type             = viewModelQuestion.Type,
                    Version          = viewModelQuestion.Version
                };

                var questionRule = new QuestionRule
                {
                    ExpressionModel = new Collection <ExpressionModel>(),
                    Name            = viewModelQuestion.Key,
                    HideQuestion    = viewModelQuestion.HideExpression
                };

                if (viewModelQuestion.ExpressionProperties != null)
                {
                    foreach (var(key, value) in viewModelQuestion.ExpressionProperties)
                    {
                        var expressionModel = new ExpressionModel
                        {
                            Key        = key,
                            Expression = value
                        };
                        questionRule.ExpressionModel.Add(expressionModel);
                    }
                }

                var globalTemplate = viewModelQuestion.TemplateOptions;

                foreach (var translation in globalTemplate.Translations)
                {
                    // check if question is required
                    questionRule.Required = globalTemplate.Required;

                    // Add all templateswith different languages to the template
                    var questionTemplate = new Template
                    {
                        Description = translation.Description,
                        InputType   = globalTemplate.Type,
                        Label       = translation.Label,
                        Language    = translation.Language,
                        Placeholder = translation.Placeholder,
                        Validations = new Collection <Validation>()
                    };

                    if (translation.Validation.Messages != null)
                    {
                        foreach (var(key, value) in translation.Validation.Messages)
                        {
                            var expressionModel = new Validation()
                            {
                                Type    = key,
                                Message = value
                            };
                            questionTemplate.Validations.Add(expressionModel);
                        }
                    }

                    if (translation.MultipleChoiceOptions != null)
                    {
                        questionTemplate.SelectAllOption = translation.SelectAllOption;
                        questionTemplate.AllowedToSelectMultipleOptions = globalTemplate.Multiple;
                        questionTemplate.Options = new Collection <MultipleChoiceOption>();

                        foreach (var option in translation.MultipleChoiceOptions)
                        {
                            var multipleChoiceOption = new MultipleChoiceOption
                            {
                                Value = option.Value,
                                Label = option.Label
                            };
                            questionTemplate.Options.Add(multipleChoiceOption);
                        }

                        question.QuestionTemplate.Add(questionTemplate);
                    }
                    else
                    {
                        question.QuestionTemplate.Add(questionTemplate);
                    }
                }

                questionnaire.Questions.Add(question);
                questionnaire.QuestionRules.Add(questionRule);
            }

            return(questionnaire);
        }
 public Task <object> Evaluate([FromBody] ExpressionModel expressionModel)
 {
     return(CSharpScript.EvaluateAsync(expressionModel.Expression));
 }
Esempio n. 7
0
        /// <summary>
        /// execute
        /// </summary>
        /// <param name="actionSetting"></param>
        /// <param name="argument"></param>
        /// <returns></returns>
        public Task <ActionExecuteResult> Execute(string actionSetting, ArgumentProvider argument)
        {
            var setting = JsonConvert.DeserializeObject <SetValueActionSetting>(actionSetting);
            var results = new Dictionary <string, JToken>();

            foreach (var kvp in setting.Set)
            {
                var             target     = argument.Format(kvp.Key, true);
                ExpressionModel expression = new ExpressionModel(string.Empty, target);
                var             currentKey = expression.CurrentKey;
                if (expression.IsArray)
                {
                    currentKey = expression.ArrayKey;
                }
                var obj = argument.Get(currentKey, true);
                if (obj != null && !(JsonHelper.IsObject(obj) || JsonHelper.IsArray(obj)))
                {
                    obj = null;
                }
                if (obj == null)
                {
                    string targetValue = argument.Format(kvp.Value, true);
                    if (setting.AsString)
                    {
                        results.Add(target, targetValue);
                    }
                    else
                    {
                        var valueObj = JsonHelper.TryGetObject(targetValue, kvp.Value);
                        var valueArr = JsonHelper.TryGetArray(targetValue, kvp.Value);
                        if (valueObj != null)
                        {
                            targetValue = JsonConvert.SerializeObject(valueObj);
                            results.Add(target, valueObj);
                        }
                        else if (valueArr != null)
                        {
                            targetValue = JsonConvert.SerializeObject(valueArr);
                            results.Add(target, valueArr);
                        }
                        else
                        {
                            results.Add(target, targetValue);
                        }
                    }
                    argument.PutPrivate(target, targetValue);
                }
                else
                {
                    JToken token = null;
                    JToken res   = null;
                    if (expression.IsArray)
                    {
                        JArray arr = JsonHelper.GetArray(obj, currentKey);
                        res = JsonHelper.FindToken(arr[expression.Index], expression.SubExpression.Key, currentKey);
                        if (res == null)
                        {
                            arr = FillArrayToCount(arr, expression.Index ?? 0);
                            if (arr[expression.Index] == null)
                            {
                                arr[expression.Index] = CreateObject(new JObject(), expression.SubExpression);
                                res = JsonHelper.FindToken(arr[expression.Index], expression.SubExpression.Key, currentKey);
                            }
                        }
                        token = arr;
                    }
                    else
                    {
                        JObject o = JsonHelper.GetObject(obj, currentKey);
                        res = JsonHelper.FindToken(o, expression.SubExpression.Key, currentKey);
                        if (res == null)
                        {
                            o   = CreateObject(o, expression.SubExpression);
                            res = JsonHelper.FindToken(o, expression.SubExpression.Key, currentKey);
                        }
                        token = o;
                    }

                    if (res?.Parent != null)
                    {
                        var prop     = (JProperty)res.Parent;
                        var newValue = argument.Format(kvp.Value, true);
                        if (setting.AsString)
                        {
                            prop.Value = newValue;
                        }
                        else if (JsonHelper.IsArray(newValue))
                        {
                            JArray newArr = JsonHelper.GetArray(newValue, kvp.Value);
                            prop.Value = newArr;
                        }
                        else if (JsonHelper.IsObject(newValue))
                        {
                            JObject newObj = JsonHelper.GetObject(newValue, kvp.Value);
                            prop.Value = newObj;
                        }
                        else
                        {
                            prop.Value = newValue;
                        }
                    }
                    argument.PutPrivate(currentKey, JsonConvert.SerializeObject(token));
                    results.Add(currentKey, token);
                }
            }

            return(Task.FromResult(new ActionExecuteResult
            {
                Success = true,
                Data = JsonConvert.SerializeObject(results)
            }));
        }
Esempio n. 8
0
        public string GetDisjunctiveNormalForm(ExpressionModel expressionModel)
        {
            //is contradiction
            if (expressionModel.TruthTable.Hexadecimal.Equals("0"))
            {
                expressionModel.DisjunctiveNormalForm = expressionModel.Prefix;
                return(expressionModel.Prefix);
            }
            //is tautology but only with one variable
            if (expressionModel.DistinctVariables.Count == 1 &&
                expressionModel.TruthTable.Binary.Distinct().Count() == 1 &&
                expressionModel.TruthTable.Binary.Contains('1'))
            {
                expressionModel.DisjunctiveNormalForm = expressionModel.Prefix;
                return(expressionModel.Prefix);
            }
            //PART 1 Extract all formulas out truth table

            //makes sure that prefix AND for any row has proper syntax.
            //aka. if you have variables ABC then one row is |(&(&(A,B),C)) with OR
            int counter;
            var disjunctiveNormalForm = string.Empty;
            var formulas = new List <string>();
            //loop distinct variables
            //on each index check value.
            var tableRowsWithoutTabs = new List <string>();

            foreach (var truthTableRow in expressionModel.TruthTable.Rows)
            {
                tableRowsWithoutTabs.Add(Regex.Replace(truthTableRow, @"\t", ""));
            }

            for (var i = 1; i < tableRowsWithoutTabs.Count; i++)
            {
                var truthTableRow = tableRowsWithoutTabs[i];
                var formula       = string.Empty;
                //makes sure that prefix AND for any row has proper syntax.
                //aka. if you have variables ABC then one row is |(&(&(A,B),C)) with OR
                //~ if variablecount > 2 need to additional AND
                counter = 0;

                var answer = truthTableRow[truthTableRow.Length - 1];
                if (answer.Equals('0'))
                {
                    continue;
                }

                for (var index = 0; index < expressionModel.DistinctVariables.Count; index++)
                {
                    var variable = expressionModel.DistinctVariables[index];
                    var value    = truthTableRow[index];


                    if (formula == string.Empty)
                    {
                        formula = $"&(";
                    }

                    formula = AddVariableToFormula(counter, value, formula, variable);
                    counter++;

                    if (index == expressionModel.DistinctVariables.Count - 1)
                    {
                        formulas.Add(formula);
                    }
                }
            }


            //PART 2 Add OR operator to all formulas and create disjunctive normal form
            counter = 0;
            foreach (var formula in formulas)
            {
                if (counter == 0)
                {
                    disjunctiveNormalForm = $"|({formula}";
                }
                else if (counter == 1)
                {
                    disjunctiveNormalForm += $"), {formula}";
                }
                //else if (counter == formulas.Count - 1)
                //{
                //    disjunctiveNormalForm += $"), {formula})";
                //}
                else
                {
                    disjunctiveNormalForm  = disjunctiveNormalForm.Insert(0, "|(");
                    disjunctiveNormalForm += $"),{formula}";
                }
                counter++;
            }
            disjunctiveNormalForm += ")";

            expressionModel.DisjunctiveNormalForm = disjunctiveNormalForm;
            return(disjunctiveNormalForm);
        }
Esempio n. 9
0
        private bool AreImplicantsMinimizable(ExpressionModel expressionModel, List <ImplicantModel> implicants, int nrOfGroups)
        {
            List <int> replacableIndicesCounter = new List <int>();

            for (int i = 0; i < nrOfGroups; i++)
            {
                if (i < nrOfGroups - 1)
                {
                    var currentGroupsImplicants = implicants.Where(x => x.Group == i).ToList();
                    if (!currentGroupsImplicants.Any())
                    {
                        continue;
                    }

                    //find the next greater key in implicants.
                    //binary search returns index (i+1) if found. if not it finds next greatest as negative complement.
                    //if nothing is found count is returned
                    List <int> possibleNextGroups =
                        (from implicant in implicants select implicant.Group).Distinct().ToList();
                    possibleNextGroups.Sort();
                    var index = possibleNextGroups.BinarySearch(i + 1);
                    index = Math.Abs(index);
                    if (index == possibleNextGroups.Count) //see binarySearch docu
                    {
                        continue;
                    }
                    //if i get the error here then i somehow need to keep the old group
                    var groupNumber          = possibleNextGroups[index];
                    var nextGroupsImplicants = implicants.Where(x => x.Group == groupNumber).ToList();

                    foreach (var currentGroupImplicant in currentGroupsImplicants)
                    {
                        List <int> indicesToBeReplacedByAsterix = new List <int>();

                        foreach (var nextGroupImplicant in nextGroupsImplicants)
                        {
                            indicesToBeReplacedByAsterix.Clear();
                            //for every in the current group need to check every item in next group
                            //it needs to be check whether exactly one difference exists in row,
                            //e.g. current: 00; next 01. then new implicant 0*
                            //however only index can be change at a given time
                            for (int j = 0; j < expressionModel.DistinctVariables.Count; j++)
                            {
                                if (currentGroupImplicant.Implicant[j] == '1' &&
                                    nextGroupImplicant.Implicant[j] == '0' ||
                                    currentGroupImplicant.Implicant[j] == '0' &&
                                    nextGroupImplicant.Implicant[j] == '1')
                                {
                                    indicesToBeReplacedByAsterix.Add(j);
                                }
                            }
                            replacableIndicesCounter.Add(indicesToBeReplacedByAsterix.Count);
                        }
                    }
                }
            }

            if (!replacableIndicesCounter.Any())
            {
                return(false);
            }
            else if (replacableIndicesCounter.Any(x => x == 1))
            {
                return(true);
            }
            return(false);
        }
Esempio n. 10
0
        private List <string> MinimizeImplicants(List <ImplicantModel> implicants, int nrOfGroups, ExpressionModel expressionModel)
        {
            Debug.WriteLine($"iteration: {nrOfRecursions++}");

            List <ImplicantModel> nextOrderImplicants = new List <ImplicantModel>();

            for (int i = 0; i < nrOfGroups; i++)
            {
                //check if not last group
                if (i < nrOfGroups - 1)
                {
                    var currentGroupsImplicants = implicants.Where(x => x.Group == i).ToList();
                    if (!currentGroupsImplicants.Any())
                    {
                        continue;
                    }

                    //find the next greater key in implicants.
                    //binary search returns index (i+1) if found. if not it finds next greatest as negative complement.
                    //if nothing is found count is returned
                    List <int> possibleNextGroups =
                        (from implicant in implicants select implicant.Group).Distinct().ToList();
                    possibleNextGroups.Sort();
                    var index = possibleNextGroups.BinarySearch(i + 1);
                    index = Math.Abs(index);
                    if (index >= possibleNextGroups.Count) //see binarySearch docu
                    {
                        continue;
                    }
                    //if i get the error here then i somehow need to keep the old group
                    var groupNumber          = possibleNextGroups[index];
                    var nextGroupsImplicants = implicants.Where(x => x.Group == groupNumber).ToList();

                    foreach (var currentGroupImplicant in currentGroupsImplicants)
                    {
                        List <int> indicesToBeReplacedByAsterix = new List <int>();

                        foreach (var nextGroupImplicant in nextGroupsImplicants)
                        {
                            indicesToBeReplacedByAsterix.Clear();
                            //for every in the current group need to check every item in next group
                            //it needs to be check whether exactly one difference exists in row,
                            //e.g. current: 00; next 01. then new implicant 0*
                            //however only index can be change at a given time
                            for (int j = 0; j < expressionModel.DistinctVariables.Count; j++)
                            {
                                if (currentGroupImplicant.Implicant[j] == '1' &&
                                    nextGroupImplicant.Implicant[j] == '0' ||
                                    currentGroupImplicant.Implicant[j] == '0' &&
                                    nextGroupImplicant.Implicant[j] == '1')
                                {
                                    indicesToBeReplacedByAsterix.Add(j);
                                }
                            }

                            string newImplicantCurrentGroup = currentGroupImplicant.Implicant;
                            string newImplicantNextGroup    = nextGroupImplicant.Implicant;
                            //add also from next group
                            if (indicesToBeReplacedByAsterix.Count == 1)
                            {
                                //replace values with * and add to new implicants
                                //for current and next group implicant
                                var k = indicesToBeReplacedByAsterix.FirstOrDefault();

                                //currentgroup
                                StringBuilder sb1 = new StringBuilder(newImplicantCurrentGroup)
                                {
                                    [k] = '*'
                                };
                                newImplicantCurrentGroup = sb1.ToString();
                                //var newGroupNumber1 = newImplicantCurrentGroup.Count(x => x.Equals('1'));
                                if (nextOrderImplicants.All(x => x.Implicant != newImplicantCurrentGroup))
                                {
                                    nextOrderImplicants.Add(new ImplicantModel(currentGroupImplicant.OriginalNrOfOnes,
                                                                               newImplicantCurrentGroup, currentGroupImplicant.OriginalNrOfOnes));
                                }
                                //nextgroup
                                StringBuilder sb2 = new StringBuilder(newImplicantNextGroup)
                                {
                                    [k] = '*'
                                };
                                newImplicantNextGroup = sb2.ToString();
                                var newGroupNumber2 = newImplicantNextGroup.Count(x => x.Equals('1'));
                                //if (!newImplicantNextGroup.Equals(newImplicantCurrentGroup))
                                if (nextOrderImplicants.All(x => x.Implicant != newImplicantNextGroup))
                                {
                                    nextOrderImplicants.Add(new ImplicantModel(nextGroupImplicant.OriginalNrOfOnes, newImplicantNextGroup, nextGroupImplicant.OriginalNrOfOnes));
                                }
                            }
                        }
                    }
                }
                //we compare to the last group but we also need to keep them for next order
                //else
                //{
                //    var lastGroupsImplicants = implicants.Where(x => x.Group == i).ToList();
                //    if (!lastGroupsImplicants.Any())
                //    {
                //        continue;
                //    }
                //    nextOrderImplicants.AddRange(lastGroupsImplicants);
                //}
            }

            //if for one nextOrderImplicants row length - 1 = number of *
            //then simplification is complete
            //thats however not always true. lets distinctVariables plus 2 and * exist then i end recursion
            //

            //if nextorderimplicants == 0 then check if there are stars in old order implicants
            //if they contain stars return them in combination with old truth table
            //if (nextOrderImplicants.Count == 0)
            //{

            //when continuationFlag is true then the table can be simplified further
            //if for one nextOrderImplicants row length - 1 = number of *
            //then simplification is complete
            bool continuationFlag = false;

            if (nextOrderImplicants.Count > 0)
            {
                foreach (var nextOrderImplicant in nextOrderImplicants)
                {
                    if (continuationFlag)
                    {
                        break;
                    }

                    int dontCareCounter = 0;
                    foreach (var c in nextOrderImplicant.Implicant)
                    {
                        if (c.Equals('*'))
                        {
                            dontCareCounter++;
                        }
                    }

                    var newNrOfGroups = nextOrderImplicants.Max(x => x.Group) + 1;
                    if (AreImplicantsMinimizable(expressionModel, nextOrderImplicants, newNrOfGroups))
                    {
                        //break;
                        continuationFlag = true;
                    }
                    //if (nextOrderImplicant.Implicant.Length - 1 != dontCareCounter)
                    //{
                    //    continuationFlag = true;
                    //}
                }

                if (continuationFlag)
                {
                    var newNrOfGroups = nextOrderImplicants.Max(x => x.Group) + 1; //see n+1 groups
                    MinimizeImplicants(nextOrderImplicants, newNrOfGroups, expressionModel);
                }
                else
                {
                    _simplifiedTruthTable = CreateSimplifiedTruthTable(expressionModel, nextOrderImplicants);
                }
            }

            return(_simplifiedTruthTable);
        }
Esempio n. 11
0
        /// <summary>
        /// rule_conditions :
        ///       key LEFT_PAREN arguments? RIGHT_PAREN
        ///     | NOT rule_conditions
        ///     | rule_conditions AND rule_conditions
        ///     | rule_conditions OR rule_conditions
        ///     | LEFT_PAREN rule_conditions RIGHT_PAREN
        ///     ;
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override object VisitRule_conditions([NotNull] WorkflowParser.Rule_conditionsContext context)
        {
            ExpressionModel result = null;
            var             key    = context.key();

            if (key != null)
            {
                var k  = (string)VisitKey(key);
                var r1 = new RuleExpressionModel()
                {
                    Key       = k,
                    Reference = ResolveRule(k),
                };

                var args = context.arguments();
                if (args != null)
                {
                    var arguments = (List <(string, string)>)VisitArguments(args);
                    foreach (var argument in arguments)
                    {
                        r1.Arguments.Add(argument.Item1, argument.Item2);
                    }
                }

                result = r1;
            }

            else if (context.NOT() != null)
            {
                result = new NotExpressionModel()
                {
                    Expression = (ExpressionModel)VisitRule_conditions(context.rule_conditions()[0])
                }
            }
            ;

            else if (context.AND() != null)
            {
                result = new BinaryExpressionModel()
                {
                    Left     = (ExpressionModel)VisitRule_conditions(context.rule_conditions()[0]),
                    Operator = "AND",
                    Right    = (ExpressionModel)VisitRule_conditions(context.rule_conditions()[1])
                }
            }
            ;

            else if (context.OR() != null)
            {
                result = new BinaryExpressionModel()
                {
                    Left     = (ExpressionModel)VisitRule_conditions(context.rule_conditions()[0]),
                    Operator = "OR",
                    Right    = (ExpressionModel)VisitRule_conditions(context.rule_conditions()[1])
                }
            }
            ;

            else if (context.LEFT_PAREN() != null && context.RIGHT_PAREN() != null)
            {
                result = (ExpressionModel)VisitRule_conditions(context.rule_conditions()[0]);
            }

            return(result);
        }