public async Task DerivativeWithCustomFunctionsReturnsCorectValue()
        {
            //arrange
            double CustomFunc(double x)
            {
                return(x * x * x);
            }

            var customFuncStr          = @"
            static double CustomFunc(double x)
            {
                return x * x * x;
            }
";
            Func <double, double> func = x => 1 - x - CustomFunc(x);
            var funcStr = "1 - x - CustomFunc(x)";

            var  point   = 3;
            uint order   = 1;
            var  epsilon = 1e-6;

            // Act
            var response = await _client.GetAsync($@"/api/numerical-calculations/derivative/{Uri.EscapeDataString(Strings.centered_five_point_method)}/{funcStr}/{point}/{order}/{epsilon}/{Uri.EscapeDataString(customFuncStr)}");

            var responseString = await response.Content.ReadAsStringAsync();

            // Assert
            response.EnsureSuccessStatusCode();
            var mathString = Derivative.centeredFivePointMethod(func, point, order, epsilon).ToMathString();

            Assert.AreEqual(mathString, responseString);
        }
        private void ComputeDerivative()
        {
            var derData = Derivative.GetRawValues();
            var outData = ForwardOutput.GetRawValues();

            Parallel.For(0, sampleNumber, sampleIndex =>
            {
                var outStart = ForwardOutput.GetRawOffset(sampleIndex, 0);
                Parallel.For(0, categoryNumber, i =>
                {
                    var derStart = Derivative.GetRawOffset(sampleIndex, i, 0);
                    for (int j = 0; j < categoryNumber; j++)
                    {
                        if (i == j)
                        {
                            derData[derStart + j] = outData[(int)(outStart + i)] * (1 - outData[(int)(outStart + j)]);
                        }
                        else
                        {
                            derData[derStart + j] = -outData[(int)(outStart + i)] * outData[(int)(outStart + j)];
                        }
                    }
                });
            });
        }
示例#3
0
        protected virtual Vector2d GetThirdDerivative(int key, double dt)
        {
            UnaryFunction fdx = Derivative.Central(tt => this.GetPosition(key, tt).X, 3, 5);
            UnaryFunction fdy = Derivative.Central(tt => this.GetPosition(key, tt).Y, 3, 5);

            return(new Vector2d(fdx(dt), fdy(dt)));
        }
示例#4
0
 private Dictionary<int, double[]> GetImgDerivative(double[] img, int width, int height)
 {
     var result = new Dictionary<int, double[]>();
     double range = 0.1;
     int rowIndex = 0;
     for (int j = 0; j < height - 2; j++)
     {
         for (int i = 0; i < width - 2; i++)
         {
             int centerIndex = rowIndex + width + i + 1;
             double value = img[centerIndex];
             if (value > range)
             {
                 Derivative d = new Derivative(img, rowIndex + i, width);
                 if (Math.Abs(d.X) > range || Math.Abs(d.Y) > range)
                 {
                     var r = new double[AutocorMatrixLength];
                     r[0] = d.X * d.X * value;
                     r[1] = r[2] = d.X * d.Y * value;
                     r[3] = d.Y * d.Y * value;
                     if (r.Count(a => Math.Abs(a) > range) > 0)
                         result.Add(centerIndex, r);
                 }
             }
         }
         rowIndex += width;
     }
     return result;
 }
示例#5
0
        private void InitializeGrid()
        {
            var d = _equation.d;
            var a = _equation.a;
            var b = _equation.b;
            var c = _equation.c;

            var tau = _params.TimeLimit / _params.TimeStepCount;
            Func <double, double> p1 = (x) => _conditions.InitialCondition(x, 0);
            Func <double, double> p2 = (x) => _conditions.DerivativeCondition(x, 0);
            var firstDerivative      = Derivative.FindByFunction(p1, 1, _params.SpaceBoundLeft, _params.SpaceBoundRight, _params.SpaceStepCount);
            var secondDerivative     = Derivative.FindByFunction(p1, 2, _params.SpaceBoundLeft, _params.SpaceBoundRight, _params.SpaceStepCount);

            for (int i = 0; i <= _params.SpaceStepCount; i++)
            {
                var x = GetSpaceCoordinate(i);
                _grid[i, 0] = p1(x);

                switch (_params.InitialApproximation)
                {
                case InitialApproximationType.FirstDegree:
                    _grid[i, 1] = p1(x) + p2(x) * tau;
                    break;

                case InitialApproximationType.SecondDegree:
                    _grid[i, 1] = p1(x) + p2(x) * tau
                                  + tau * tau / 2 * (a * secondDerivative[i] + b * firstDerivative[i] + c * p1(x) + _equation.f(x, 0) - d * p2(x));
                    break;
                }
            }
        }
示例#6
0
        public async Task <ActionResult> MapOxoDerivative(ImportExceptionParameters parameters)
        {
            var filter = ImportQueueFilter.FromExceptionId(parameters.ExceptionId.GetValueOrDefault());

            var derivative = Derivative.FromIdentifier(parameters.DerivativeCode);
            var importView = await GetModelFromParameters(parameters);

            var importDerivatives = (IEnumerable <string>)TempData["MapOxoDerivative"];

            foreach (var importDerivative in importDerivatives)
            {
                var derivativeMapping = new FdpDerivativeMapping()
                {
                    ImportDerivativeCode = importDerivative,
                    DocumentId           = parameters.DocumentId.GetValueOrDefault(),
                    ProgrammeId          = parameters.ProgrammeId.GetValueOrDefault(),
                    Gateway        = parameters.Gateway,
                    DerivativeCode = derivative.DerivativeCode,
                    BodyId         = derivative.BodyId.GetValueOrDefault(),
                    EngineId       = derivative.EngineId.GetValueOrDefault(),
                    TransmissionId = derivative.TransmissionId.GetValueOrDefault()
                };

                await DataContext.Import.MapDerivative(filter, derivativeMapping);
            }
            await DeactivateException(importView.CurrentException);
            await ReProcessException(importView.CurrentException);

            return(Json(JsonActionResult.GetSuccess(), JsonRequestBehavior.AllowGet));
        }
示例#7
0
        public double MethodSplains(double h)
        {
            double       sum1   = 0;
            double       sum2   = 0;
            List <Point> points = new List <Point>();

            for (double i = a; i < b; i += h)
            {
                points.Add(new Point(i, GetFunctionValue(i)));
            }
            Derivative derivative = new Derivative(points);

            for (double i = a; i <= b; i += h)
            {
                if (i == b)
                {
                    break;
                }
                sum1 += (GetFunctionValue(i) + GetFunctionValue(i + h)) * h;
                sum2 += derivative.CubicInterpolationMethod(3).DerivativePoints.IndexOf(new Point(i, GetFunctionValue(i + h))) * Math.Pow(h, 3);
            }
            sum1 *= 0.5;
            sum2 *= 1 / 12;
            double result = sum1 - sum2;

            return(result);
        }
示例#8
0
        public virtual Vec2d GetSecondDerivative(double t)
        {
            UnaryFunction fdx = Derivative.Central(tt => this.GetPosition(tt).X, 2, 5);
            UnaryFunction fdy = Derivative.Central(tt => this.GetPosition(tt).Y, 2, 5);

            return(new Vec2d(fdx(t), fdy(t)));
        }
示例#9
0
        public async Task <ActionResult> MapMissingDerivative(ImportExceptionParameters parameters)
        {
            var filter     = ImportQueueFilter.FromExceptionId(parameters.ExceptionId.GetValueOrDefault());
            var derivative = Derivative.FromIdentifier(parameters.DerivativeCode);
            var importView = await GetModelFromParameters(parameters);

            //var derivative = importView.AvailableDerivatives
            //    .First(d => d.DerivativeCode.Equals(parameters.DerivativeCode, StringComparison.InvariantCultureIgnoreCase));

            var derivativeMapping = new FdpDerivativeMapping()
            {
                ImportDerivativeCode = parameters.ImportDerivativeCode,

                DocumentId     = parameters.DocumentId.GetValueOrDefault(),
                ProgrammeId    = parameters.ProgrammeId.GetValueOrDefault(),
                Gateway        = parameters.Gateway,
                DerivativeCode = derivative.DerivativeCode,
                BodyId         = derivative.BodyId.GetValueOrDefault(),
                EngineId       = derivative.EngineId.GetValueOrDefault(),
                TransmissionId = derivative.TransmissionId.GetValueOrDefault()
            };

            importView.CurrentException = await DataContext.Import.MapDerivative(filter, derivativeMapping);
            await DeactivateException(importView.CurrentException);
            await ReProcessException(importView.CurrentException);

            return(Json(JsonActionResult.GetSuccess(), JsonRequestBehavior.AllowGet));
        }
示例#10
0
        protected virtual Vec2d GetFirstDerivative(int index, double t)
        {
            UnaryFunction fdx = Derivative.Central(tt => this.GetPosition(index, tt).X, 1, 5);
            UnaryFunction fdy = Derivative.Central(tt => this.GetPosition(index, tt).Y, 1, 5);

            return(new Vec2d(fdx(t), fdy(t)));
        }
示例#11
0
        static void lab4()
        {
            var derivative = new Derivative(Fi4, Xi4);

            Console.WriteLine(derivative.First(X4));
            Console.WriteLine(derivative.Second(X4));
        }
示例#12
0
        public void Deriv()
        {
            var simp     = new Derivative(new Add(new Number(2), new Number(3)));
            var expected = new Derivative(new Number(5));

            SimpleTest(simp, expected);
        }
示例#13
0
        public List <Point> TaylorsRow(int degree, double area, double areaLimit, double step)
        {
            List <Point> resultPoints = new List <Point>();
            List <Point> values       = new List <Point>();

            for (double i = area - areaLimit; i <= area + areaLimit; i += step)
            {
                values.Add(new Point(i, GetFunctionValue(i)));
            }

            Derivative der = new Derivative(values);

            for (int i = 0; i < values.Count - 2 * degree; i++)
            {
                double sum = 0;
                for (int j = 0; j <= degree; j++)
                {
                    if (j == 0)
                    {
                        sum = values[i].Y;
                    }
                    else
                    {
                        sum += der.QuadraticInterpolation(j).DerivativePoints[i].Y;
                    }
                }
                resultPoints.Add(new Point(values[i].X, sum));
            }

            return(resultPoints);
        }
示例#14
0
        public void CloneTest()
        {
            var exp   = new Derivative(new Sin(new Variable("x")), new Variable("x"), new Number(1));
            var clone = exp.Clone();

            Assert.Equal(exp, clone);
        }
示例#15
0
        public void CloneTest()
        {
            var exp   = new Derivative(null, null, new Sin(Variable.X), Variable.X, new Number(1));
            var clone = exp.Clone();

            Assert.Equal(exp, clone);
        }
示例#16
0
        public void TestDerivException()
        {
            var diff = new Differentiator();
            var simp = new Simplifier();
            var exp  = new Derivative(diff, simp, new IExpression[] { Variable.X, new Number(1) });

            TestException(exp);
        }
示例#17
0
        public void TestDerivNumber()
        {
            var diff = new Differentiator();
            var simp = new Simplifier();
            var exp  = new Derivative(diff, simp, Variable.X, Variable.X, new Number(2));

            Test(exp, ResultType.Number);
        }
示例#18
0
        public void TestDerivExpressionWithVar()
        {
            var diff = new Differentiator();
            var simp = new Simplifier();
            var exp  = new Derivative(diff, simp, Variable.X, Variable.X);

            Test(exp, ResultType.Expression);
        }
示例#19
0
        public void TestPartial(double[] arr, int index, double expected)
        {
            Derivative = new Derivative(TypicalMultivariateFunction);
            var vector = new Vector(arr);
            var got    = Derivative.GetPartialDerivative(vector, index);

            Assert.AreEqual(expected, got);
        }
示例#20
0
        public virtual Vec2d GetThirdDerivative(double t)
        {
            throw new NotImplementedException();
            UnaryFunction fdx = Derivative.Central(tt => this.GetPosition(tt).X, 3, 5);
            UnaryFunction fdy = Derivative.Central(tt => this.GetPosition(tt).Y, 3, 5);

            return(new Vec2d(fdx(t), fdy(t)));
        }
示例#21
0
        public void TestSecondDerivative(double point, double expected)
        {
            Derivative = new Derivative(TypicalFunction);
            var got = Derivative.GetSecondDerivative(point);

            // delta подбирается эмпирическим путём
            Assert.AreEqual(expected, got, delta: 1E-06);
        }
示例#22
0
        public void Derive_ComplexConstant_Returns0()
        {
            Environment environment = new Environment();
            SyntaxNode  node        = Parser.ParseExpression("(2 * 2) + 4 ^ 2 - 5 / 5", environment);
            Expression  expression  = new Expression(node, environment);
            Derivative  derivative  = new Derivative(expression, "x");

            Assert.AreEqual(derivative.Derive().ToString(), "0");
        }
示例#23
0
        public void Deriv()
        {
            var diff     = new Differentiator();
            var simpl    = new Simplifier();
            var simp     = new Derivative(diff, simpl, new Add(new Number(2), new Number(3)));
            var expected = new Derivative(diff, simpl, new Number(5));

            SimpleTest(simp, expected);
        }
        public void DiffInjectTest()
        {
            var deriv = new Derivative(Variable.X, Variable.X);

            resolver.Resolve(deriv);

            Assert.NotNull(deriv.Differentiator);
            Assert.Equal(this.differentiator, deriv.Differentiator);
        }
示例#25
0
        public void TestGradient(double[] arr, double[] expected)
        {
            Derivative = new Derivative(TypicalMultivariateFunction);
            var vector   = new Vector(arr);
            var gradient = Derivative.GetGradient(vector);
            var got      = gradient.Items;

            Assert.AreEqual(expected, got);
        }
示例#26
0
 public RelativisticParticle(Symbol mass, EuclideanVector3 position, Variable time)
 {
     this.Mass = mass;
     this.Position = new LorentzVectorU(time, position);
     Operator dt = new Derivative(time);
     EuclideanVector3 v = dt * position;
     this.Gamma = LorentzTransform.Gamma(v);
     this.Velocity = this.Gamma * new LorentzVectorU(Symbol.One, v);
     this.InvariantTimeDerivative = this.Gamma * dt;
 }
 /// <summary>
 /// Расчет производных
 /// </summary>
 private void InitDerivatives()
 {
     if (Alfa1B != null && Alfa1F != null && H != null)
     {
         Derivative1 = Derivative.GetDerivativeOperator1D3P_Derivative1((decimal)Alfa1B,
                                                                        (decimal)Alfa1F, (decimal)H);
         Derivative2 = Derivative.GetDerivativeOperator1D3P_Derivative2((decimal)Alfa1B,
                                                                        (decimal)Alfa1F, (decimal)H);
     }
 }
示例#28
0
        public double GetTangentModulus(double ratio)
        {
            double stress = ratio * SoilModel.GetFailureStress();
            var    solver = new NewtonSolver(x => SoilModel.GetDeviatoricStress(x) - stress, 0);
            double eps    = solver.Solve();

            var derivative = new Derivative(x => SoilModel.GetDeviatoricStress(x), DerivativeAccuracy);

            return(derivative.GetFirstDerivative(eps));
        }
示例#29
0
    public IntegrateDataPoint(Point p)
    {
        evalResult = new Derivative();
        a          = new Derivative();
        b          = new Derivative();
        c          = new Derivative();
        d          = new Derivative();

        this.p = p;
    }
示例#30
0
        private Derivative Evaluate(ref State initial, ref Derivative d, double dt)
        {
            var state = new State {
                x = initial.x + d.dx * dt, v = initial.v + d.dv * dt
            };

            return(new Derivative {
                dx = initial.v + d.dv * dt, dv = Acceleration(ref state)
            });
        }
示例#31
0
        /// <summary>
        /// Computes the unit tangent vector to the curve at point t
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public Double2 TangentAt(double t)
        {
            var d = Derivative.At(t);

            if (DoubleUtils.RoughlyZero(d))
            {
                return(Derivative.TangentAt(t));
            }
            return(d.Normalized);
        }
示例#32
0
        private Derivative Evaluate( StateModel initial, double dt, Derivative d, double dampK, double dampB )
        {
            StateModel state;
              state.a = initial.a + (d.da * dt);
              state.v = initial.v + (d.dv * dt);

              Derivative output = new Derivative( );
              output.da = state.v;
              output.dv = Acceleration( state, dampK, dampB );
              return output;
        }
示例#33
0
文件: MP.cs 项目: babaq/Soul
 public MP(string name, Point3D position, IHillock hillock, double initpotential, double startT)
 {
     id = Guid.NewGuid();
     this.name = name;
     this.position = position;
     synapses = new Dictionary<Guid, ISynapse>();
     currentsources = new Dictionary<Guid, ICurrentSource>();
     this.hillock = hillock;
     this.hillock.HostNeuron = this;
     this.initpotential = initpotential;
     ReSet(startT);
     parentnetwork = null;
     dynamicrule = null;
     type = NeuronType.MP;
 }
示例#34
0
    public void updateParticle(float dt, SandParticle[] otherParticles, int aliveParticles) {
        // Update forces
        if (applyForce) {
            Fl = forceHit;
            applyForce = false;
        } else {
            Fl.Set(0, 0, 0);
        }

        // Integrate Velocities (Runge Kutta)
        a = evaluate(position, linearMomentum, angMomentum, 0, new Derivative());
        b = evaluate(position, linearMomentum, angMomentum, dt * 0.5f, a);
        c = evaluate(position, linearMomentum, angMomentum, dt * 0.5f, b);
        d = evaluate(position, linearMomentum, angMomentum, dt, c);

        position = position + ((1.0f / 6.0f) * (a.dx + 2.0f * (b.dx + c.dx) + d.dx)) * dt;
        rotation = addQuaToQua(rotation, multiplyQuaByScalar((angVelocityQua * rotation), 0.5f * dt));

        // collision and stuff        
        collision(dt, otherParticles, aliveParticles);

        // Momentum
        linearMomentum = linearMomentum + ((1.0f / 6.0f) * (a.dm + 2.0f * (b.dm + c.dm) + d.dm)) * dt;
        //if (linearMomentum.magnitude < 0.001)
            //linearMomentum.Set(0, 0, 0);

        angMomentum = angMomentum + ((1.0f / 6.0f) * (a.dam + 2.0f * (b.dam + c.dam) + d.dam)) * dt;
        //if (angMomentum.magnitude < 0.001)
            //angMomentum.Set(0, 0, 0);        

        // Velocity
        linearVelocity = linearMomentum / mass;
        angVelocity = Vector3.Scale(new Vector3(1.0f / inertiaTensor.x, 1.0f / inertiaTensor.y, 1.0f / inertiaTensor.z), angMomentum);
        angVelocityQua = new Quaternion(angVelocity.x, angVelocity.y, angVelocity.z, 0);

        // Natural Roll ?
        naturalRoll = (Mathf.Abs(linearVelocity.magnitude - (radius * angVelocity.magnitude)) < 0.1);
    }
示例#35
0
	// Update is called once per frame
	void Update () {
        float dt = 0.003f;
        particles = GameObject.Find("GameObject").GetComponent<ParticleSystem>().partEmit.particles;
        int aliveParticles = GameObject.Find("GameObject").GetComponent<ParticleSystem>().currentParticles;

        Fl.Set(0, 0, 0);

        // Integrate Velocities (Runge Kutta)
        a = evaluate(transform.position, linearMomentum, angMomentum, 0, new Derivative());
        b = evaluate(transform.position, linearMomentum, angMomentum, dt * 0.5f, a);
        c = evaluate(transform.position, linearMomentum, angMomentum, dt * 0.5f, b);
        d = evaluate(transform.position, linearMomentum, angMomentum, dt, c);

        transform.position = transform.position + ((1.0f / 6.0f) * (a.dx + 2.0f * (b.dx + c.dx) + d.dx)) * dt;
        transform.rotation = addQuaToQua(transform.rotation, multiplyQuaByScalar((angVelocityQua * transform.rotation), 0.5f * dt));

        // collision and stuff        
        collision(dt, particles, aliveParticles);

        // Momentum
        linearMomentum = linearMomentum + ((1.0f / 6.0f) * (a.dm + 2.0f * (b.dm + c.dm) + d.dm)) * dt;
        //if (linearMomentum.magnitude < 0.001)
        //linearMomentum.Set(0, 0, 0);

        angMomentum = angMomentum + ((1.0f / 6.0f) * (a.dam + 2.0f * (b.dam + c.dam) + d.dam)) * dt;
        //if (angMomentum.magnitude < 0.001)
        //angMomentum.Set(0, 0, 0);        

        // Velocity
        linearVelocity = linearMomentum / mass;
        angVelocity = Vector3.Scale(new Vector3(1.0f / inertiaTensor.x, 1.0f / inertiaTensor.y, 1.0f / inertiaTensor.z), angMomentum);
        angVelocityQua = new Quaternion(angVelocity.x, angVelocity.y, angVelocity.z, 0);

        // Natural Roll ?
        naturalRoll = (Mathf.Abs(linearVelocity.magnitude - (radius * angVelocity.magnitude)) < 0.1);
    }
示例#36
0
    Derivative evaluate(Vector3 initialPos, Vector3 initialMomentum, Vector3 initialAngMomentum, float dt, Derivative d)
    {
        Vector3 newPos = initialPos + d.dx * dt;
        Vector3 newMomentum = initialMomentum + d.dm * dt;
        Vector3 newAngMomentum = initialAngMomentum + d.dam * dt;

        Vector3 newVel = newMomentum / mass;
        Vector3 newAngVel = Vector3.Scale(new Vector3(1.0f / inertiaTensor.x, 1.0f / inertiaTensor.y, 1.0f / inertiaTensor.z), newAngMomentum);

        Derivative output = new Derivative();
        output.dx = newVel;
        output.dm = force(newVel);
        output.dam = torque(newVel);

        return output;
    }
示例#37
0
 internal void AddDerivation(Derivative der)
 {
     parseContext.ElementScope.Derivations.Add(der);
 }