Exemplo n.º 1
0
        /// <inheritdoc />
        public IConcreteValue this[IVariable variable]
        {
            get
            {
                if (!_variables.TryGetValue(variable, out var value))
                {
                    value = variable switch
                    {
                        CilVariable cilVariable => _valueFactory.CreateValue(cilVariable.Variable.VariableType, false),
                        CilParameter cilParameter => _valueFactory.CreateValue(cilParameter.Parameter.ParameterType,
                                                                               false),
                        _ => throw new NotSupportedException($"IVariable implementation {variable.GetType()} is not supported.")
                    };
                    _variables[variable] = value;
                }

                return(value);
            }
            set
            {
                if (!(variable is CilParameter) && !(variable is CilVariable))
                {
                    throw new NotSupportedException($"IVariable implementation {variable.GetType()} is not supported.");
                }

                _variables[variable] = value;
            }
        }
Exemplo n.º 2
0
 public void Compile()
 {
     if (!this.IsLoaded())
     {
         this.Load();
     }
     this.compiled = true;
     foreach (string r_expr in script.Split(';'))
     {
         if (r_expr == "" || r_expr == " ")
         {
             continue;
         }
         string expr = Regex.Replace(r_expr, "\r?\n+[ \t]*", " ");
         if (expr == "" || expr == " ")
         {
             continue;
         }
         int index = 0;
         tt.Value.Logger.Debug("Start Parsing Expr : " + expr);
         IVariable Value = Split.Parse(expr, ref index, ';');
         tt.Value.Logger.Debug("Parsed Expr to : " + Value.ToString());
         string vt = Value.GetType();
         if (vt == "Recipe")
         {
             recipes.Add((MLRecipe)Value);
         }
         else if (vt == "Remove")
         {
             removes.Add((MLItem)Value.GetValue());
         }
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Apply commands.
        /// </summary>
        /// <param name="model">The underlying model to apply the commands to</param>
        public void Apply(Model model)
        {
            if (this.Command != null)
            {
                foreach (string command in this.Command)
                {
                    try
                    {
                        string propertyName  = command;
                        string propertyValue = StringUtilities.SplitOffAfterDelimiter(ref propertyName, "=");

                        propertyName  = propertyName.TrimEnd();
                        propertyValue = propertyValue.TrimEnd();

                        if (propertyName != string.Empty && propertyValue != string.Empty)
                        {
                            IVariable property = model.FindByPath(propertyName) as IVariable;
                            if (property == null)
                            {
                                throw new Exception(string.Format("Invalid command in cultivar {0}: {1}", Name, propertyName));
                            }
                            if (property.GetType() != null)
                            {
                                object oldValue = property.Value;
                                if (oldValue is string || oldValue.GetType().IsArray || !oldValue.GetType().IsClass)
                                {
                                    this.oldPropertyValues.Add(oldValue);
                                    property.Value = propertyValue;
                                    this.properties.Add(property);
                                }
                                else
                                {
                                    throw new ApsimXException(this, "Invalid type for setting cultivar parameter: " + propertyName +
                                                              ". Must be a built-in type e.g. double");
                                }
                            }
                            else
                            {
                                throw new ApsimXException(this, "While applying cultivar '" + Name + "', could not find property name '" + propertyName + "'");
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        throw new Exception($"Error in cultivar {Name}: Unable to apply command '{command}'", err);
                    }
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Apply commands.
        /// </summary>
        /// <param name="model">The underlying model to apply the commands to</param>
        public void Apply(Model model)
        {
            if (this.Commands != null)
            {
                foreach (string command in this.Commands)
                {
                    string propertyName  = command;
                    string propertyValue = StringUtilities.SplitOffAfterDelimiter(ref propertyName, "=");

                    propertyName  = propertyName.TrimEnd();
                    propertyValue = propertyValue.TrimEnd();

                    if (propertyName != string.Empty && propertyValue != string.Empty)
                    {
                        IVariable property = Apsim.GetVariableObject(model, propertyName) as IVariable;
                        if (property == null)
                        {
                            throw new Exception("Cannot find cultivar property: " + propertyName);
                        }
                        if (property.GetType() != null)
                        {
                            object oldValue = property.Value;
                            if (oldValue is string || oldValue.GetType().IsArray || !oldValue.GetType().IsClass)
                            {
                                this.oldPropertyValues.Add(oldValue);
                                property.Value = propertyValue;
                                this.properties.Add(property);
                            }
                            else
                            {
                                throw new ApsimXException(this, "Invalid type for setting cultivar parameter: " + propertyName +
                                                          ". Must be a built-in type e.g. double");
                            }
                        }
                        else
                        {
                            throw new ApsimXException(this, "While applying cultivar '" + Name + "', could not find property name '" + propertyName + "'");
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
        public Edge(SerializationInfo info, StreamingContext context)
        {
            FlagVisible   = 0;
            region        = new Region();
            ForInvalidate = new GraphicsPath();
            variable      = null;
            calculate     = null;
            pen           = new Pen(Color.Black, 7);
            PathLine      = new GraphicsPath();
            BeginEllips   = new GraphicsPath();
            EndEllips     = new GraphicsPath();

            BeginPoint   = (Point)info.GetValue("BeginPoint", BeginPoint.GetType());
            EndPoint     = (Point)info.GetValue("EndPoint", EndPoint.GetType());
            LastLocation = (Point)info.GetValue("LastLocation", LastLocation.GetType());
            try
            {
                calculate = (ICalculate)info.GetValue("calculate", ((BaseControl)calculate).GetType());
            }
            catch
            {
                calculate = null;
            }
            try
            {
                variable = (IVariable)info.GetValue("variable", variable.GetType());
            }
            catch {
                variable = null;
            }
            BeginEllips.AddEllipse(BeginPoint.X - 10, BeginPoint.Y - 10, 20, 20);
            PathLine.AddLine(BeginPoint, EndPoint);
            EndEllips.AddEllipse(EndPoint.X - 10, EndPoint.Y - 10, 20, 20);

            if (Move != null)
            {
                Move(this, BeginPoint, EndPoint);
            }
        }
Exemplo n.º 6
0
        public static IMultiDimensionalArray CreateEmptyValuesArray(IVariable variable)
        {
            Type valueType = variable.GetType().GetGenericArguments()[0];

            return (MultiDimensionalArray)TypeUtils.CreateGeneric(typeof(MultiDimensionalArray<>), valueType);
        }
Exemplo n.º 7
0
        public static IMultiDimensionalArray CreateEmptyValuesArray(IVariable variable)
        {
            Type valueType = variable.GetType().GetGenericArguments()[0];

            return((MultiDimensionalArray)TypeUtils.CreateGeneric(typeof(MultiDimensionalArray <>), valueType));
        }
        //Calculates the value by expression tree.
        //Calculator - The object that contains functions, variables and expressions.
        //Relative - The relative variable.
        public object Calc(ICalculator calculator, IVariable relative, IFunction callFunction)
        {
            try
            {
                if (m_type == NODE_TYPE.FUNCTION || m_type == NODE_TYPE.OPERATOR)
                {
                    //Run function.
                    IFunction func;
                    //(14.11.2006 11:50)
                    //Point directly to the function to increase speed.
                    if (m_function != null)
                    {
                        func = m_function;
                    }
                    else
                    {
                        string val = (string)m_value;
                        FunctionSet functions = calculator.Functions;
                        if (functions.Contains(val))
                        {
                            func = functions.Item(val);
                            m_function = func;
                        }
                        else
                        {
                            throw new Exception("Unknown function :" + val);
                        }
                    }

                    if (func is IIntelligenceFunction)
                    {
                        return ((IIntelligenceFunction)func).Run(m_subNodes, calculator, relative);
                    }

                    object[] @params = new object[this.m_subNodes.Length];
                    //The argument position.
                    int i = 0;
                    while (i < @params.Length)
                    {
                        object obj = m_subNodes[i].Calc(calculator, relative, func);
                        @params[i] = obj;
                        i += 1;
                    }

                    return func.Run(@params);
                }
                else if (m_type == NODE_TYPE.TEXT)
                    return m_value;
                else if (m_type == NODE_TYPE.NUMBER)
                    return (float)m_value;
                else if (m_type == NODE_TYPE.VARIABLE)
                {
                    string val = (string)m_value;
                    int propIndex = val.IndexOf('.');

                    #region "Sub Expression Updating"
                    // Update sub expressions before calculating the value to make sure
                    // the computation will be correct.
                    if (calculator.RunExpressions && relative != null)
                    {
                        if (this.m_subExpressionUpdate == null)
                            this.m_subExpressionUpdate = new SubExpressionUpdate(calculator, callFunction, val, propIndex, relative);
                        this.m_subExpressionUpdate.UpdateSubExpressions(calculator);
                        if (propIndex == 0)
                            return relative.GetType().InvokeMember(val.Substring(propIndex + 1), System.Reflection.BindingFlags.GetProperty, null, relative, new object[] {});
                        else
                            return calculator.ComputeVariable(val, null);
                    }
                    #endregion

                    // Don't use relative if there is none.
                    if (relative == null || propIndex != 0 && (propIndex == -1 || val.Substring(0, propIndex) != relative.Name))
                    {
                        return calculator.ComputeVariable(val, relative);
                    }
                    // Get value directly from variable if relative is the variable.
                    return relative.GetType().InvokeMember(val.Substring(propIndex + 1), System.Reflection.BindingFlags.GetProperty, null, relative, new object[] {});
                }

            }
            catch (Exception ex)
            {
                if (!(ex is ExpressionException))
                {
                    throw new ExpressionException(ex.Message, m_column, m_length);
                }
                else
                {
                    throw ex;
                }
            }
            return null;
        }
Exemplo n.º 9
0
 public string WrongTypeError(IVariable variable) =>
 $"Переменная \"{variable.Name}\" помечена как логическая переменная, но имеет недопустимое значение ({variable.GetType()}).";
Exemplo n.º 10
0
        public static void CreateTestMethod(IMathExpression result, CodeTypeDeclaration t, CodeNamespace ns, CodeMemberMethod m, AssemblyRefList imports, VariableList parameters, List <IPropertyPointer> pointerList)
        {
            result.GetAllImports(imports);
            //
            m.ReturnType = new CodeTypeReference(result.DataType.Type);
            //
            m.Comments.Add(new CodeCommentStatement("Variable mapping:"));
            m.Comments.Add(new CodeCommentStatement("In formula:  method parameter"));
            //
            MethodType mt = new MethodType();

            mt.MethodCode = m;
            result.GenerateInputVariables();
            VariableList variables = result.InputVariables;
            Dictionary <string, IPropertyPointer> pointers = new Dictionary <string, IPropertyPointer>();

            result.GetPointers(pointers);
            int n = variables.Count;

            MathNode.Trace("Generate arguments from {0} input variables", n);
            MathNode.IndentIncrement();
            for (int k = 0; k < n; k++)
            {
                IVariable var = variables[k];
                MathNode.Trace(k, var);
                if (!(var is MathNodeVariableDummy) && !var.IsParam && !var.IsConst)
                {
                    string paramName = "";
                    parameters.Add(var);
                    paramName = var.CodeVariableName;
                    CodeParameterDeclarationExpression p = new CodeParameterDeclarationExpression(new CodeTypeReference(var.VariableType.Type), paramName);
                    m.Parameters.Add(p);
                    //add comment
                    string sub = var.SubscriptName;
                    if (string.IsNullOrEmpty(sub))
                    {
                        sub = " ";
                    }
                    m.Comments.Add(new CodeCommentStatement(string.Format("{0}{1}:\t {2}", var.VariableName, sub, var.CodeVariableName)));
                    MathNode.IndentIncrement();
                    MathNode.Trace("Argument {0} {1} for {2}, {3}", var.VariableType.Type, paramName, var.TraceInfo, var.GetType());
                    MathNode.IndentDecrement();
                    //
                    result.AssignCodeExp(new CodeArgumentReferenceExpression(paramName), var.CodeVariableName);
                }
            }
            MathNode.Trace("Generate arguments from {0} pointers", pointers.Count);
            foreach (KeyValuePair <string, IPropertyPointer> kv in pointers)
            {
                string paramName = "";
                pointerList.Add(kv.Value);
                paramName = kv.Value.CodeName;
                CodeParameterDeclarationExpression p = new CodeParameterDeclarationExpression(new CodeTypeReference(kv.Value.ObjectType), paramName);
                m.Parameters.Add(p);
                //add comment
                m.Comments.Add(new CodeCommentStatement(string.Format("{0}:\t {1}", kv.Value.ToString(), paramName)));
                MathNode.IndentIncrement();
                MathNode.Trace("Argument {0} {1} for {2}", kv.Value.ObjectType, paramName, kv.Value.ToString());
                MathNode.IndentDecrement();
            }
            MathNode.IndentDecrement();
            //do the compiling
            CodeExpression ce = result.ReturnCodeExpression(mt);

            //
            MathNode.Trace("Test method returns {0}, compiled type: {1}", result.DataType.Type, result.ActualCompileDataType.Type);
            if (result.ActualCompileDataType.Type.Equals(result.DataType.Type))
            {
                CodeMethodReturnStatement mr = new CodeMethodReturnStatement(ce);
                m.Statements.Add(mr);
            }
            else
            {
                if (result.ActualCompileDataType.IsVoid)
                {
                    m.Statements.Add(new CodeExpressionStatement(ce));
                    CodeMethodReturnStatement mr = new CodeMethodReturnStatement(ValueTypeUtil.GetDefaultValueByType(result.DataType.Type));
                    m.Statements.Add(mr);
                }
                else
                {
                    if (result.DataType.IsVoid)
                    {
                        m.Statements.Add(new CodeExpressionStatement(ce));
                    }
                    else
                    {
                        if (result.DataType.Type.Equals(typeof(string)))
                        {
                            CodeMethodReturnStatement mr = new CodeMethodReturnStatement(new CodeMethodInvokeExpression(ce, "ToString", new CodeExpression[] { }));
                            m.Statements.Add(mr);
                        }
                        else
                        {
                            CodeExpression mie = RaisDataType.GetConversionCode(result.ActualCompileDataType, ce, result.DataType, m.Statements);
                            if (mie != null)
                            {
                                CodeMethodReturnStatement mr = new CodeMethodReturnStatement(mie);
                                m.Statements.Add(mr);
                            }
                        }
                    }
                }
            }
        }