public static Matrix JakobiMatrix(Vector x, Function[] f, double precision)
        {
            if ((f.Length > 0) && (x.Length > 0) && (precision > 0))
            {

                Matrix J = new Matrix(f.Length, x.Length);
                Vector temp = x.Clone() as Vector;

                for (int counter1 = 0; counter1 < J.Height; counter1++)
                {
                    for (int counter2 = 0; counter2 < J.Width; counter2++)
                    {
                        temp[counter2] += precision;

                        J[counter1][counter2] = (f[counter1](temp) - f[counter1](x)) / precision;

                        temp[counter2] -= precision;
                    }
                }

                return J;
            }
            else
            {
                throw new IncorrectIncomingDataException("Dimensions of delegates or vectors or precision are incorrect.");
            }
        }
 /// <summary>
 /// Creates a new verification exception
 /// </summary>
 /// <param name="message">The message</param>
 /// <param name="function">The function being verified</param>
 /// <param name="instruction">The instruction being verified</param>
 /// <param name="index">The index of the instruction</param>
 public VerificationException(string message, Function function, Instruction instruction, int index)
     : base($"{index}: {message}")
 {
     this.Function = function;
     this.Instruction = instruction;
     this.InstructionIndex = index;
 }
 private static void BuildDeclarations(Namespace @namespace, IEnumerable<Declarations.Declaration> declarations)
 {
     foreach(var declaration in declarations)
         declaration.Match()
             .With<NamespaceDeclaration>(ns =>
             {
                 var childNamespace = new Namespace(ns.Syntax, @namespace, ns.Name);
                 @namespace.Add(childNamespace);
                 BuildDeclarations(childNamespace, ns.Members);
             })
             .With<ClassDeclaration>(@classDecl =>
             {
                 var syntax = @classDecl.Syntax.Single(); // TODO handle partial classes
                 var @class = new Class(syntax, @namespace, syntax.Accessibility, @classDecl.Name);
                 @namespace.Add(@class);
             })
             .With<FunctionDeclaration>(@functionDeclaration =>
             {
                 var syntax = @functionDeclaration.Syntax.Single(); // TODO handle overloads
                 var function = new Function(syntax, @namespace, syntax.Accessibility, @functionDeclaration.Name);
                 @namespace.Add(function);
             })
             // TODO handle ambigouous declarations
             .Exhaustive();
 }
      public static void FixGetterSetter(this Type type)
      {         
         var methods = type.GetInstanceMethodNames(); 

         foreach(string methname in methods)
         {
            if(methname.StartsWith("get_"))
            {
               string propname = methname.Substring(4);
               bool has_setter = methods.Contains("set_"+propname);

               Function fget = new Function("",string.Format("return this.get_{0}();",propname));
               Function fset = new Function("value",string.Format("this.set_{0}(value);",propname));
               
               if(has_setter)
               {
                  defineprop(type, propname,fget,fset);
               }
               else
               {
                  definepropreadonly(type, propname, fget);
               }
            }
         }
      }
 public FunctionInliner(Function root)
 {
     _root = root;
     _funStack.Push(root);
     _sim = new ScopedIdentifierManager(true);
     _locals = new CacheDictionary<Tuple<Function, IStorableLiteral>, IStorableLiteral>(CreateLocal);
 }
        private Ref Call(Function function)
        {
            try
            {
                foreach(var statement in function.Body)
                {
                    var returnValue = Execute(statement);
                    if(returnValue != null)
                        // TODO check that the reference ownership and mutablilty match the return type
                        // TODO constrain value to return type
                        // TODO constrain integer values to bits of return type
                        return returnValue;
                }

                // Reached end without return
                if(function.ReturnType.Type is VoidType)
                    return voidReference.Borrow();

                throw new InterpreterPanicException("Reached end of function without returning value");
            }
            catch(InterpreterPanicException ex)
            {
                ex.AddCallStack(function.QualifiedName());
                throw;
            }
        }
        public void TestInvalidMain()
        {
            using (var container = new Win64Container())
            {
                var intType = container.VirtualMachine.TypeProvider.GetPrimitiveType(PrimitiveTypes.Int);

                var mainFunc = new Function(
                    new FunctionDefinition("main", new List<VMType>() { intType }, intType),
                    new List<Instruction>()
                    {
                        new Instruction(OpCodes.LoadInt, 0),
                        new Instruction(OpCodes.Ret)
                    },
                    new List<VMType>());

                try
                {
                    container.LoadAssembly(Assembly.SingleFunction(mainFunc));
                    Assert.Fail("Expected invalid main to not pass.");
                }
                catch (Exception e)
                {
                    Assert.AreEqual("Expected the main function to have the signature: 'main() Int'.", e.Message);
                }
            }
        }
Exemple #8
0
		///
		/// <summary> * Create a window function for a given sample size. This preallocates
		/// * resources appropriate to that block size.
		/// *  </summary>
		/// * <param name="size"> The number of samples in a block that we will
		/// *                      be asked to transform. </param>
		/// * <param name="function"> The window function to use. Function.RECTANGULAR
		/// *                      effectively means no transformation. </param>
		///
		public Window(int size, Function function)
		{
			blockSize = size;

			// Create the window function as an array, so we do the
			// calculations once only. For RECTANGULAR, leave the kernel as
			// null, signalling no transformation.
			kernel = function == Function.RECTANGULAR ? null : new double[size];

			switch (function)
			{
				case Function.RECTANGULAR:
					// Nothing to do.
					break;
				case Function.BLACKMAN_HARRIS:
					makeBlackmanHarris(kernel, size);
					break;
				case Function.GAUSS:
					makeGauss(kernel, size);
					break;
				case Function.WEEDON_GAUSS:
					makeWeedonGauss(kernel, size);
					break;
			}
		}
 internal CreateFunctionImportMappingCommand(EntityContainerMapping em, Function function, string createFuncImpCmdId)
     : base(PrereqId)
 {
     ContainerMapping = em;
     Function = function;
     _createFuncImpCmdId = createFuncImpCmdId;
 }
Exemple #10
0
        //TODO: get this near functiontest. This is not a general function.
        public static IFunction CreateSimpleFunction(IFunctionStore store)
        {
            var function = new Function("test");

            store.Functions.Add(function);

            // initialize schema
            IVariable x = new Variable<double>("x", 3);
            IVariable y = new Variable<double>("y", 2);
            IVariable f1 = new Variable<double>("f1");

            function.Arguments.Add(x);
            function.Arguments.Add(y);
            function.Components.Add(f1);


            // write some data
            var xValues = new double[] {0, 1, 2};
            var yValues = new double[] {0, 1};
            var fValues = new double[] {100, 101, 102, 103, 104, 105};

            function.SetValues(fValues,
                               new VariableValueFilter<double>(x, xValues),
                               new VariableValueFilter<double>(y, yValues),
                               new ComponentFilter(f1));
            return function;
        }
 internal CreateFunctionImportMappingCommand(EntityContainerMapping em, Function function, FunctionImport functionImport)
     : base(PrereqId)
 {
     ContainerMapping = em;
     Function = function;
     FunctionImport = functionImport;
 }
Exemple #12
0
        [Category(TestCategory.Jira)] //TOOLS-4934
        public void EventBubbleCorerctlyForFunctionWithReducedArgument()
        {
            IFunction function = new Function
                                     {
                                         Arguments = {new Variable<int>("x1"), new Variable<int>("x2")},
                                         Components = {new Variable<int>("f")}
                                     };

            function[0, 1] = new[] {1};
            function[0, 2] = new[] {2};
            function[1, 1] = new[] {3};
            function[1, 2] = new[] {4};

            var arg1 = function.Arguments[0];

            var filteredFunction = function.Filter(new VariableValueFilter<int>(arg1, 0), new VariableReduceFilter(arg1));
            
            int called = 0;

            filteredFunction.ValuesChanged += (s, e) => called++;

            function[0, 2] = 3; //set value

            Assert.AreEqual(1, called);
        }
Exemple #13
0
        public static CXXOperatorArity ClassifyOperator(Function function)
        {
            if (function.Parameters.Count == 1)
                return CXXOperatorArity.Unary;

            return CXXOperatorArity.Binary;
        }
        private static bool CheckDefaultParametersForAmbiguity(Function function, Function overload)
        {
            var commonParameters = Math.Min(function.Parameters.Count, overload.Parameters.Count);

            var i = 0;
            for (; i < commonParameters; ++i)
            {
                var funcParam = function.Parameters[i];
                var overloadParam = overload.Parameters[i];

                if (!funcParam.QualifiedType.Equals(overloadParam.QualifiedType))
                    return false;
            }

            for (; i < function.Parameters.Count; ++i)
            {
                var funcParam = function.Parameters[i];
                if (!funcParam.HasDefaultValue)
                    return false;
            }

            for (; i < overload.Parameters.Count; ++i)
            {
                var overloadParam = overload.Parameters[i];
                if (!overloadParam.HasDefaultValue)
                    return false;
            }

            if (function.Parameters.Count > overload.Parameters.Count)
                overload.ExplicitlyIgnore();
            else
                function.ExplicitlyIgnore();

            return true;
        }
Exemple #15
0
		protected void WriteFunctionTitle( StreamWriter stream, Function function )
		{
			stream.Write( "//-----------------------------------------------------------------------------" );
			stream.WriteLine( "// Function Name: " + function.Name );
			stream.WriteLine( "//Function Desc: " + function.Description );
			stream.WriteLine( "//-----------------------------------------------------------------------------" );
		}
        /**
         * Formats nicer error messages for the junit output
         */
        private static double invokeInternal(Function target, ValueEval[] args, int srcCellRow, int srcCellCol)
        {
            ValueEval EvalResult = null;
            try
            {
                EvalResult = target.Evaluate(args, srcCellRow, (short)srcCellCol);
            }
            catch (NotImplementedException e)
            {
                throw new NumericEvalEx("Not implemented:" + e.Message);
            }

            if (EvalResult == null)
            {
                throw new NumericEvalEx("Result object was null");
            }
            if (EvalResult is ErrorEval)
            {
                ErrorEval ee = (ErrorEval)EvalResult;
                throw new NumericEvalEx(formatErrorMessage(ee));
            }
            if (!(EvalResult is NumericValueEval))
            {
                throw new NumericEvalEx("Result object type (" + EvalResult.GetType().Name
                        + ") is invalid.  Expected implementor of ("
                        + typeof(NumericValueEval).Name + ")");
            }

            NumericValueEval result = (NumericValueEval)EvalResult;
            return result.NumberValue;
        }
        public void TestAsArgument()
        {
            IVariable<IFeatureLocation> a = new Variable<IFeatureLocation>("argument");
            IVariable<double> c1 = new Variable<double>("value");
            IVariable<string> c2 = new Variable<string>("description");

            // f = (a, p)(h)
            IFunction f = new Function("rating curve");
            f.Arguments.Add(a);
            f.Components.Add(c1);
            f.Components.Add(c2);

            SimpleFeature simpleFeature = new SimpleFeature(10.0);
            IFeatureLocation featureLocation = new FeatureLocation { Feature = simpleFeature };

            // value based argument referencing.
            f[featureLocation] = new object[] { 1.0, "jemig de pemig" };

            IMultiDimensionalArray<double> c1Value = f.GetValues<double>(new ComponentFilter(f.Components[0]),
                                                                         new VariableValueFilter<IFeatureLocation>(
                                                                             f.Arguments[0],
                                                                             new FeatureLocation
                                                                                 {Feature = simpleFeature}));

            Assert.AreEqual(1.0, c1Value[0], 1.0e-6);

            //IMultiDimensionalArray<string> c2Value = f.GetValues<string>(new ComponentFilter(f.Components[1]),
            //                                                             new VariableValueFilter<IFeatureLocation>(
            //                                                                 f.Arguments[0], featureLocation));

            //Assert.AreEqual("jemig de pemig", c2Value[0]);
        }
        public Expression Generate(Function method, IEnumerable<Expression> arguments)
        {
            var instance = arguments.First();
            var type = (ConstantExpression)arguments.Skip(1).Last();

            return Expression.TypeIs(instance, (Type)type.Value);
        }
        public void TestNotEndInReturn()
        {
            using (var container = new Win64Container())
            {
                var intType = container.VirtualMachine.TypeProvider.GetPrimitiveType(PrimitiveTypes.Int);

                var instructions = new List<Instruction>();
                instructions.Add(new Instruction(OpCodes.LoadInt, 0));

                var func = new Function(
                    new FunctionDefinition("main", new List<VMType>(), intType),
                    instructions,
                    new List<VMType>());

                container.LoadAssembly(Assembly.SingleFunction(func));

                try
                {
                    container.Execute();
                    Assert.Fail("Expected without return to not pass.");
                }
                catch (VerificationException e)
                {
                    Assert.AreEqual("0: Functions must end with a return instruction.", e.Message);
                }
            }
        }
 /// This bisection method returns the best double approximation
 /// to a root of F.f.  Returns double.NaN if the F.f(a)*F.f(b) > 0.
 public static double Bisection(Function F, double a, double b)
 {
     if (F.f(a) == 0) {
     return a;
      }
      if (F.f(b) == 0) {
     return b;
      }
      if (Math.Sign(F.f (b)) == Math.Sign (F.f (a))) { //or F.f(a)*F.f(b)>0
     return double.NaN;
      }
      double c = (a + b) / 2;
      // If no f(c) is exactly 0, iterate until the smallest possible
      // double interval, when there is no distinct double midpoint.
      while (c != a && c != b) {
     Console.WriteLine ("a = {0}  b= {1}", a, b);
     if (F.f(c) == 0) {
        return c;
     }
     if (Math.Sign(F.f (c)) == Math.Sign (F.f (a)))
        a = c;
     else
        b = c;
     c = (a + b) / 2;
      }
      return c;
 }
        public void ConvertOneArgumentOfTwoDimensionalFunction()
        {
            IFunction func = new Function();
            IVariable<int> x = new Variable<int>("x");
            IVariable<DateTime> t = new Variable<DateTime>("t");
            var fx = new Variable<int>();
            func.Arguments.Add(x);
            func.Arguments.Add(t);
            func.Components.Add(fx);
            DateTime t0 = DateTime.Now;
            func[10,t0] = 4;

            IFunction convertedFunction = new ConvertedFunction<string, int>(func, x, Convert.ToInt32, Convert.ToString);
            //notice both argument and component are converted
            Assert.IsTrue(convertedFunction.Arguments[0] is IVariable<string>);
            Assert.IsTrue(convertedFunction.Components[0] is IVariable<int>);
            //notice the argument has been converted to a string variable
            Assert.AreEqual(4, convertedFunction["10",t0]);
            Assert.AreEqual(4, convertedFunction.Components[0].Values[0,0]);
            //arguments of components are converted as well :)
            Assert.AreEqual(4, convertedFunction.Components[0]["10",t0]);
            convertedFunction["30",t0] = 10;
            IMultiDimensionalArray<string> strings = (IMultiDimensionalArray<string>)convertedFunction.Arguments[0].Values;
            Assert.IsTrue(new[] { "10", "30" }.SequenceEqual(strings));
            
        }
Exemple #22
0
        public void SetComponentAtArgumentValueZero()
        {
            var function = new Function();

            function.Components.Add(new Variable<double>("y"));
            function.Arguments.Add(new Variable<double>("x"));

            //0.0 is replaced by 'nextvalue' because it is DefaultValue.
            //if you want to assign 0.0 you should change the DefaultValue now
            //-> Maybe dont wont a default by default or other default?
            //FIX:
            function.Arguments[0].DefaultValue = -999.0;
            var argumentValues = new[] {-10.0, 0.0, 10.0};
            var componentValues = new[] { 8.0, 9.0, 10.0 };
            for (int i = 0; i < argumentValues.Count(); i++)
            {
                function[argumentValues[i]] = componentValues[i];
            }

            Assert.AreEqual(new[] {-10.0, 0.0, 10.0},function.Arguments[0].Values);
            Assert.AreEqual(new[] { 8.0, 9.0, 10.0 }, function.Components[0].Values);
            function.Components[0].Values.Count
                .Should("there should be three values").Be.EqualTo(3);
            function.Components[0].Values[1]
                .Should("Value should be componentValue").Be.EqualTo(componentValues[1]);

            function.Arguments[0].Values.Count
                .Should("there should be three values").Be.EqualTo(3);
            function.Arguments[0].Values[1]
                .Should("Value should be argumentValues").Be.EqualTo(argumentValues[1]);
        }
		public Parameter2DFunction(Function functionX,Function functionY)
		{
			if (functionX == null)
				throw new ArgumentNullException("functionX");
			if (functionY == null)
				throw new ArgumentNullException("functionY");

			if (functionX.ArgsCount > 1 || functionX.ReturnType != typeof(double))
				throw new ArgumentException("functionX must have double return type and <= 1 arguments","functionX");
			if (functionY.ArgsCount > 1 || functionY.ReturnType != typeof(double))
				throw new ArgumentException("functionY must have double return type and <= 1 arguments","functionY");

			if (functionX.DefinitionType != functionY.DefinitionType)
				throw new ArgumentException("functionX and functionY must have equal DefinitionType");

			_functionX = functionX;
			_functionY = functionY;

			_expressionX = _functionX.Expression;
			_expressionY = _functionY.Expression;

			_expression = (_functionX.DefinitionType == DefinitionType.Analytic) ?
				string.Format("{0};{1}",_expressionX,_expressionY) : null;

			_function = DelegateFactory.CreateParameter2DFunctionDelegate(
				_functionX.ValueAt,_functionY.ValueAt);

			base._delegate = _function;
			base._definitionType = functionX.DefinitionType;
		}
        public void ClearFunctionThatIsBoundToDecorator()
        {
            IFunction function = new Function("time series");

            function.Arguments.Add(new Variable<DateTime>("time"));
            function.Components.Add(new Variable<double>("water_discharge"));

            // set initial values
            DateTime time1 = DateTime.Now;
            DateTime time2 = time1.AddMinutes(1);
            DateTime time3 = time2.AddMinutes(1);
            function[time1] = 0.0;
            function[time2] = 1.0;
            function[time3] = 2.0;

            ILineChartSeries lineChartSeries = ChartSeriesFactory.CreateLineSeries();

            lineChartSeries.XValuesDataMember = function.Arguments[0].DisplayName;
            lineChartSeries.YValuesDataMember = function.Components[0].DisplayName;

            var control = new Control();
            WindowsFormsTestHelper.Show(control);

            var functionBindingList = new FunctionBindingList(function) { SynchronizeInvoke = control };
            lineChartSeries.DataSource = functionBindingList;
            
            function.Clear();

            while(functionBindingList.IsProcessing)
            {
                Application.DoEvents();
            }

        }
Exemple #25
0
        public static void Main() {
            Foo f = new Foo(0, 1);
            Bar b = new Bar(0, 1, new Foo(0, 1));
            Test t = new Test();
            Date d = new Date("3/9/1976");
            int[] items = new Array();
            int[] items2 = new int[] { 1, 2 };
            int[] items3 = { 4, 5 };
            int[] items4 = new int[5];
            ArrayList list = new ArrayList();
            ArrayList list2 = new ArrayList(5);
            ArrayList list3 = new ArrayList("abc", "def", "ghi");
            ArrayList list4 = new ArrayList(1, 2, 3);
            Date[] dates = new Date[] {
                             new Date("1/1/2006"),
                             new Date("1/1/2005") };

            Point p = new Point(0, 0);

            CustomDictionary cd = new CustomDictionary();
            CustomDictionary cd2 = new CustomDictionary("abc", 123, "def", true);

            object o1 = Script.CreateInstance(typeof(Test));

            Type type1 = typeof(Foo);
            object o2 = Script.CreateInstance(type1, 1, 2);
            object o3 = Script.CreateInstance(typeof(Bar), 1, 2, (Foo)o2);

            Function f1 = new Function("alert('hello');");
            Function f2 = new Function("alert(s);", "s");
            Function f3 = new Function("alert(greeting + ' ' + name + '!');", "greeting", "name");
        }
 protected override VCExpr GenCastTypeAxioms(Function castToU, Function castFromU) {
   //Contract.Requires(castFromU != null);
   //Contract.Requires(castToU != null);
   Contract.Ensures(Contract.Result<VCExpr>() != null);
   // nothing
   return VCExpressionGenerator.True;
 }
Exemple #27
0
        public static double[] RungeKutta4(Function[] f, double[] x0, double t0, double dt)
        {
            int n = x0.Length;
            double[] k1 = new double[n];
            double[] k2 = new double[n];
            double[] k3 = new double[n];
            double[] k4 = new double[n];

            double t = t0;
            double[] x1 = new double[n];
            double[] x = x0;

            for (int i = 0; i < n; i++)
            {
                k1[i] = dt * f[i](x, t);
            }
            for (int i = 0; i < n; i++)
            {
                x1[i] = x[i] + k1[i] / 2;
            }
            for (int i = 0; i < n; i++)
            {
                k2[i] = dt * f[i](x1, t + dt / 2);
            }
            for (int i = 0; i < n; i++)
            {
                x1[i] = x[i] + k2[i] / 2;
            }
            for (int i = 0; i < n; i++)
            {
                k3[i] = dt * f[i](x1, t + dt / 2);
            }
            for (int i = 0; i < n; i++)
            {
                x1[i] = x[i] + k3[i];
            }
            for (int i = 0; i < n; i++)
            {
                k4[i] = dt * f[i](x1, t + dt);
            }
            for (int i = 0; i < n; i++)
            {
                x[i] += (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]) / 6;
            }

            return x;
        }
        public FunctionOperation(Function function, IConstruct[] arguments)
        {
            if (function == null)
                throw new ArgumentNullException();

            this.function = function;
            this.arguments = arguments;
        }
Exemple #29
0
 internal virtual string GetFunctionName(Function Function)
 {
     switch (Function)
     {
         case Function.Count: return "COUNT";
         default: throw new NotSupportedException($"The given function (`{Function.ToString()}`) is not supporthed in the surrent context.");
     }
 }
        internal SetFunctionImportSprocCommand(FunctionImport functionImport, Function function)
        {
            CommandValidation.ValidateFunctionImport(functionImport);
            CommandValidation.ValidateFunction(function);

            _functionImport = functionImport;
            _function = function;
        }