示例#1
0
        public override void Evaluate()
        {
            var       target = new Expression.Expression(RegexMatch.Groups[2].Value, ParentContext).GetValue();
            var       name   = new Term(RegexMatch.Groups[3].Value);
            var       type   = new Term(RegexMatch.Groups[1].Value);
            ListValue list;

            if (target is VesselTarget)
            {
                list = Vessel.PartList(type.Text);
            }
            else
            {
                var targetVessel = VesselUtils.GetVesselByName(target.ToString());
                if (targetVessel != null)
                {
                    if (targetVessel.loaded)
                    {
                        list = targetVessel.PartList(type.Text);
                    }
                    else
                    {
                        throw new KOSException("Vessel: " + target + " Is Unloaded, Cannot continue.");
                    }
                }
                else
                {
                    throw new KOSException("Could not get list: " + type.Text + " for Vessel: " + target);
                }
            }

            FindOrCreateVariable(name.Text).Value = list;
            State = ExecutionState.DONE;
        }
示例#2
0
        public override void Evaluate()
        {
            // Todo: let the user specify a volume "LOG something TO file ON volume"
            var targetVolume = SelectedVolume;

            // If the archive is out of reach, the signal is lost in space.
            if (!targetVolume.CheckRange())
            {
                State = ExecutionState.DONE;
                return;
            }

            var targetFile = RegexMatch.Groups[2].Value.Trim();
            var e = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);

            if (e.IsNull())
            {
                State = ExecutionState.DONE;
            }
            else
            {
                targetVolume.AppendToFile(targetFile, e.ToString());
                State = ExecutionState.DONE;
            }
        }
示例#3
0
文件: CommandSet.cs 项目: vosechu/KOS
        public override void Evaluate()
        {
            var targetTerm = new Term(RegexMatch.Groups[1].Value);
            var e          = new Expression.Expression(RegexMatch.Groups[2].Value, ParentContext);

            if (targetTerm.Type == Term.TermTypes.STRUCTURE)
            {
                var baseObj = new Expression.Expression(targetTerm.SubTerms[0], ParentContext).GetValue();

                var obj = baseObj as ISuffixed;
                if (obj != null)
                {
                    if (obj.SetSuffix(targetTerm.SubTerms[1].Text.ToUpper(), e.GetValue()))
                    {
                        State = ExecutionState.DONE;
                        return;
                    }
                    throw new KOSException(
                              "Suffix '" + targetTerm.SubTerms[1].Text + "' doesn't exist or is read only", this);
                }
                throw new KOSException(
                          "Can't set subvalues on a " + Expression.Expression.GetFriendlyNameOfItem(baseObj), this);
            }
            var v = FindOrCreateVariable(targetTerm.Text);

            if (v == null)
            {
                return;
            }
            v.Value = e.GetValue();
            State   = ExecutionState.DONE;
        }
示例#4
0
        public override void Evaluate()
        {
            var target = new Expression.Expression(RegexMatch.Groups[2].Value, ParentContext).GetValue();
            var name = new Term(RegexMatch.Groups[3].Value);
            var type = new Term(RegexMatch.Groups[1].Value);
            ListValue list;

            if (target is VesselTarget)
            {
                list = Vessel.PartList(type.Text);
            }
            else
            {
                var targetVessel = VesselUtils.GetVesselByName(target.ToString());
                if (targetVessel != null)
                {
                    if (targetVessel.loaded)
                    {
                        list = targetVessel.PartList(type.Text);
                    }
                    else
                    {
                        throw new KOSException("Vessel: " + target + " Is Unloaded, Cannot continue.");
                    }
                }
                else
                {
                    throw new KOSException("Could not get list: " + type.Text + " for Vessel: " + target);
                }
            }

            FindOrCreateVariable(name.Text).Value = list;
            State = ExecutionState.DONE;
        }
示例#5
0
 public override Statement Simplify()
 {
     Start = Start.Simplify();
     End   = End.Simplify();
     Step  = Step.Simplify();
     return(base.Simplify());
 }
        private static bool HasDerivative(Expression.Expression node)
        {
            switch (node.Type)
            {
            case ExpressionType.Negation:
                return(HasDerivative((Negation)node));

            case ExpressionType.Addition:
                return(HasDerivative((InfixExpression)node));

            case ExpressionType.Subtraction:
                return(HasDerivative((InfixExpression)node));

            case ExpressionType.Division:
                return(HasDerivative((InfixExpression)node));

            case ExpressionType.Multiplication:
                return(HasDerivative((InfixExpression)node));

            case ExpressionType.Float:
                return(false);

            case ExpressionType.Variable:
                return(HasDerivative((Expression.Variable)node));

            case ExpressionType.Function:
                return(HasDerivative((Function)node));

            case ExpressionType.Power:
                return(HasDerivative((InfixExpression)node));
            }
            throw new Exception("hasDerivative function exception");
        }
示例#7
0
文件: Command.cs 项目: vosechu/KOS
 public override void Lock(string name, Expression.Expression expression)
 {
     if (ParentContext != null)
     {
         ParentContext.Lock(name, expression);
     }
 }
示例#8
0
 public override Statement Simplify()
 {
     Start = Start.Simplify();
     End = End.Simplify();
     Step = Step.Simplify();
     return base.Simplify();
 }
示例#9
0
文件: CommandLog.cs 项目: vosechu/KOS
        public override void Evaluate()
        {
            // Todo: let the user specify a volume "LOG something TO file ON volume"
            var targetVolume = SelectedVolume;

            // If the archive is out of reach, the signal is lost in space.
            if (!targetVolume.CheckRange())
            {
                State = ExecutionState.DONE;
                return;
            }

            var targetFile = RegexMatch.Groups[2].Value.Trim();
            var e          = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);

            if (e.IsNull())
            {
                State = ExecutionState.DONE;
            }
            else
            {
                targetVolume.AppendToFile(targetFile, e.ToString());
                State = ExecutionState.DONE;
            }
        }
示例#10
0
        public override void Evaluate()
        {
            var targetTerm = new Term(RegexMatch.Groups[1].Value);
            var e = new Expression.Expression(RegexMatch.Groups[2].Value, ParentContext);

            if (targetTerm.Type == Term.TermTypes.STRUCTURE)
            {
                var baseObj = new Expression.Expression(targetTerm.SubTerms[0], ParentContext).GetValue();

                var obj = baseObj as ISuffixed;
                if (obj != null)
                {
                    if (obj.SetSuffix(targetTerm.SubTerms[1].Text.ToUpper(), e.GetValue()))
                    {
                        State = ExecutionState.DONE;
                        return;
                    }
                    throw new KOSException(
                        "Suffix '" + targetTerm.SubTerms[1].Text + "' doesn't exist or is read only", this);
                }
                throw new KOSException(
                    "Can't set subvalues on a " + Expression.Expression.GetFriendlyNameOfItem(baseObj), this);
            }
            var v = FindOrCreateVariable(targetTerm.Text);

            if (v == null) return;
            v.Value = e.GetValue();
            State = ExecutionState.DONE;
        }
示例#11
0
        public override void Evaluate()
        {
            var e = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);

            StdOut(e.GetValue().ToString());

            State = ExecutionState.DONE;
        }
示例#12
0
        public override void Evaluate()
        {
            var e = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);

            StdOut(e.GetValue().ToString());

            State = ExecutionState.DONE;
        }
示例#13
0
        public override void Evaluate()
        {
            expression = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);
            targetCommand = Get(RegexMatch.Groups[2].Value, ParentContext);

            ParentContext.Lock(this);

            State = ExecutionState.DONE;
        }
示例#14
0
        public override void Evaluate()
        {
            // External functions are now handled within expressions,
            // so simply execute the expression and throw away the value
            var subEx = new Expression.Expression(RegexMatch.Groups[1].Value, this);
            subEx.GetValue();

            State = ExecutionState.DONE;
        }
示例#15
0
        public override void Evaluate()
        {
            expression    = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);
            targetCommand = Get(RegexMatch.Groups[2].Value, ParentContext);

            ParentContext.Lock(this);

            State = ExecutionState.DONE;
        }
示例#16
0
        public override void Evaluate()
        {
            var varname = RegexMatch.Groups[1].Value;
            var expression = new Expression.Expression(RegexMatch.Groups[2].Value, ParentContext);

            ParentContext.Unlock(varname);
            ParentContext.Lock(varname, expression);

            State = ExecutionState.DONE;
        }
示例#17
0
        public override void Evaluate()
        {
            // External functions are now handled within expressions,
            // so simply execute the expression and throw away the value
            var subEx = new Expression.Expression(RegexMatch.Groups[1].Value, this);

            subEx.GetValue();

            State = ExecutionState.DONE;
        }
示例#18
0
        public override void Evaluate()
        {
            var varname    = RegexMatch.Groups[1].Value;
            var expression = new Expression.Expression(RegexMatch.Groups[2].Value, ParentContext);

            ParentContext.Unlock(varname);
            ParentContext.Lock(varname, expression);

            State = ExecutionState.DONE;
        }
示例#19
0
        public virtual void Lock(string name, Expression.Expression expression)
        {
            name = name.ToLower();

            FindOrCreateVariable(name);

            if (!Locks.ContainsKey(name.ToUpper()))
            {
                Locks.Add(name.ToUpper(), expression);
            }
        }
示例#20
0
        public override void Evaluate()
        {
            waitExpression = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);

            var numLinesChild = Utils.NewLineCount(Input.Substring(0, RegexMatch.Groups[2].Index));
            targetCommand = Get(RegexMatch.Groups[2].Value, this, Line + numLinesChild);

            //commandstring = RegexMatch.Groups[2].Value;

            State = ExecutionState.WAIT;
        }
示例#21
0
        public override void Evaluate()
        {
            waitExpression = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);

            var numLinesChild = Utils.NewLineCount(Input.Substring(0, RegexMatch.Groups[2].Index));

            targetCommand = Get(RegexMatch.Groups[2].Value, this, Line + numLinesChild);

            //commandstring = RegexMatch.Groups[2].Value;

            State = ExecutionState.WAIT;
        }
示例#22
0
        public override void Evaluate()
        {
            var e = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);

            if (e.IsNull())
            {
                StdOut("NULL");
                State = ExecutionState.DONE;
            }
            else
            {
                StdOut(e.ToString());
                State = ExecutionState.DONE;
            }
        }
示例#23
0
        public override void Evaluate()
        {
            var e = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);

            if (e.IsNull())
            {
                StdOut("NULL");
                State = ExecutionState.DONE;
            }
            else
            {
                StdOut(e.ToString());
                State = ExecutionState.DONE;
            }
        }
示例#24
0
        public override void Evaluate()
        {
            var e = new Expression.Expression(RegexMatch.Groups[2].Value, ParentContext);
            var untilClause = (RegexMatch.Groups[1].Value.Trim().ToUpper() == "UNTIL");

            if (!untilClause)
            {
                waitTime = e.Float();
            }
            else
            {
                waitExpression = e;
            }

            State = ExecutionState.WAIT;
        }
示例#25
0
        public override void Evaluate()
        {
            var e           = new Expression.Expression(RegexMatch.Groups[2].Value, ParentContext);
            var untilClause = (RegexMatch.Groups[1].Value.Trim().ToUpper() == "UNTIL");

            if (!untilClause)
            {
                waitTime = e.Float();
            }
            else
            {
                waitExpression = e;
            }

            State = ExecutionState.WAIT;
        }
        public override void Evaluate()
        {
            var ex = new Expression.Expression(RegexMatch.Groups[1].Value, this);
            var obj = ex.GetValue();

            var node = obj as Node;
            if (node != null)
            {
                node.Remove();
            }
            else
            {
                throw new KOSException("Supplied object ineligible for removal", this);
            }

            State = ExecutionState.DONE;
        }
        public override void Evaluate()
        {
            var ex  = new Expression.Expression(RegexMatch.Groups[1].Value, this);
            var obj = ex.GetValue();

            var node = obj as Node;

            if (node != null)
            {
                node.Remove();
            }
            else
            {
                throw new KOSException("Supplied object ineligible for removal", this);
            }

            State = ExecutionState.DONE;
        }
示例#28
0
        public override void Evaluate()
        {
            expression = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);

            var numLinesChild = Utils.NewLineCount(Input.Substring(0, RegexMatch.Groups[2].Index));
            targetCommand = Get(RegexMatch.Groups[2].Value, this, Line + numLinesChild);

            if (expression.IsTrue())
            {
                targetCommand.Evaluate();
                Push(targetCommand);
                State = ExecutionState.WAIT;
            }
            else
            {
                State = ExecutionState.DONE;
            }
        }
示例#29
0
        public override void Evaluate()
        {
            expression = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);

            var numLinesChild = Utils.NewLineCount(Input.Substring(0, RegexMatch.Groups[2].Index));

            targetCommand = Get(RegexMatch.Groups[2].Value, this, Line + numLinesChild);

            if (expression.IsTrue())
            {
                targetCommand.Evaluate();
                Push(targetCommand);
                State = ExecutionState.WAIT;
            }
            else
            {
                State = ExecutionState.DONE;
            }
        }
示例#30
0
        public override void Evaluate()
        {
            var listName = RegexMatch.Groups[2].Value;
            iteratorstring = RegexMatch.Groups[1].Value;

            var expression = new Expression.Expression(listName, ParentContext).GetValue();
            var list = expression as ListValue;
            if (list != null)
            {
                iterator = list.GetSuffix("ITERATOR") as Enumerator;
            }
            else
            {
                throw new KOSException(string.Format("List {0} Not Found.", listName));
            }

            var numLinesChild = Utils.NewLineCount(Input.Substring(0, RegexMatch.Groups[2].Index));
            targetCommand = Get(RegexMatch.Groups[3].Value, this, Line + numLinesChild);

            State = ExecutionState.WAIT;
        }
示例#31
0
        public override void Evaluate()
        {
            var e = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);
            var ex = new Expression.Expression(RegexMatch.Groups[2].Value, ParentContext);
            var ey = new Expression.Expression(RegexMatch.Groups[3].Value, ParentContext);

            if (e.IsNull()) throw new KOSException("Null value in print statement");

            int x, y;

            if (Int32.TryParse(ex.ToString(), out x) && Int32.TryParse(ey.ToString(), out y))
            {
                Put(e.ToString(), x, y);
            }
            else
            {
                throw new KOSException("Non-numeric value assigned to numeric function", this);
            }

            State = ExecutionState.DONE;
        }
示例#32
0
        public override void Evaluate()
        {
            var listName = RegexMatch.Groups[2].Value;

            iteratorstring = RegexMatch.Groups[1].Value;

            var expression = new Expression.Expression(listName, ParentContext).GetValue();
            var list       = expression as ListValue;

            if (list != null)
            {
                iterator = list.GetSuffix("ITERATOR") as Enumerator;
            }
            else
            {
                throw new KOSException(string.Format("List {0} Not Found.", listName));
            }

            var numLinesChild = Utils.NewLineCount(Input.Substring(0, RegexMatch.Groups[2].Index));

            targetCommand = Get(RegexMatch.Groups[3].Value, this, Line + numLinesChild);

            State = ExecutionState.WAIT;
        }
示例#33
0
        public override void Evaluate()
        {
            var e  = new Expression.Expression(RegexMatch.Groups[1].Value, ParentContext);
            var ex = new Expression.Expression(RegexMatch.Groups[2].Value, ParentContext);
            var ey = new Expression.Expression(RegexMatch.Groups[3].Value, ParentContext);

            if (e.IsNull())
            {
                throw new KOSException("Null value in print statement");
            }

            int x, y;

            if (Int32.TryParse(ex.ToString(), out x) && Int32.TryParse(ey.ToString(), out y))
            {
                Put(e.ToString(), x, y);
            }
            else
            {
                throw new KOSException("Non-numeric value assigned to numeric function", this);
            }

            State = ExecutionState.DONE;
        }
示例#34
0
 public BinaryOperator(Expression.Expression leftOperator, Expression.Expression rightOperator)
 {
     this.leftOperator  = leftOperator;
     this.rightOperator = rightOperator;
 }
 public OpenReadFile(Expression.Expression expression)
 {
     this.expression = expression;
 }
 public IfStatement(Expression.Expression expr, Statement thenSt, Statement elseSt)
 {
     this.expr     = expr;
     this.thenStat = thenSt;
     this.elseStat = elseSt;
 }
示例#37
0
 public override Statement Simplify()
 {
     Condition = Condition.Simplify();
     return(base.Simplify());
 }
示例#38
0
 public override Statement Simplify()
 {
     Name = Name.Simplify();
     return(base.Simplify());
 }
        private NonlinearEquationDescription CompileEquations(RootNode root)
        {
            List <RPNExpression>         rpnEquations = new List <RPNExpression>();
            List <Expression.Expression> equations    = new List <Expression.Expression>();

            foreach (var constant in root.constants)
            {
                Expression.Expression right = ExpressionSimplifier.Simplify(ConvertToExpression(constant.Right));
                //ExpressionNode right = simplify(constant.Right);
                if (right is Float)
                {
                    constants.Add(constant.Identifier, ((Float)right).Value);
                }
                else
                {
                    constants.Add(constant.Identifier, float.NaN);
                    compilerErrors.Add(new ErrorMessage("Определение константы " + constant.Identifier + " не является константным выражением"));
                }
            }

            foreach (var equation in root.equations)
            {
                SubtractionNode subtraction = new SubtractionNode
                {
                    Left     = equation.Left,
                    Right    = equation.Right,
                    Line     = equation.Line,
                    Position = equation.Position
                };
                Expression.Expression expression = ExpressionSimplifier.Simplify(ConvertToExpression(subtraction));
                equations.Add(expression);
            }

            //initialValues aren't important
            foreach (var initialValue in root.initialValues)
            {
                if (variables.ContainsKey(initialValue.Identifier))
                {
                    Expression.Expression right = ExpressionSimplifier.Simplify(ConvertToExpression(initialValue.Right));
                    //Expression expression = ConvertToExpression(right)
                    if (right is Float)
                    {
                        initialValues[variables[initialValue.Identifier]] = ((Float)right).Value;
                    }
                    else
                    {
                        //add error message
                        compilerErrors.Add(new ErrorMessage("Определение начального приближения переменной" +
                                                            initialValue.Identifier + " не является константным выражением"));
                    }
                }
                else
                {
                    //add error message
                    compilerErrors.Add(new ErrorMessage("Определение начального приближения несуществующей переменной"));
                }
            }
            //check that number of variables = number of equations
            if (variableNames.Count != equations.Count)
            {
                compilerErrors.Add(new ErrorMessage($"Количество переменных не совпадает с количеством уравнений: {variableNames.Count} переменных, {equations.Count} уравнений"));
            }
            if (equations.Count == 0)
            {
                compilerErrors.Add(new ErrorMessage("Пустая система уравнений"));
            }
            if (compilerErrors.Count > 0)
            {
                throw new CompilerException(compilerErrors);
                //fall back;
            }
            Expression.Compiler expCompiler = new Expression.Compiler(variables);
            for (int i = 0; i < equations.Count; i++)
            {
                rpnEquations.Add(expCompiler.Compile(equations[i]));
            }
            RPNExpression [,] jacobiMatrix = new RPNExpression[equations.Count, equations.Count];
            Expression.DifferentiationVisitor difVisitor = new Expression.DifferentiationVisitor();
            int j = 0;

            foreach (var equation in equations)
            {
                int i = 0;
                foreach (var variable in variableNames)
                {
                    //find derivative for variable
                    Expression.Expression derivative = ExpressionSimplifier.Simplify(difVisitor.Differentiate(equation, variable));
                    //simplify derivative expression
                    RPNExpression exp = expCompiler.Compile(derivative);
                    jacobiMatrix[i, j] = exp;
                    i++;
                }
                j++;
            }
            NonlinearEquationDescription ned = new NonlinearEquationDescription(initialValues.ToArray(), variableNames.ToArray(),
                                                                                rpnEquations, jacobiMatrix);

            return(ned);
        }
        private DAEDefinition compileDAE(RootNode root)
        {
            List <Expression.Expression> equations = new List <Expression.Expression>();

            parameters["time"] = 1.0;
            parameters["t0"]   = 0.0;
            foreach (var parameter in root.parameters)
            {
                //Convert to expression
                Expression.Expression right = ExpressionSimplifier.simplify(ConvertToExpression(parameter.Right));
                if (right is Float)
                {
                    //parameters.Add(parameter.Identifier, ((Float)right).Value);
                    parameters[parameter.Identifier] = ((Float)right).Value;
                }
                else
                {
                    parameters.Add(parameter.Identifier, float.NaN);
                    compilerErrors.Add(new ErrorMessage("Определение параметра " + parameter.Identifier + " не является константным выражением"));
                }
            }
            foreach (var equation in root.equations)
            {
                //Convert to expression
                SubtractionNode exp = new SubtractionNode
                {
                    Left     = equation.Left,
                    Right    = equation.Right,
                    Line     = equation.Line,
                    Position = equation.Position
                };
                equations.Add(ConvertToExpression(exp));
            }
            foreach (var initialValue in root.initialValues)
            {
                if (variables.ContainsKey(initialValue.Identifier))
                {
                    Expression.Expression right = ExpressionSimplifier.simplify(ConvertToExpression(initialValue.Right));
                    if (right is Float)
                    {
                        Variable var = variables[initialValue.Identifier];
                        var.InitialValue = ((Float)right).Value;
                        var.Initialized  = true;
                    }
                    else
                    {
                        //add error message
                        compilerErrors.Add(new ErrorMessage("Определение начального условия переменной " +
                                                            initialValue.Identifier + " не является константным выражением"));
                    }
                }
                else
                {
                    //add error message
                    compilerErrors.Add(new ErrorMessage("Определение начального условия несуществующей переменной"));
                }
            }
            //check that number of variables = number of equations
            if (variables.Count - 1 != equations.Count)
            {
                compilerErrors.Add(new ErrorMessage("Количество переменных не совпадает с количеством уравнений"));
            }
            if (equations.Count == 0)
            {
                compilerErrors.Add(new ErrorMessage("Пустая система уравнений"));
            }
            foreach (var variable in variables)
            {
                if (variable.Value.Initialized == false)
                {
                    compilerErrors.Add(new ErrorMessage("Не объявлены начальные условия для переменной " + variable.Key));
                }
            }
            if (compilerErrors.Count > 0)
            {
                throw new Exception("Equation definition errors");
                //fall back;
            }

            List <Expression.Expression> explicitDifferentialEquations = new List <Expression.Expression>();
            List <Expression.Expression> implicitDifferentialEquations = new List <Expression.Expression>();
            List <Expression.Expression> algebraicEquations            = new List <Expression.Expression>();

            bool semiExplicitForm = true;

            for (int i = 0; i < equations.Count; i++)
            {
                var         equation    = equations[i];
                var         astEquation = root.equations[i];
                Subtraction exp         = (Subtraction)equation;
                if (astEquation.Left.Type == ASTNodeType.Derivative)
                {
                    exp.Right = ExpressionSimplifier.simplify(exp.Right);
                    if (hasDerivative(exp.Right) || variables[(astEquation.Left as DerivativeNode).Identifier].DerCount != 1)
                    {
                        semiExplicitForm = false;
                        implicitDifferentialEquations.Add(ExpressionSimplifier.simplify(exp));
                    }
                    else
                    {
                        exp.Right = ExpressionSimplifier.simplify(exp.Right);
                        explicitDifferentialEquations.Add(exp);
                    }
                }
                else
                {
                    Expression.Expression t_exp = ExpressionSimplifier.simplify(exp);
                    if (hasDerivative(t_exp))
                    {
                        semiExplicitForm = false;
                        implicitDifferentialEquations.Add(t_exp);
                    }
                    else
                    {
                        algebraicEquations.Add(t_exp);
                    }
                }
            }

            /*
             * if all differential equations are explicit then
             * create semiExplicit definition
             */
            if (semiExplicitForm)
            {
                List <string>        variableNamesX           = new List <string>();
                List <double>        initialValuesX           = new List <double>();
                List <string>        variableNamesZ           = new List <string>();
                List <double>        initialValuesZ           = new List <double>();
                List <RPNExpression> differentialEquationsRPN = new List <RPNExpression>();
                List <RPNExpression> algebraicEquationRPN     = new List <RPNExpression>();


                Dictionary <string, int> variableIndicies = new Dictionary <string, int>();
                List <Variable>          variableListX    = new List <Variable>();
                List <Variable>          variableListZ    = new List <Variable>();
                foreach (var variable in variables)
                {
                    if (variable.Value.VarType == Variable.Type.Algebraic)
                    {
                        variableListZ.Add(variable.Value);
                    }
                    else
                    {
                        variableListX.Add(variable.Value);
                    }
                }
                variableListX.Sort(delegate(Variable x, Variable y)
                {
                    return(x.Name.CompareTo(y.Name));
                });
                variableListZ.Sort(delegate(Variable x, Variable y)
                {
                    return(x.Name.CompareTo(y.Name));
                });
                variableIndicies.Add("t", 0);
                foreach (var variable in variableListX)
                {
                    variableNamesX.Add(variable.Name);
                    initialValuesX.Add(variable.InitialValue);
                    variableIndicies.Add(variable.Name, variableIndicies.Count);
                }
                foreach (var variable in variableListZ)
                {
                    variableNamesZ.Add(variable.Name);
                    initialValuesZ.Add(variable.InitialValue);
                    variableIndicies.Add(variable.Name, variableIndicies.Count);
                }

                /*
                 * for (int i = 0; i < explicitDifferentialEquations.Count; i++)
                 * {
                 *  Subtraction equation = (Subtraction)explicitDifferentialEquations[i];
                 *  Expression.Variable left = (Expression.Variable)equation.Left;
                 *  string variableName = left.Name.TrimEnd(new char['\'']);
                 *  variableIndicies.Add(variableName, variableIndicies.Count);
                 *  variableNamesX.Add(variableName);
                 *  initialValuesX.Add(variables[variableName].InitialValue);
                 * }
                 * foreach (var variable in variableList)
                 * {
                 *  if (variable.Value.VarType == Variable.Type.Algebraic)
                 *  {
                 *      variableNamesZ.Add(variable.Key);
                 *      initialValuesZ.Add(variable.Value.InitialValue);
                 *      variableIndicies.Add(variable.Key, variableIndicies.Count);
                 *  }
                 * }*/

                ExpressionCompiler expCompiler = new ExpressionCompiler(variableIndicies);
                for (int i = 0; i < explicitDifferentialEquations.Count; i++)
                {
                    Subtraction equation = (Subtraction)explicitDifferentialEquations[i];
                    differentialEquationsRPN.Add(expCompiler.compile(equation.Right));
                }
                for (int i = 0; i < algebraicEquations.Count; i++)
                {
                    algebraicEquationRPN.Add(expCompiler.compile(algebraicEquations[i]));
                }
                DAESemiExplicitDefinition definition = new DAESemiExplicitDefinition(
                    variableNamesX.ToArray(),
                    variableNamesZ.ToArray(),
                    initialValuesX.ToArray(),
                    initialValuesZ.ToArray(),
                    differentialEquationsRPN,
                    algebraicEquationRPN
                    );
                return(definition);
            }
            else
            {
                List <RPNExpression>     equationsRPN     = new List <RPNExpression>();
                List <string>            variableNames    = new List <string>();
                List <double>            initialValues    = new List <double>();
                Dictionary <string, int> variableIndicies = new Dictionary <string, int>();

                List <Variable> variableList = new List <Variable>();
                foreach (var variable in variables)
                {
                    variableList.Add(variable.Value);
                }
                variableList.Sort(delegate(Variable x, Variable y)
                {
                    return(x.Name.CompareTo(y.Name));
                });
                //time variable
                variableIndicies.Add("t", 0);
                //variables
                foreach (var variable in variableList)
                {
                    variableNames.Add(variable.Name);
                    initialValues.Add(variable.InitialValue);
                    variableIndicies.Add(variable.Name, variableIndicies.Count);
                }
                //derivatives
                foreach (var variable in variableList)
                {
                    variableIndicies.Add(variable.Name + "'", variableIndicies.Count);
                }

                ExpressionCompiler expCompiler = new ExpressionCompiler(variableIndicies);
                for (int i = 0; i < implicitDifferentialEquations.Count; i++)
                {
                    equationsRPN.Add(expCompiler.compile(implicitDifferentialEquations[i]));
                }
                for (int i = 0; i < explicitDifferentialEquations.Count; i++)
                {
                    Subtraction equation = (Subtraction)explicitDifferentialEquations[i];
                    equationsRPN.Add(expCompiler.compile(equation));
                }
                for (int i = 0; i < algebraicEquations.Count; i++)
                {
                    equationsRPN.Add(expCompiler.compile(algebraicEquations[i]));
                }

                DAEImplicitDefinition definition = new DAEImplicitDefinition(variableNames.ToArray(), initialValues.ToArray(), equationsRPN);
                return(definition);
            }
        }
示例#41
0
 public override Statement Simplify()
 {
     Expression = Expression.Simplify();
     return base.Simplify();
 }
示例#42
0
 public NewStatement(Expression.Expression expr, string @var)
 {
     this.expr = expr;
     this.var  = var;
 }
示例#43
0
 public Variable(string name, Value value, Expression.Expression function)
 {
     this.name = name;
     this.value = value;
     this.function = function;
 }
示例#44
0
 public override Statement Simplify()
 {
     Name = Name.Simplify();
     return base.Simplify();
 }
示例#45
0
 public CloseFile(Expression.Expression expression)
 {
     this.expression = expression;
 }
示例#46
0
 public override Statement Simplify()
 {
     Condition = Condition.Simplify();
     return base.Simplify();
 }
        private Implicit.DAEIDescription CompileDAEImplicit(RootNode root)
        {
            List <Expression.Expression> equations = new List <Expression.Expression>();

            constants["time"] = 1.0;
            constants["t0"]   = 0.0;
            foreach (var constant in root.constants)
            {
                //Convert to expression
                Expression.Expression right = ExpressionSimplifier.Simplify(ConvertToExpression(constant.Right));
                if (right is Float)
                {
                    constants[constant.Identifier] = ((Float)right).Value;
                }
                else
                {
                    constants.Add(constant.Identifier, float.NaN);
                    compilerErrors.Add(new ErrorMessage("Определение константы " + constant.Identifier + " не является константным выражением"));
                }
            }
            foreach (var parameter in root.parameters)
            {
                //Convert to expression
                Expression.Expression right = ExpressionSimplifier.Simplify(ConvertToExpression(parameter.Right));
                if (right is Float)
                {
                    //parameters.Add(parameter.Identifier, ((Float)right).Value);
                    parameters[parameter.Identifier] = ((Float)right).Value;
                }
                else
                {
                    parameters.Add(parameter.Identifier, float.NaN);
                    compilerErrors.Add(new ErrorMessage("Определение параметра " + parameter.Identifier + " не является константным выражением"));
                }
            }
            foreach (var equation in root.equations)
            {
                //Convert to expression
                SubtractionNode exp = new SubtractionNode
                {
                    Left     = equation.Left,
                    Right    = equation.Right,
                    Line     = equation.Line,
                    Position = equation.Position
                };
                Expression.Expression expression = ExpressionSimplifier.Simplify(ConvertToExpression(exp));
                equations.Add(expression);
            }
            foreach (var initialValue in root.initialValues)
            {
                if (variables.ContainsKey(initialValue.Identifier))
                {
                    //Convert to expression
                    Expression.Expression right = ExpressionSimplifier.Simplify(ConvertToExpression(initialValue.Right));
                    if (right is Float)
                    {
                        Variable var = variables[initialValue.Identifier];
                        var.InitialValue = ((Float)right).Value;
                        var.Initialized  = true;
                    }
                    else
                    {
                        //add error message
                        compilerErrors.Add(new ErrorMessage("Определение начального условия переменной " +
                                                            initialValue.Identifier + " не является константным выражением"));
                    }
                }
                else
                {
                    //add error message
                    compilerErrors.Add(new ErrorMessage("Определение начального условия несуществующей переменной"));
                }
            }

            //!!!!!!!!!!!!!!!!!!!!!!!!!

            //check that number of variables = number of equations
            if (variables.Count != equations.Count)
            {
                compilerErrors.Add(new ErrorMessage("Количество переменных не совпадает с количеством уравнений"));
            }
            if (equations.Count == 0)
            {
                compilerErrors.Add(new ErrorMessage("Пустая система уравнений"));
            }
            foreach (var variable in variables)
            {
                if (variable.Value.Initialized == false)
                {
                    variable.Value.InitialValue = 0.0;
                    //compilerErrors.Add(new ErrorMessage("Не объявлены начальные условия для переменной " + variable.Key));
                }
            }
            if (compilerErrors.Count > 0)
            {
                throw new CompilerException(compilerErrors);
                //fall back;
            }

            List <RPNExpression>     equationsRPN   = new List <RPNExpression>();
            List <string>            variableNames  = new List <string>();
            List <string>            symbolNames    = new List <string>();
            List <double>            initialValues  = new List <double>();
            Dictionary <string, int> symbolIndicies = new Dictionary <string, int>();

            List <Variable> variableList = new List <Variable>();

            foreach (var variable in variables)
            {
                variableList.Add(variable.Value);
            }
            variableList.Sort(delegate(Variable x, Variable y)
            {
                return(x.Name.CompareTo(y.Name));
            });
            //time variable
            symbolIndicies.Add("t", 0);

            symbolNames.Add("t");
            //variables
            foreach (var variable in variableList)
            {
                variableNames.Add(variable.Name);
                symbolNames.Add(variable.Name);
                initialValues.Add(variable.InitialValue);
                symbolIndicies.Add(variable.Name, symbolIndicies.Count);
            }
            //derivatives
            foreach (var variable in variableList)
            {
                symbolNames.Add(variable.Name + "'");
                symbolIndicies.Add(variable.Name + "'", symbolIndicies.Count);
            }

            string[] parameterNames  = new string[parameters.Count];
            double[] parameterValues = new double[parameters.Count];
            {
                int i = 0;
                foreach (var parameter in parameters)
                {
                    parameterNames[i]  = parameter.Key;
                    parameterValues[i] = parameter.Value;
                    i++;
                }
            }
            foreach (var parameter in parameterNames)
            {
                symbolNames.Add(parameter);
                symbolIndicies.Add(parameter, symbolIndicies.Count);
            }

            Expression.Compiler expCompiler = new Expression.Compiler(symbolIndicies);
            for (int i = 0; i < equations.Count; i++)
            {
                equationsRPN.Add(expCompiler.Compile(equations[i]));
            }
            MathUtils.SparseMatrix <RPNExpression> dfdx = MathUtils.SparseMatrix <RPNExpression> .Build(equations.Count, equations.Count);

            MathUtils.SparseMatrix <RPNExpression> dfddx = MathUtils.SparseMatrix <RPNExpression> .Build(equations.Count, equations.Count);

            Expression.DifferentiationVisitor difVisitor = new Expression.DifferentiationVisitor();
            for (int j = 0; j < equations.Count; j++)
            {
                for (int i = 0; i < equations.Count; i++)
                {
                    Expression.Expression derivative = ExpressionSimplifier.Simplify(difVisitor.Differentiate(equations[i], variableNames[j]));
                    if (derivative.Type == ExpressionType.Float)
                    {
                        if ((derivative as Expression.Float).IsZero())
                        {
                            continue;
                        }
                    }
                    RPNExpression exp = expCompiler.Compile(derivative);
                    //dfdx[i, j] = exp;
                    dfdx.Add(i, j, exp);
                }
            }
            for (int j = 0; j < equations.Count; j++)
            {
                for (int i = 0; i < equations.Count; i++)
                {
                    Expression.Expression derivative = ExpressionSimplifier.Simplify(difVisitor.Differentiate(equations[i], variableNames[j] + "'"));
                    if (derivative.Type == ExpressionType.Float)
                    {
                        if ((derivative as Expression.Float).IsZero())
                        {
                            continue;
                        }
                    }
                    RPNExpression exp = expCompiler.Compile(derivative);
                    //dfddx[i, j] = exp;
                    dfddx.Add(i, j, exp);
                }
            }
            Implicit.DAEIDescription definition = new Implicit.DAEIDescription(variableNames.ToArray(),
                                                                               parameterNames,
                                                                               parameterValues,
                                                                               initialValues.ToArray(),
                                                                               equationsRPN,
                                                                               dfdx,
                                                                               dfddx,
                                                                               constants["t0"],
                                                                               constants["time"]);
            return(definition);
        }
 public AssignStatement(string id, Expression.Expression expr)
 {
     this.id   = id;
     this.expr = expr;
 }
示例#49
0
 public Variable(string name, Value value, Expression.Expression function)
 {
     this.name     = name;
     this.value    = value;
     this.function = function;
 }