Пример #1
0
        static void Main(string[] args)
        {
            // create function factory for arctangent
            var arctan = UnaryFunc.Factory(
                x => Math.Atan(x),      // evaluate
                x => 1 / (1 + x * x));  // derivative of atan

            // create function factory for atan2
            var atan2 = BinaryFunc.Factory(
                (x, y) => Math.Atan2(y, x),
                (x, y) => Tuple.Create(
                    -y / (x * x + y * y),  // d/dx (from wikipedia)
                    x / (x * x + y * y))); // d/dy (from wikipedia)


            // define variables
            var u = new Variable();
            var v = new Variable();
            var w = new Variable();

            // create and compile a term
            var term     = atan2(u, v) - arctan(w) * atan2(v, w);
            var compiled = term.Compile(u, v, w);

            // compute value + gradient
            var diff = compiled.Differentiate(1, 2, -2);

            Console.WriteLine("The value at (1, 2, -2) is {0}", diff.Item2);
            Console.WriteLine("The gradient at (1, 2, -2) is ({0}, {1}, {2})",
                              diff.Item1[0],
                              diff.Item1[1],
                              diff.Item1[2]);
        }
Пример #2
0
        /// <summary>
        /// Creates a new basic generic operations implementation using the given expression generator.
        /// </summary>
        /// <param name="expressionGenerator">The expression generator that will be used to build the generic methods at run-time.</param>
        public BasicOperations(IExpressionGenerator expressionGenerator)
        {
            if (null == expressionGenerator)
            {
                throw new ArgumentNullException("expressionGenerator");
            }
            Contract.EndContractBlock();
            ExpressionGenerator = expressionGenerator;

            Add      = BuildBinaryFunc("Add");
            Subtract = BuildBinaryFunc("Subtract");
            Multiply = BuildBinaryFunc("Multiply");
            Divide   = BuildBinaryFunc("Divide");
            Negate   = BuildUnaryFunc("Negate");
            Sin      = BuildUnaryFunc("Sin");
            Cos      = BuildUnaryFunc("Cos");
            Tan      = BuildUnaryFunc("Tan");
            Asin     = BuildUnaryFunc("Asin");
            Acos     = BuildUnaryFunc("Acos");
            Atan     = BuildUnaryFunc("Atan");
            Sinh     = BuildUnaryFunc("Sinh");
            Cosh     = BuildUnaryFunc("Cosh");
            Tanh     = BuildUnaryFunc("Tanh");
            Asinh    = BuildUnaryFunc("Asinh");
            Acosh    = BuildUnaryFunc("Acosh");
            Atanh    = BuildUnaryFunc("Atanh");
            Log      = BuildUnaryFunc("Log");
            Log10    = BuildUnaryFunc("Log10");
            Exp      = BuildUnaryFunc("Exp");
            Abs      = BuildUnaryFunc("Abs");
            Atan2    = BuildBinaryFunc <ReverseCoordinates, TValue>("Atan2");
            Pow      = BuildBinaryFunc("Pow");
            Ceiling  = BuildUnaryFunc("Ceiling");
            Floor    = BuildUnaryFunc("Floor");
            Truncate = BuildUnaryFunc("Truncate");
            Min      = BuildBinaryFunc("Min");
            Max      = BuildBinaryFunc("Max");

            Equal          = BuildBinaryFunc <ComparisonTest, bool>("Equal");
            NotEqual       = BuildBinaryFunc <ComparisonTest, bool>("NotEqual");
            Less           = BuildBinaryFunc <ComparisonTest, bool>("Less");
            LessOrEqual    = BuildBinaryFunc <ComparisonTest, bool>("LessEqual");
            Greater        = BuildBinaryFunc <ComparisonTest, bool>("Greater");
            GreaterOrEqual = BuildBinaryFunc <ComparisonTest, bool>("GreaterOrEqual");
            CompareTo      = BuildBinaryFunc <Comparison <TValue>, int>("CompareTo");

            ToDouble            = BuildConversion <TValue, double>();
            FromDouble          = BuildConversion <double, TValue>();
            _zeroValueGenerator = BuildConstant("0");
        }
Пример #3
0
            public SubstitutionResult Visit(BinaryFunc func)
            {
                var leftResult  = func.Left.Accept(this);
                var rightResult = func.Right.Accept(this);

                double leftValue, rightValue;

                if (TryGetConstant(leftResult, out leftValue) && TryGetConstant(rightResult, out rightValue))
                {
                    return(CreateResult(func.Eval(leftValue, rightValue)));
                }
                else
                {
                    return(CreateResult(new BinaryFunc(func.Eval, func.Diff, leftResult.Term, rightResult.Term)));
                }
            }
        public void TestBinaryFuncSimple()
        {
            var v    = Vec(new Variable(), new Variable());
            var func = BinaryFunc.Factory(
                (x, y) => x * x - x * y,
                (x, y) => Tuple.Create(2 * x - y, -x));

            var term = func(v[0], v[1]);

            var y1 = term.Evaluate(v, NumVec(1, 0)); // 1 - 0 = 1
            var y2 = term.Evaluate(v, NumVec(0, 1)); // 0 - 0 = 0
            var y3 = term.Evaluate(v, NumVec(1, 2)); // 1 - 2 = -1

            Assert.Equal(1.0, y1);
            Assert.Equal(0.0, y2);
            Assert.Equal(-1.0, y3);
        }
        public void TestBinaryFuncComplex()
        {
            var v    = Vec(new Variable(), new Variable());
            var func = BinaryFunc.Factory(
                (x, y) => x * x - x * y,
                (x, y) => Tuple.Create(2 * x - y, -x));

            // f(x, y) = x² - xy - y² + xy = x² - y²
            var term = func(v[0], v[1]) - func(v[1], v[0]);

            var y1 = term.Evaluate(v, NumVec(1, 0)); // 1 - 0 = 1
            var y2 = term.Evaluate(v, NumVec(0, 1)); // 0 - 1 = -1
            var y3 = term.Evaluate(v, NumVec(2, 1)); // 4 - 1 = 3

            Assert.Equal(1.0, y1);
            Assert.Equal(-1.0, y2);
            Assert.Equal(3.0, y3);
        }
        public void DiffBinaryComplex()
        {
            var v    = Vec(new Variable(), new Variable());
            var func = BinaryFunc.Factory(
                (x, y) => x * x - x * y,
                (x, y) => Tuple.Create(2 * x - y, -x));

            // f(x, y) = x² - xy - y² + xy = x² - y²
            // df/dx = 2x
            // df/dy = -2y
            var term = func(v[0], v[1]) - func(v[1], v[0]);

            var y1 = term.Differentiate(v, Vec(1.0, 0.0)); // (2, 0)
            var y2 = term.Differentiate(v, Vec(0.0, 1.0)); // (0, -2)
            var y3 = term.Differentiate(v, Vec(2.0, 1.0)); // (4, -2)

            Assert.Equal(Vec(2.0, 0.0), y1);
            Assert.Equal(Vec(0.0, -2.0), y2);
            Assert.Equal(Vec(4.0, -2.0), y3);
        }
        public void DiffBinarySimple()
        {
            var v    = Vec(new Variable(), new Variable());
            var func = BinaryFunc.Factory(
                (x, y) => x * x - x * y,
                (x, y) => Tuple.Create(2 * x - y, -x));

            // f(x, y) = x² - xy
            // df/dx = 2x - y
            // df/dy = -x
            var term = func(v[0], v[1]);

            var y1 = term.Differentiate(v, Vec(1.0, 0.0)); // (2, -1)
            var y2 = term.Differentiate(v, Vec(0.0, 1.0)); // (-1, 0)
            var y3 = term.Differentiate(v, Vec(1.0, 2.0)); // (0, -1)

            Assert.Equal(Vec(2.0, -1.0), y1);
            Assert.Equal(Vec(-1.0, 0.0), y2);
            Assert.Equal(Vec(0.0, -1.0), y3);
        }
Пример #8
0
        public List <Node> AStarPath(Node start, Node goal, BinaryFunc costFunc, BinaryFunc heuristicFunc)
        {
            List <Node> openSet = new List <Node>();

            openSet.Add(start);

            Dictionary <Node, Node> cameFrom = new Dictionary <Node, Node>();

            Dictionary <Node, float> gScore = new Dictionary <Node, float>();

            gScore[start] = 0;

            Dictionary <Node, float> fScore = new Dictionary <Node, float>();

            fScore[start] = heuristicFunc(start, goal);

            while (openSet.Count > 0)
            {
                Node  current  = null;
                float minScore = Mathf.Infinity;
                foreach (var n in openSet)
                {
                    if (fScore[n] < minScore)
                    {
                        current  = n;
                        minScore = fScore[n];
                    }
                }

                if (current == goal)
                {
                    List <Node> path = new List <Node>();
                    path.Add(current);
                    while (cameFrom.ContainsKey(current))
                    {
                        current = cameFrom[current];
                        path.Insert(0, current);
                    }
                    return(path);
                }

                openSet.Remove(current);
                foreach (var neighbor in _neighbors[current])
                {
                    if (!gScore.ContainsKey(neighbor))
                    {
                        gScore[neighbor] = Mathf.Infinity;
                    }
                    if (!fScore.ContainsKey(neighbor))
                    {
                        fScore[neighbor] = Mathf.Infinity;
                    }
                    float tgScore = gScore[current] + costFunc(current, neighbor);
                    if (tgScore < gScore[neighbor])
                    {
                        cameFrom[neighbor] = current;
                        gScore[neighbor]   = tgScore;
                        fScore[neighbor]   = tgScore + heuristicFunc(neighbor, goal);
                        if (!openSet.Contains(neighbor))
                        {
                            openSet.Add(neighbor);
                        }
                    }
                }
            }

            return(null);
        }