Example #1
0
        public static VariableContextExpression diff(VariableContextExpression expression, string variableName)
        {
            VariableContext c    = expression.VariableContext;
            Expression      diff = new Differ(expression.Expression, variableName).Calculate(c);

            TypeCheckingContext context = new MathyLanguageService().CreateTypeCheckingContext(c);

            foreach (VariableInfo variable in expression.Variables)
            {
                c.Set(variable.Name, context.CreateAutoCreatedVariableValue(variable.Type));
            }

            VariableContextExpression result = new VariableContextExpression(diff, expression.Variables, 0, 0)
            {
                VariableContext = expression.VariableContext
            };

            new MathyLanguageService().CreateTypeChecker().PerformTypeChecking(result, context);

            result = new VariableContextExpression(new Cherimoya.Reduction.ExpressionReductor(new MathyLanguageService()).Reduce(diff), expression.Variables, 0, 0)
            {
                VariableContext = expression.VariableContext
            };
            new MathyLanguageService().CreateTypeChecker().PerformTypeChecking(result, context);

            foreach (VariableInfo variable in expression.Variables)
            {
                context.VariableContext.Remove(variable.Name);
            }


            return(result);
        }
Example #2
0
        public static Matrix map(Matrix m, LambdaExpression mapper, VariableContext vc)
        {
            ExpressionEvaluator evaluator = new MathyLanguageService().CreateEvaluator();

            List <List <double> > result = new List <List <double> >();

            double[] row = new double[m.ColumnCount];

            for (int i = 0; i <= m.RowCount - 1; i++)
            {
                for (int j = 0; j <= m.ColumnCount - 1; j++)
                {
                    row[j] = m[i, j];
                }

                vc.Set(mapper.VariableNames[0], row.Where(c => !double.IsNaN(c)).ToArray());

                if (mapper.VariableNames.Length > 1)
                {
                    vc.Set(mapper.VariableNames[1], i);
                }

                double[] mappedRow;
                var      obj = evaluator.Evaluate(mapper.Body, vc);
                try
                {
                    mappedRow = (double[])obj;
                }
                catch (Exception ex)
                {
                    var a = (object[])obj;
                    mappedRow = (double[])a[0];
                }


                result.Add(new List <double>());

                for (int j = 0; j <= mappedRow.Length - 1; j++)
                {
                    result[i].Add(mappedRow[j]);
                }
            }

            vc.Remove(mapper.VariableNames[0]);


            List <double> cells = new List <double>();

            foreach (List <double> resultRow in result)
            {
                foreach (double cell in resultRow)
                {
                    cells.Add(cell);
                }
            }

            return(new Matrix(m.RowCount, result[0].Count, cells.ToArray()));
        }
Example #3
0
        private VariableContext CreateVariebleContext()
        {
            VariableContext vc = MathyLanguageService.CreateVariableContext();

            foreach (SourceVariable variable in plan.Variables)
            {
                vc.Set(variable.Name, DataFuncs.CreateDefaultValue(variable.Type));
            }


            return(vc);
        }
Example #4
0
        public static VariableContext CreateVariableContext(Dictionary <string, object> variables)
        {
            VariableContext c = MathyLanguageService.CreateVariableContext();

            foreach (string variableName in variables.Keys)
            {
                c.Set(variableName, variables[variableName]);
            }


            return(c);
        }
Example #5
0
        private static object[] map(object[] items, LambdaExpression mapper, VariableContext vc)
        {
            ExpressionEvaluator evaluator = new MathyLanguageService().CreateEvaluator();

            object[] result = new object[items.Length];

            for (int i = 0; i <= items.Length - 1; i++)
            {
                vc.Set(mapper.VariableNames[0], items[i]);
                result[i] = evaluator.Evaluate(mapper.Body, vc);
            }

            vc.Remove(mapper.VariableNames[0]);
            return(result);
        }
Example #6
0
        public static object eval(Expression expression, Dictionary <string, object> variables, VariableContext vc)
        {
            foreach (string variableName in variables.Keys)
            {
                vc.Set(variableName, variables[variableName]);
            }

            object result = new MathyLanguageService().CreateEvaluator().Evaluate(expression is VariableContextExpression ? (expression as VariableContextExpression).Expression : expression, vc);

            foreach (string variableName in variables.Keys)
            {
                vc.Remove(variableName);
            }


            return(result);
        }
Example #7
0
        private VariableContext CreateVariableContext()
        {
            VariableContext vc = MathyLanguageService.CreateVariableContext();

            foreach (Step step in Steps)
            {
                for (int i = 0; i <= step.InSourceVariables.Length - 1; i++)
                {
                    object value = step.InValues[i];

                    if (value != null)
                    {
                        if (value is double)
                        {
                            value = Math.Round((double)value, Settings.DecimalDigitCount);
                        }
                        else if (value is double[])
                        {
                            value = (value as double[]).Where(j => !double.IsNaN(j)).Select(j => Math.Round(j, Settings.DecimalDigitCount)).ToArray();
                        }
                        else if (value is int[])
                        {
                            value = (value as int[]).Select(j => Math.Round((double)j, Settings.DecimalDigitCount)).ToArray();
                        }
                        else if (value is Vector)
                        {
                            Vector v = (value as Vector).Clone();
                            v.SetDecimalDigitCount(Settings.DecimalDigitCount);
                            value = v;
                        }
                        else if (value is Matrix)
                        {
                            Matrix m = (value as Matrix).Clone();
                            m.SetDecimalDigitCount(Settings.DecimalDigitCount);
                            value = m;
                        }
                        vc.Set(step.InSourceVariables[i].Name, value);
                    }
                }
            }

            vc.Set("_EvaluationContext", this);
            return(vc);
        }
Example #8
0
        public bool EvaluateConditions(VariableContext vc)
        {
            List <bool> conditions = new List <bool>();

            int index = 0;

            foreach (Expression expression in Conditions)
            {
                object result = new MathyLanguageService().CreateEvaluator().Evaluate(expression, vc);
                if (!(result is bool))
                {
                    throw new Exception(string.Format("Condition {0} does not evaluate to boolean.", index));
                }
                else
                {
                    conditions.Add((bool)result);
                }
                index++;
            }


            return(conditions.All(i => i));
        }
Example #9
0
        public EvaluationContext Analyze()
        {
            VariableContext vc = CreateVariebleContext();


            MathyLanguageService service = new MathyLanguageService();

            List <Step> steps = new List <Step>();

            List <string> existingInVariables = new List <string>();


            int index = 0;

            foreach (SourceExpression expression in plan.Expressions)
            {
                Step step = new Step();
                step.SourceExpression = expression;

                try
                {
                    step.Expressions = service.Compile(expression.Expression, vc);
                }
                catch (CompileException ex)
                {
                    throw new Exception(string.Format("步骤{0}表达式编译错误:\r\n{1}", index + 1, ex.Message));
                }

                if (string.IsNullOrEmpty(expression.Condition))
                {
                    step.Conditions = new Expression[] { };
                }
                else
                {
                    try
                    {
                        step.Conditions = service.Compile(expression.Condition, vc);
                    }
                    catch (CompileException ex)
                    {
                        throw new Exception(string.Format("步骤{0}条件编译错误:\r\n{1}", index + 1, ex.Message));
                    }
                }

                Bitmap expressionImage = new NodeVisualizer(
                    step.Expressions
                    .Select(i => new NodeConverter().Convert(i))
                    .ToArray()).VisulizeAsBitmap();

                Bitmap conditionImage = step.Conditions.Length == 0 ? null :
                                        new NodeVisualizer(
                    step.Conditions
                    .Select(i => new NodeConverter().Convert(i))
                    .ToArray()).VisulizeAsBitmap();

                step.Image        = StackImages(expressionImage, conditionImage);
                step.ImageData    = Funcs.ImageToBytes(step.Image);
                step.OutVariables = CollectOutVariables(step.Expressions).ToArray();


                string[] inVariables = CollectVariables(step.Expressions)
                                       .Where(i => !step.OutVariables.Contains(i))
                                       .ToArray();

                string[] conditionVariables = CollectVariables(step.Conditions);

                step.InSourceVariables  = plan.Variables.Where(i => inVariables.Contains(i.Name) && !existingInVariables.Contains(i.Name)).ToArray();
                step.InValues           = new object[step.InSourceVariables.Length];
                step.DependentVariables = plan.Variables.Where(i => inVariables.Contains(i.Name)).ToArray();
                step.DependentValues    = new object[step.DependentVariables.Length];
                step.InTempVariables    = inVariables.Where(i => plan.Variables.All(j => j.Name != i)).ToArray();
                step.ConditionVariables = conditionVariables;

                existingInVariables.AddRange(step.InSourceVariables.Select(i => i.Name));

                steps.Add(step);


                index++;
            }

            foreach (Step step in steps)
            {
                List <Step> froms = new List <Step>();
                foreach (string tempVariable in step.InTempVariables)
                {
                    froms.AddRange(steps.Where(i => i.OutVariables.Contains(tempVariable)));
                }

                foreach (string tempVariable in step.ConditionVariables)
                {
                    froms.AddRange(steps.Where(i => i.OutVariables.Contains(tempVariable)));
                }


                step.Froms = froms.Where(i => i != null).Distinct().ToArray();
            }


            EvaluationContext context = new EvaluationContext(plan, steps.ToArray());

            foreach (SourceVariable variable in plan.Variables)
            {
                context.SetValue(variable.Name, null);
            }


            return(context);
        }
Example #10
0
        public static VariableContextExpression ucomb(VariableContextExpression func, Matrix r, Vector u)
        {
            int count = func.Variables.Length;

            VariableContextExpression[] diffs = func.Variables.Select(i => ExpressionFuncs.diff(func, i.Name)).ToArray();


            Expression e1 = null;

            for (int i = 0; i <= count - 1; i++)
            {
                Expression right = BinaryExpression.Create(BinaryOperator.Multiply,
                                                           ConstantExpression.create(u[i] * u[i], 0, 0),
                                                           new FunctionCallExpression("pow",
                                                                                      new Expression[]
                {
                    diffs[i].Expression,
                    ConstantExpression.create(2, 0, 0)
                },
                                                                                      0,
                                                                                      0));

                e1 = e1 == null ? right : BinaryExpression.Create(BinaryOperator.Add, e1, right);
            }


            Expression e2 = null;

            for (int i = 1; i <= count - 1; i++)
            {
                for (int j = i + 1; j <= count; j++)
                {
                    Expression right = BinaryExpression.Create(BinaryOperator.Multiply,
                                                               ConstantExpression.create(u[i - 1] * u[j - 1] * r[i - 1, j - 1], 0, 0),
                                                               BinaryExpression.Create(BinaryOperator.Multiply,
                                                                                       diffs[i - 1].Expression,
                                                                                       diffs[j - 1].Expression));

                    e2 = e2 == null ? right : BinaryExpression.Create(BinaryOperator.Add, e2, right);
                }
            }

            e2 = BinaryExpression.Create(BinaryOperator.Multiply,
                                         ConstantExpression.create(2, 0, 0),
                                         e2);


            Expression e = BinaryExpression.Create(BinaryOperator.Add,
                                                   e1,
                                                   e2);


            VariableContext     c       = func.VariableContext;
            TypeCheckingContext context = new MathyLanguageService().CreateTypeCheckingContext(c);

            foreach (VariableInfo variable in func.Variables)
            {
                c.Set(variable.Name, context.CreateAutoCreatedVariableValue(variable.Type));
            }

            VariableContextExpression result = new VariableContextExpression(e, func.Variables, 0, 0)
            {
                VariableContext = func.VariableContext
            };

            new MathyLanguageService().CreateTypeChecker().PerformTypeChecking(result, context);

            result = new VariableContextExpression(new Cherimoya.Reduction.ExpressionReductor(new MathyLanguageService()).Reduce(e), func.Variables, 0, 0)
            {
                VariableContext = func.VariableContext
            };
            new MathyLanguageService().CreateTypeChecker().PerformTypeChecking(result, context);

            foreach (VariableInfo variable in func.Variables)
            {
                context.VariableContext.Remove(variable.Name);
            }


            return(result);
        }
Example #11
0
        private static RenderBranch Create(double x, double y, int angle, TreeBranch branch, VariableContext variables, Graphics g, Font font)
        {
            double x2 = x - branch.Position * Math.Cos(angle * Math.PI / 180);
            double y2 = y + branch.Position * Math.Sin(angle * Math.PI / 180);

            double x1 = x2 + branch.Length * Math.Cos((angle + branch.Angle) * Math.PI / 180);
            double y1 = y2 - branch.Length * Math.Sin((angle + branch.Angle) * Math.PI / 180);

            double a = Funcs.Atan(x1, y1, x2, y2);

            x2 = x1 + (branch.Length - 2) * Math.Cos(a);
            y2 = y1 - (branch.Length - 2) * Math.Sin(a);

            RenderBranch[] branches = branch.Branches.Select(i => Create(x2, y2, angle + branch.Angle - 180, i, variables, g, font)).ToArray();


            string description;

            double imageX          = 0;
            double imageY          = 0;
            Bitmap expressionImage = null;

            if (branch is ExpressionBranch)
            {
                string[] preVariables = variables.GetAllVariables();

                Expression[] expressions = new MathyLanguageService().Compile((branch as ExpressionBranch).Expression, variables);
                foreach (Expression expression in expressions)
                {
                    new MathyLanguageService().CreateEvaluator().Evaluate(expression, variables);
                }


                StringBuilder b = new StringBuilder();

                foreach (string variableName in variables.GetAllVariables().Where(i => !preVariables.Contains(i)))
                {
                    b.AppendFormat("{0}={1}", variableName, variables.GetValue(variableName));
                }


                description = branch.Description + "\r\n" + b.ToString();


                double xt = x2 + (branch as ExpressionBranch).ImageX * Math.Cos(a + Math.PI);
                double yt = y2 - (branch as ExpressionBranch).ImageX * Math.Sin(a + Math.PI);

                double d = (branch as ExpressionBranch).ImageY;

                imageX = xt + d * Math.Cos(a + Math.PI / 2);
                imageY = yt - d * Math.Sin(a + Math.PI / 2);

                expressionImage = new NodeVisualizer(expressions.Select(i => new NodeConverter().Convert(i)).ToArray()).VisulizeAsBitmap();
            }
            else
            {
                string variableName = (branch as VariableBranch).VariableName;
                object value        = variables.GetValue(variableName);
                description = string.Format("{0}\r\n{1}={2}", branch.Description, variableName, value);
            }


            double dx;
            double dy;

            EvaluateDescriptionPosition(branch, description, x1, y1, x2, y2, g, font, out dx, out dy);


            return(new RenderBranch()
            {
                X1 = x1,
                Y1 = y1,
                X2 = x2,
                Y2 = y2,
                IsVariable = branch is VariableBranch,
                ImageX = imageX,
                ImageY = imageY,
                Image = expressionImage,
                Branches = branches,
                DescriptionX = dx,
                DescriptionY = dy,
                Description = description
            });
        }