public void AssociatedLaguerreOrthonormality() { // don't let orders get too big, or (1) the Gamma function will overflow and (2) our integral will become highly oscilatory foreach (int n in TestUtilities.GenerateIntegerValues(1, 10, 3)) { foreach (int m in TestUtilities.GenerateIntegerValues(1, 10, 3)) { foreach (double a in TestUtilities.GenerateRealValues(0.1, 10.0, 5)) { //int n = 2; //int m = 4; //double a = 3.5; Console.WriteLine("n={0} m={1} a={2}", n, m, a); // evaluate the orthonormal integral Func <double, double> f = delegate(double x) { return(Math.Pow(x, a) * Math.Exp(-x) * OrthogonalPolynomials.LaguerreL(m, a, x) * OrthogonalPolynomials.LaguerreL(n, a, x) ); }; Interval r = Interval.FromEndpoints(0.0, Double.PositiveInfinity); // need to loosen default evaluation settings in order to get convergence in some of these cases // seems to have most convergence problems for large a EvaluationSettings e = new EvaluationSettings(); e.AbsolutePrecision = TestUtilities.TargetPrecision; e.RelativePrecision = TestUtilities.TargetPrecision; double I = FunctionMath.Integrate(f, r, e).Value; Console.WriteLine(I); // test for orthonormality if (n == m) { Assert.IsTrue(TestUtilities.IsNearlyEqual( I, AdvancedMath.Gamma(n + a + 1) / AdvancedIntegerMath.Factorial(n) )); } else { Assert.IsTrue(Math.Abs(I) < TestUtilities.TargetPrecision); } } } } }
public void OdeOrbitKepler() { // This is a simple Keplerian orbit. // Hull (1972) constructed initial conditions that guarantee a given orbital eccentricity // and a period of 2 \pi with unit masses and unit gravitational constant. Func <double, IReadOnlyList <double>, IReadOnlyList <double> > rhs = (double t, IReadOnlyList <double> r) => { double d = MoreMath.Hypot(r[0], r[1]); double d3 = MoreMath.Pow(d, 3); return(new double[] { -r[0] / d3, -r[1] / d3 }); }; foreach (double e in new double[] { 0.0, 0.1, 0.3, 0.5, 0.7, 0.9 }) { ColumnVector r0 = new ColumnVector(1.0 - e, 0.0); ColumnVector rDot0 = new ColumnVector(0.0, Math.Sqrt((1.0 + e) / (1.0 - e))); double E = OrbitEnergy(r0, rDot0); double L = OrbitAngularMomentum(r0, rDot0); MultiOdeSettings settings = new MultiOdeSettings() { Listener = (MultiOdeResult b) => { Assert.IsTrue(TestUtilities.IsNearlyEqual(OrbitAngularMomentum(b.Y, b.YPrime), L, b.Settings)); EvaluationSettings relaxed = new EvaluationSettings() { RelativePrecision = 2.0 * b.Settings.RelativePrecision, AbsolutePrecision = 2.0 * b.Settings.AbsolutePrecision }; Assert.IsTrue(TestUtilities.IsNearlyEqual(OrbitEnergy(b.Y, b.YPrime), E, relaxed)); } }; MultiOdeResult result = MultiFunctionMath.IntegrateConservativeOde(rhs, 0.0, r0, rDot0, 2.0 * Math.PI, settings); ColumnVector r1 = result.Y; Console.WriteLine(result.EvaluationCount); Assert.IsTrue(TestUtilities.IsNearlyEqual(r0, r1, new EvaluationSettings() { RelativePrecision = 512 * result.Settings.RelativePrecision })); // For large eccentricities, we loose precision. This is apparently typical behavior. // Would be nice if we could quantify expected loss, or correct to do better. } }
public void GetEvaluationSettings_Both() { try { RequestContext.SetContext(null, null, null, "Japan/Tokyo"); CalculatedFieldSettings calcSettings = new CalculatedFieldSettings(); calcSettings.TimeZone = "Australia/Brisbane"; EvaluationSettings evalSettings = CalculatedFieldProvider.CreateEvaluationSettings(calcSettings); Assert.That(evalSettings.TimeZoneName, Is.EqualTo("Australia/Brisbane")); } finally { RequestContext.FreeContext(); } }
public void ThomsonLocal() { for (int n = 2; n < 8; n++) { Console.WriteLine(n); // define the thompson metric Func <IList <double>, double> f = GetThompsonFunction(n); // random distribution to start // using antipodal pairs gives us a better starting configuration Random r = new Random(1001110000); double[] start = new double[2 * (n - 1)]; for (int i = 0; i < (n - 1) / 2; i++) { int j = 4 * i; start[j] = -Math.PI + 2.0 * r.NextDouble() * Math.PI; start[j + 1] = Math.Asin(2.0 * r.NextDouble() - 1.0); start[j + 2] = -(Math.PI - start[j]); start[j + 3] = -start[j + 1]; } // add one more point if necessary if (n % 2 == 0) { start[2 * n - 4] = -Math.PI + 2.0 * r.NextDouble() * Math.PI; start[2 * n - 3] = Math.Asin(2.0 * r.NextDouble() - 1.0); } EvaluationSettings set = new EvaluationSettings() { RelativePrecision = 1.0E-9 }; MultiExtremum min = MultiFunctionMath.FindLocalMinimum(f, start, set); Console.WriteLine(min.Dimension); Console.WriteLine(min.EvaluationCount); Console.WriteLine("{0} ({1}) ?= {2}", min.Value, min.Precision, thompsonSolutions[n]); Assert.IsTrue(min.Dimension == 2 * (n - 1)); Assert.IsTrue(TestUtilities.IsNearlyEqual(min.Value, thompsonSolutions[n], new EvaluationSettings() { AbsolutePrecision = 4.0 * min.Precision })); } }
public static bool IsSumNearlyEqual(IEnumerable <double> xs, double y, EvaluationSettings settings) { double sum = 0.0; double norm = 0.0; foreach (double x in xs) { sum += x; norm += Math.Abs(x); } if (Double.IsNaN(sum) && Double.IsNaN(y)) { return(true); } double tol = settings.AbsolutePrecision + settings.RelativePrecision * norm; return(Math.Abs(sum - y) <= tol); }
public void Test_CountFromParam_26597(string script, int expect) { // Schema string typeName = Guid.NewGuid().ToString(); EntityType type = new EntityType(); type.Name = typeName; type.Save(); EntityType type2 = new EntityType(); type2.Name = typeName + "B"; type2.Save(); Relationship rel = new Relationship(); rel.Cardinality_Enum = CardinalityEnum_Enumeration.ManyToMany; rel.FromType = type; rel.ToType = type2; rel.ToName = "Risk"; rel.Save(); // Instance Resource instance = Entity.Create(type.Id).As <Resource>(); instance.Name = "TestInstance"; instance.Save(); // Compile BuilderSettings settings = new BuilderSettings(); settings.ParameterNames = new List <string> { "Input" }; settings.StaticParameterResolver = param => ExprTypeHelper.EntityListOfType(new EntityRef(type.Id)); IExpression expr = Factory.ExpressionCompiler.Compile(script, settings); // Run EvaluationSettings eval = new EvaluationSettings(); eval.ParameterResolver = param => instance; var result = Factory.ExpressionRunner.Run(expr, eval); // Check Assert.That(result.Value, Is.EqualTo(expect)); }
public static bool IsNearlyEqual(double x, double y, EvaluationSettings s) { if (Double.IsPositiveInfinity(x) && Double.IsPositiveInfinity(y)) { return(true); } if (Double.IsNegativeInfinity(x) && Double.IsNegativeInfinity(y)) { return(true); } if (Double.IsNaN(x) && Double.IsNaN(y)) { return(true); } double norm = Math.Abs(x) + Math.Abs(y); double tol = Math.Max(0.0, s.AbsolutePrecision) + norm * Math.Max(0.0, s.RelativePrecision); return(Math.Abs(x - y) <= tol); }
public void SumOfPowers() { // This test is difficult because the minimum is emphatically not quadratic. // We do get close to the minimum but we massivly underestimate our error. Func <IList <double>, double> function = (IList <double> x) => { double s = 0.0; for (int i = 0; i < x.Count; i++) { s += MoreMath.Pow(Math.Abs(x[i]), i + 2); } return(s); }; for (int n = 2; n < 8; n++) { Console.WriteLine(n); ColumnVector start = new ColumnVector(n); for (int i = 0; i < n; i++) { start[i] = 1.0; } EvaluationSettings settings = new EvaluationSettings() { AbsolutePrecision = 1.0E-8, EvaluationBudget = 32 * n * n * n }; MultiExtremum minimum = MultiFunctionMath.FindLocalMinimum(function, start, settings); Console.WriteLine(minimum.EvaluationCount); Console.WriteLine("{0} {1}", minimum.Value, minimum.Precision); Console.WriteLine("|| {0} {1} ... || = {2}", minimum.Location[0], minimum.Location[1], minimum.Location.FrobeniusNorm()); Assert.IsTrue(TestUtilities.IsNearlyEqual(minimum.Value, 0.0, new EvaluationSettings() { AbsolutePrecision = 1.0E-4 })); //Assert.IsTrue(TestUtilities.IsNearlyEqual(minimum.Location, new ColumnVector(n), new EvaluationSettings() { AbsolutePrecision = 1.0E-2 })); } }
/// <summary> /// Evaluates an expression tree. /// </summary> /// <param name="expression">The expression tree.</param> /// <param name="settings">Additional settings to be used in evaluation, such as the root context object, timezone info, etc.</param> /// <returns>The result of the evaluation.</returns> public ExpressionRunResult Run(IExpression expression, EvaluationSettings settings) { if (expression == null) { throw new ArgumentNullException("expression"); } if (settings == null) { throw new ArgumentNullException("settings"); } Expression expressionToRun = expression as Expression; if (expressionToRun == null) { throw new ArgumentException("Expected instance of type Expression.", "expression"); } if (expressionToRun.Root == null) { throw new ArgumentException("expression.Root"); } using (EntryPointContext.AppendEntryPoint("ExprRun")) using (Profiler.Measure("ExpressionEngine.Run")) { var evalContext = new EvaluationContext { Settings = settings, }; object result = expressionToRun.Evaluate(evalContext); var resultList = result as IEnumerable <IEntity>; if (resultList != null) { result = resultList.ToList( ); } ExpressionRunResult runResult = new ExpressionRunResult(result); return(runResult); } }
/// <summary> /// Given a text expression and runtimeArgs, evaluate the expression. /// Expressions must be compatible with DataColumn.Expression. the result is cast to T /// </summary> internal static object EvaluateExpressionImpl(WfExpression wfExpression, IRunState context, IDictionary <string, Resource> knownEntities) { var expression = context.Metadata.CompiledExpressionCache[wfExpression.Id]; if (expression == null) { return(GetKnownEntities(wfExpression, knownEntities)); } else { // Evaluate the expression var eSettings = new EvaluationSettings(); eSettings.TimeZoneName = TimeZoneHelper.SydneyTimeZoneName; // TODO: Workflow engine to provide a timezone to run in. Required for date-time functions. eSettings.ParameterResolver = paramName => context.ResolveParameterValue(paramName, knownEntities); // used for runtime parameters object result = Factory.ExpressionRunner.Run(expression, eSettings).Value; return(CoerceToListIfNeeded(wfExpression, result)); } }
public void RunCalculatedFieldFromEvalHost() { // Ensure a workflow can access a calculated field. // Create scenario EntityType type = new EntityType(); type.Name = "Test" + Guid.NewGuid().ToString(); Field field = new StringField().As <Field>(); field.Name = "MyCalcField"; field.FieldCalculation = "Name + 'hello'"; field.IsCalculatedField = true; type.Fields.Add(field); type.Save(); Resource inst = Entity.Create(type.Id).As <Resource>(); inst.Name = "TestName"; inst.Save(); var script = "MyCalcField"; BuilderSettings settings = new BuilderSettings { RootContextType = new ExprType { Type = DataType.Entity, EntityType = new EntityRef(type.Id) }, ScriptHost = ScriptHostType.Evaluate }; IExpression expr = Factory.ExpressionCompiler.Compile(script, settings); EvaluationSettings evalSettings = new EvaluationSettings(); evalSettings.ContextEntity = inst; evalSettings.TimeZoneName = "Australia/Sydney"; var runResult = Factory.ExpressionRunner.Run(expr, evalSettings); Assert.That(runResult.Value, Is.EqualTo("TestNamehello")); }
public void OdeDawson() { // The Dawson function fulfills a simple ODE. // \frac{dF}{dx} + 2 x F = 1 \qquad F(0) = 0 // See e.g. https://en.wikipedia.org/wiki/Dawson_function // Verify that we get correct values via ODE integration. Func <double, double, double> rhs = (double x, double F) => 1.0 - 2.0 * x * F; foreach (double x1 in TestUtilities.GenerateRealValues(0.1, 10.0, 8)) { EvaluationSettings s = new EvaluationSettings() { RelativePrecision = 1.0E-13, AbsolutePrecision = 0.0 }; OdeResult r = FunctionMath.IntegrateOde(rhs, 0.0, 0.0, x1); Debug.WriteLine("{0}: {1} {2}: {3}", x1, r.Y, AdvancedMath.Dawson(x1), r.EvaluationCount); Assert.IsTrue(TestUtilities.IsNearlyEqual(r.Y, AdvancedMath.Dawson(x1), s)); } }
public void MinimizePerturbedQuadratic2D() { EvaluationSettings s = new EvaluationSettings() { EvaluationBudget = 100, RelativePrecision = 1.0E-10 }; Func <IList <double>, double> f = (IList <double> x) => 1.0 + 2.0 * MoreMath.Sqr(x[0] - 3.0) + 4.0 * (x[0] - 3.0) * (x[1] - 5.0) + 6.0 * MoreMath.Sqr(x[1] - 5.0) + 7.0 * MoreMath.Pow(x[0] - 3.0, 4) + 8.0 * MoreMath.Pow(x[1] - 5.0, 4); MultiExtremum m = MultiFunctionMath.FindLocalMinimum(f, new double[] { 1.0, 1.0 }, s); Assert.IsTrue(m.EvaluationCount <= s.EvaluationBudget); Assert.IsTrue(m.Dimension == 2); Assert.IsTrue(TestUtilities.IsNearlyEqual(m.Value, 1.0, s)); Assert.IsTrue(TestUtilities.IsNearlyEqual(m.Location, new ColumnVector(3.0, 5.0), new EvaluationSettings() { RelativePrecision = Math.Sqrt(s.RelativePrecision) })); }
public void Griewank() { // See http://mathworld.wolfram.com/GriewankFunction.html for (int n = 2; n < 8; n++) { Console.WriteLine(n); Func <IList <double>, double> function = (IList <double> x) => { double s = 0.0; double p = 1.0; for (int i = 0; i < x.Count; i++) { s += MoreMath.Sqr(x[i]); p *= Math.Cos(x[i] / Math.Sqrt(i + 1.0)); } return(1.0 + s / 4000.0 - p); }; Interval[] box = new Interval[n]; for (int i = 0; i < n; i++) { box[i] = Interval.FromEndpoints(-100.0, 100.0); } EvaluationSettings settings = new EvaluationSettings() { AbsolutePrecision = 1.0E-6, EvaluationBudget = 1000000 }; MultiExtremum minimum = MultiFunctionMath.FindGlobalMinimum(function, box, settings); Console.WriteLine(minimum.Dimension); Console.WriteLine(minimum.EvaluationCount); Console.WriteLine("{0} ({1}) ?= 0.0", minimum.Value, minimum.Precision); Console.WriteLine("{0} {1} ...", minimum.Location[0], minimum.Location[1]); // We usually find the minimum at 0, but sometimes land a valley or two over. } }
public void WatsonIntegrals() { // Watson defined and analytically integrated three complicated triple integrals related to random walks in three dimension // See http://mathworld.wolfram.com/WatsonsTripleIntegrals.html // These integrals are difficult, so up the budget to about 1,000,000 and reduce the target accuracy to about 10^{-4} EvaluationSettings settings = new EvaluationSettings() { RelativePrecision = 1.0E-4, EvaluationBudget = 1000000 }; Interval watsonWidth = Interval.FromEndpoints(0.0, Math.PI); Interval[] watsonBox = new Interval[] { watsonWidth, watsonWidth, watsonWidth }; Assert.IsTrue( MultiFunctionMath.Integrate( (IList <double> x) => 1.0 / (1.0 - Math.Cos(x[0]) * Math.Cos(x[1]) * Math.Cos(x[2])), watsonBox, settings ).Estimate.ConfidenceInterval(0.99).ClosedContains( MoreMath.Pow(AdvancedMath.Gamma(1.0 / 4.0), 4) / 4.0 ) ); Assert.IsTrue( MultiFunctionMath.Integrate( (IList <double> x) => 1.0 / (3.0 - Math.Cos(x[0]) * Math.Cos(x[1]) - Math.Cos(x[1]) * Math.Cos(x[2]) - Math.Cos(x[0]) * Math.Cos(x[2])), watsonBox, settings ).Estimate.ConfidenceInterval(0.99).ClosedContains( 3.0 * MoreMath.Pow(AdvancedMath.Gamma(1.0 / 3.0), 6) / Math.Pow(2.0, 14.0 / 3.0) / Math.PI ) ); Assert.IsTrue( MultiFunctionMath.Integrate( (IList <double> x) => 1.0 / (3.0 - Math.Cos(x[0]) - Math.Cos(x[1]) - Math.Cos(x[2])), watsonBox, settings ).Estimate.ConfidenceInterval(0.99).ClosedContains( Math.Sqrt(6.0) / 96.0 * AdvancedMath.Gamma(1.0 / 24.0) * AdvancedMath.Gamma(5.0 / 24.0) * AdvancedMath.Gamma(7.0 / 24.0) * AdvancedMath.Gamma(11.0 / 24.0) ) ); }
/// <summary> /// Create an evaluation-settings object. /// </summary> /// <remarks> /// The settings object will be reused for all entities requested in this iteration. /// The context entity will be set in each time. /// </remarks> internal static EvaluationSettings CreateEvaluationSettings(CalculatedFieldSettings settings) { EvaluationSettings evalSettings = new EvaluationSettings(); evalSettings.TimeZoneName = settings.TimeZone; if (evalSettings.TimeZoneName == null) { var requestContext = RequestContext.GetContext(); if (requestContext != null) { evalSettings.TimeZoneName = requestContext.TimeZone; } if (evalSettings.TimeZoneName == null) { throw new InvalidOperationException("TimeZone information must be provided in settings object, or via RequestContext."); } } return(evalSettings); }
public double VIXfuture_LogNormal(double T, Func <double, double> epsilon) { //For Integrale calculation EvaluationSettings settings = new EvaluationSettings(); settings.AbsolutePrecision = 1.0E-5; settings.RelativePrecision = 0.0; //Grid On [O,T] Grid grid = new Grid(0, T, 1000); // Variance Calcul Func <double, double> f = s => Math.Pow(Math.Pow(T - s + Delta, H + 0.5) - Math.Pow(T - s, H + 0.5), 2); IntegrationResult integr_f = FunctionMath.Integrate(f, Meta.Numerics.Interval.FromEndpoints(0.0, T), settings); double var = (4 * Math.Pow(vi * Ch, 2)) / (Math.Pow(Delta * (H + 0.5), 2)) * integr_f.Value; IntegrationResult integr_epsilon = FunctionMath.Integrate(epsilon, Meta.Numerics.Interval.FromEndpoints(T, T + Delta), settings); //LogNormal Solution APproximation return(Math.Pow(Delta, -0.5) * Math.Sqrt(integr_epsilon.Value) * Math.Exp(-var / 8)); }
public void OdeEuler() { // Euler's equations for rigid body motion (without external forces) are // I_1 \dot{\omega}_1 = (I_2 - I_3) \omega_2 \omega_3 // I_2 \dot{\omega}_2 = (I_3 - I_1) \omega_3 \omega_1 // I_3 \dot{\omega}_3 = (I_1 - I_2) \omega_1 \omega_2 // where \omega's are rotations about the principal axes and I's are the moments // of inertia about those axes. The rotational kinetic energy // I_1 \omega_1^2 + I_2 \omega_2^2 + I_3 \omega_3^2 = 2E // and angular momentum // I_1^2 \omega_1^2 + I_2^2 \omega_2^2 + I_3^2 \omega_3^2 = M^2 // are conserved quantities. ColumnVector I = new ColumnVector(1.0, 2.0, 3.0); Func <double, IList <double>, IList <double> > rhs = (double t, IList <double> w) => { return(new ColumnVector((I[1] - I[2]) * w[1] * w[2] / I[0], (I[2] - I[0]) * w[2] * w[0] / I[1], (I[0] - I[1]) * w[0] * w[1] / I[2])); }; ColumnVector w0 = new ColumnVector(1.0, 1.0, 1.0); double eps = 1.0E-12; EvaluationSettings settings = new EvaluationSettings() { RelativePrecision = eps, AbsolutePrecision = eps * eps, EvaluationBudget = 10000 }; settings.UpdateHandler = (EvaluationResult r) => { OdeResult <IList <double> > q = (OdeResult <IList <double> >)r; Console.WriteLine("{0} {1}", q.EvaluationCount, q.X); Assert.IsTrue(TestUtilities.IsNearlyEqual(EulerKineticEnergy(I, q.Y), EulerKineticEnergy(I, w0), settings)); Assert.IsTrue(TestUtilities.IsNearlyEqual(EulerAngularMomentum(I, q.Y), EulerAngularMomentum(I, w0), settings)); }; MultiFunctionMath.SolveOde(rhs, 0.0, w0, 10.0, settings); }
public void IsingIntegrals() { // See http://www.davidhbailey.com/dhbpapers/ising.pdf. EvaluationSettings settings = new EvaluationSettings() { RelativePrecision = 1.0E-3, EvaluationBudget = 1000000 }; int d = 4; Interval[] volume = new Interval[d]; for (int i = 0; i < volume.Length; i++) { volume[i] = Interval.FromEndpoints(0.0, Double.PositiveInfinity); } IntegrationResult r = MultiFunctionMath.Integrate((IList <double> x) => { double p = 1.0; double q = 0.0; for (int i = 0; i < x.Count; i++) { double u = x[i]; double v = 1.0 / u; q += (u + v); p *= v; } return(p / MoreMath.Sqr(q)); }, volume, settings); double c = 4.0 / AdvancedIntegerMath.Factorial(d); Console.WriteLine("{0} {1}", c * r.Estimate, r.EvaluationCount); Console.WriteLine(7.0 * AdvancedMath.RiemannZeta(3.0) / 12.0); Assert.IsTrue((c * r.Estimate).ConfidenceInterval(0.99).ClosedContains(7.0 * AdvancedMath.RiemannZeta(3.0) / 12.0)); }
/// <summary> /// Get all instances of the requested type. /// </summary> /// <param name="context">The context, such as the parent entity, from which these entities are being loaded.</param> /// <returns>List of entities.</returns> public override IEnumerable <DataElement> GetData(WriterContext context) { EvaluationSettings settings = new EvaluationSettings { ContextEntity = context.CurrentEntity, TimeZoneName = context.Settings.TimeZoneName }; ExpressionRunResult result = context.ExternalServices.ExpressionRunner.Run(Expression, settings); IEnumerable <IEntity> instances; if (result.Value == null) { instances = Enumerable.Empty <IEntity>(); } else { instances = result.Value as IEnumerable <IEntity>; if (instances == null) { IEntity instance = result.Value as IEntity; if (instance != null) { instances = new[] { instance } } ; else { throw new Exception("Expected result to be list of entities."); } // assert false, the cast step should ensure this, or have thrown a ParseException } } return(instances.Select((entity, pos) => new DataElement(entity, pos))); }
/// <summary> /// Runs the expression. /// </summary> /// <param name="compiledExpression">The compile result.</param> /// <param name="contextEntity">The context entity.</param> /// <returns></returns> /// <exception cref="InvalidOperationException"> /// TimeZone information must be provided in settings object, or via /// RequestContext. /// </exception> private string RunExpression(IExpression compiledExpression, IEntity contextEntity) { var evaluationSettings = new EvaluationSettings { ContextEntity = contextEntity }; var requestContext = RequestContext.GetContext(); if (requestContext != null) { evaluationSettings.TimeZoneName = requestContext.TimeZone; } if (evaluationSettings.TimeZoneName == null) { throw new InvalidOperationException( "TimeZone information must be provided in settings object, or via RequestContext."); } var result = Factory.ExpressionRunner.Run(compiledExpression, evaluationSettings).Value; return(result?.ToString() ?? string.Empty); }
public void PackCirclesInSquare() { // Put n points into the unit square. Place them so as to maximize the minimum distance between them. // See http://en.wikipedia.org/wiki/Circle_packing_in_a_square, http://hydra.nat.uni-magdeburg.de/packing/csq/csq.html // This is a great test problem because it is simple to understand, hard to solve, // solutions are known/proven for many n, and it covers many dimensions. double[] solutions = new double[] { Double.NaN, Double.NaN, Math.Sqrt(2.0), /* at opposite corners */ Math.Sqrt(6.0) - Math.Sqrt(2.0), 1.0, /* at each corner */ Math.Sqrt(2.0) / 2.0 /* at each corner and in center */, Math.Sqrt(13.0) / 6.0, 4.0 - 2.0 * Math.Sqrt(3.0), (Math.Sqrt(6.0) - Math.Sqrt(2.0)) / 2.0, 1.0 / 2.0, /* 3 X 3 grid */ 0.421279543983903432768821760651, 0.398207310236844165221512929748, Math.Sqrt(34.0) / 15.0, 0.366096007696425085295389370603, 2.0 / (4.0 + Math.Sqrt(3.0)), 2.0 / (Math.Sqrt(6.0) + 2.0 + Math.Sqrt(2.0)), 1.0 / 3.0 }; //int n = 11; for (int n = 2; n < 8; n++) { Console.WriteLine("n={0}", n); Func <IList <double>, double> function = (IList <double> x) => { // Intrepret coordinates as (x_1, y_1, x_2, y_2, \cdots, x_n, y_n) // Iterate over all pairs of points, finding smallest distance betwen any pair of points. double sMin = Double.MaxValue; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { double s = MoreMath.Hypot(x[2 * i] - x[2 * j], x[2 * i + 1] - x[2 * j + 1]); if (s < sMin) { sMin = s; } } } return(sMin); }; IList <Interval> box = new Interval[2 * n]; for (int i = 0; i < box.Count; i++) { box[i] = Interval.FromEndpoints(0.0, 1.0); } EvaluationSettings settings = new EvaluationSettings() { RelativePrecision = 1.0E-4, AbsolutePrecision = 1.0E-6, EvaluationBudget = 10000000 }; MultiExtremum maximum = MultiFunctionMath.FindGlobalMaximum(function, box, settings); Console.WriteLine(maximum.EvaluationCount); Console.WriteLine("{0} {1}", solutions[n], maximum.Value); Assert.IsTrue(maximum.Dimension == 2 * n); Assert.IsTrue(TestUtilities.IsNearlyEqual(maximum.Value, solutions[n], new EvaluationSettings() { AbsolutePrecision = 2.0 * maximum.Precision })); } }
//<summary> //Carga el datasource del gridview evaluacion deacuerdo a al actor seleccionado //</summary> //<param name="objevaluacion"></param> protected void CargarPreguntas(EvaluationSettings.CEvaluacion objevaluacion) { try { #region Cargar Preguntas Ambientes List<IQueryable<ESM.Model.Pregunta>> cpreguntas = new List<IQueryable<Model.Pregunta>>(); cpreguntas = objevaluacion.LoadEvaluation(); int contador = 0; for (int p = 0; p < cpreguntas.Count; p++) { GridView objGridView = (GridView)this.pnlEvaluacion.FindControl(String.Format("gvAmb{0}", p + 1)); //Llama al metodo load del objeto CEvaluacion que obtiene el Iqueryable para asignar al datasource del control objGridView.DataSource = cpreguntas[p]; //Actualizo el control Gridview en el formulario para que almacene los cambio realizados objGridView.DataBind(); //Asigna el tema para los griviews ObtenerTema(objGridView); for (int i = 0; i < objGridView.Rows.Count; i++) { Label objlabel = (Label)objGridView.Rows[i].FindControl("lblIdPregunta"); TextBox objtextbox = (TextBox)objGridView.Rows[i].FindControl("txtsesion" + objlabel.Text); CheckBox objcheckbox = (CheckBox)objGridView.Rows[i].FindControl("chxPendiente" + objlabel.Text); Label objlabelLP = (Label)objGridView.Rows[i].FindControl("lblLP"); HtmlAnchor objlknayuda = (HtmlAnchor)objGridView.Rows[i].FindControl("lknAyuda"); RadioButton objsi = (RadioButton)objGridView.Rows[i].FindControl("rbtnSi"); RadioButton objno = (RadioButton)objGridView.Rows[i].FindControl("rbtnNo"); int idPregunta = Convert.ToInt32(objlabel.Text); foreach (var item in cpreguntas[p]) { if (item.IdPregunta == idPregunta) { if (item.Sesiones != null) { if ((bool)item.Sesiones) { objtextbox.Visible = true; objtextbox.Enabled = false; } } ESM.Model.AyudaByPregunta objAyudaByPregunta = _objevaluacion.ObtenerAyudaPregunta(item.IdPregunta); if ((bool)objAyudaByPregunta.Lectura && (bool)objAyudaByPregunta.Participacion) { objlabelLP.Text = "LP"; objlabelLP.Visible = true; objcheckbox.Visible = true; } else if ((bool)objAyudaByPregunta.Lectura) { objlabelLP.Text = "L"; objlabelLP.Visible = true; } else if ((bool)objAyudaByPregunta.Participacion) { objlabelLP.Text = "P"; objlabelLP.Visible = true; } else objlabelLP.Visible = false; if (item.Ocultar != null) { if ((bool)item.Ocultar == true) { objtextbox.Visible = false; objcheckbox.Visible = false; objsi.Visible = false; objno.Visible = false; objlknayuda.Visible = false; objlabelLP.Visible = false; } } } } } contador++; } #endregion activa_timer.Value = "1"; } /*En caso de presentar excepcion retorno una alerta en javascript que me muestra y me controla el error presentado*/ catch (Exception) { Response.Write("<script>alert('Ocurrio un error inesperado.');</script>"); } }
public double VIXfuture_TruncatedChlsky(double T, Func <double, double> epsilon) { DateTime start = DateTime.Now; //StreamWriter sw = new StreamWriter("C:\\Users\\Marouane\\Desktop\\M2IF\\rough volatility\\rBergomiFile.txt"); //Grid int N = 100; int S = 7; Grid grid = new Grid(T, T + Delta, N); #region Correlation "Correl Matrix Construction" // Small Covariance Matrix t_0 , ... , t_7 SymmetricMatrix covM_Small = new SymmetricMatrix(S); //the full Covariance Matrix SymmetricMatrix covM = new SymmetricMatrix(N + 1); //Setting for integrale approximations EvaluationSettings settings = new EvaluationSettings(); settings.AbsolutePrecision = 1.0E-7; settings.RelativePrecision = 0.0; // Small Covariance Calcul t_0,.....,t_7 for (int i = 0; i < S; i++) { covM_Small[i, i] = (Math.Pow(grid.t(i), 2 * H) - Math.Pow(grid.t(i) - T, 2 * H)) / (2 * H); for (int j = 0; j < i; j++) { Func <double, double> covfunc = t => Math.Pow((grid.t(j) - t) * (grid.t(i) - t), H - 0.5); IntegrationResult integresult = FunctionMath.Integrate(covfunc, Meta.Numerics.Interval.FromEndpoints(0.0, T), settings); covM_Small[i, j] = integresult.Value; } } // full COrrelation Calcul for (int i = 0; i <= N; i++) { covM[i, i] = (Math.Pow(grid.t(i), 2 * H) - Math.Pow(grid.t(i) - T, 2 * H)) / (2 * H); for (int j = 0; j < i; j++) { Func <double, double> covfunc = t => Math.Pow((grid.t(j) - t) * (grid.t(i) - t), H - 0.5); IntegrationResult integresult = FunctionMath.Integrate(covfunc, Meta.Numerics.Interval.FromEndpoints(0.0, T), settings); covM[i, j] = integresult.Value; } } Func <int, int, double> corrf_Small = (i, j) => covM_Small[i, j] / (Math.Sqrt(covM_Small[i, i] * covM_Small[j, j])); SymmetricMatrix Correl_Small = new SymmetricMatrix(S); Correl_Small.Fill(corrf_Small); Func <int, int, double> corrf = (i, j) => covM[i, j] / (Math.Sqrt(covM[i, i] * covM[j, j])); SymmetricMatrix Correl = new SymmetricMatrix(N + 1); Correl.Fill(corrf); #endregion CholeskyDecomposition cholesky = Correl_Small.CholeskyDecomposition(); SquareMatrix choleskyCorrel_Small = new SquareMatrix(S); choleskyCorrel_Small = cholesky.SquareRootMatrix(); GaussianSimulator simulator = new GaussianSimulator(); double VIX = 0.0; var MC = 1.0E5; for (int mc = 1; mc < MC; mc++) { ColumnVector GaussianVector = new ColumnVector(S); // Simulating Volterra at 8 first steps on [T, T+Delta] for (int i = 0; i < S; i++) { GaussianVector[i] = simulator.Next(); } ColumnVector Volterra_small = choleskyCorrel_Small * GaussianVector; //Adjusting the variance of Volterra Processus for (int i = 0; i < S; i++) { Volterra_small[i] = Volterra_small[i] * Math.Sqrt((Math.Pow(grid.t(i), 2 * H) - Math.Pow(grid.t(i) - grid.t(0), 2 * H)) / (2 * H)); } // Simulating VOlterra on t_8 ... t_N with the truncated Formula double[] Volterra = new double[N + 1]; for (int i = 0; i <= N; i++) { if (i < S) { Volterra[i] = Volterra_small[i]; } //Tranceted Formula else { Volterra[i] = Math.Sqrt(covM[i, i]) * (Correl[i, i - 1] * Volterra[i - 1] / Math.Sqrt(covM[i - 1, i - 1]) + Math.Sqrt(1 - Math.Pow(Correl[i, i - 1], 2)) * simulator.Next()); } } double VIX_ = VIX_Calculate(epsilon, grid, Volterra); VIX += VIX_; } //sw.Close(); VIX /= MC; TimeSpan dur = DateTime.Now - start; return(VIX); }
/// <summary> /// Inners the eval. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> private static EvalResult InnerEval(EvalRequest request) { try { var settings = new BuilderSettings( ); if (!string.IsNullOrEmpty(request.Context)) { long typeId; EntityRef contextType = long.TryParse(request.Context, out typeId) ? new EntityRef(typeId) : new EntityRef(request.Context); settings.RootContextType = ExprTypeHelper.EntityOfType(contextType); } if (!string.IsNullOrEmpty(request.Host)) { settings.ScriptHost = ( ScriptHostType )Enum.Parse(typeof(ScriptHostType), request.Host); } var paramTypes = new Dictionary <string, ExprType>( ); var paramValues = new Dictionary <string, object>( ); if (request.Parameters != null) { foreach (ExpressionParameter p in request.Parameters) { var type = ( DataType )Enum.Parse(typeof(DataType), p.TypeName); if (type == DataType.Entity) { long typeId; paramTypes[p.Name] = long.TryParse(p.EntityTypeId, out typeId) ? ExprTypeHelper.EntityOfType(new EntityRef(typeId)) : ExprTypeHelper.EntityOfType(new EntityRef(p.EntityTypeId)); } else { paramTypes[p.Name] = new ExprType(type); } paramTypes[p.Name].IsList = p.IsList; paramValues[p.Name] = DataTypeHelpers.StringToObject(p.StringValue, type); } settings.ParameterNames = paramTypes.Keys.ToList( ); settings.StaticParameterResolver = paramName => { ExprType result2; return(paramTypes.TryGetValue(paramName, out result2) ? result2 : null); }; } // Compile IExpression expression = Factory.ExpressionCompiler.Compile(request.Expression, settings); // used for runtime parameters EvaluationSettings evalSettings = new EvaluationSettings { TimeZoneName = TimeZoneHelper.SydneyTimeZoneName, ParameterResolver = paramName => { object result1; return(paramValues.TryGetValue(paramName, out result1) ? result1 : null); } }; object result = Factory.ExpressionRunner.Run(expression, evalSettings).Value; // Return success result return(new EvalResult { Value = result.ToString( ), ResultType = expression.ResultType.Type, IsList = expression.ResultType.IsList, EntityTypeId = expression.ResultType.EntityTypeId }); } catch (ParseException ex) { // Return script error result return(new EvalResult { ErrorMessage = ex.Message }); } }
public void DistributionProbabilityIntegral() { Random rng = new Random(4); // if integral is very small, we still want to get it very accurately EvaluationSettings settings = new EvaluationSettings(); settings.AbsolutePrecision = 0.0; foreach (Distribution distribution in distributions) { if (distribution is TriangularDistribution) { continue; } for (int i = 0; i < 3; i++) { double x; if (Double.IsNegativeInfinity(distribution.Support.LeftEndpoint) && Double.IsPositiveInfinity(distribution.Support.RightEndpoint)) { // pick an exponentially distributed random point with a random sign double y = rng.NextDouble(); x = -Math.Log(y); if (rng.NextDouble() < 0.5) { x = -x; } } else if (Double.IsPositiveInfinity(distribution.Support.RightEndpoint)) { // pick an exponentialy distributed random point double y = rng.NextDouble(); x = distribution.Support.LeftEndpoint - Math.Log(y); } else { // pick a random point within the support x = distribution.Support.LeftEndpoint + rng.NextDouble() * distribution.Support.Width; } Console.WriteLine("{0} {1}", distribution.GetType().Name, x); double P = FunctionMath.Integrate(distribution.ProbabilityDensity, Interval.FromEndpoints(distribution.Support.LeftEndpoint, x), settings).Value; double Q = FunctionMath.Integrate(distribution.ProbabilityDensity, Interval.FromEndpoints(x, distribution.Support.RightEndpoint), settings).Value; if (!TestUtilities.IsNearlyEqual(P + Q, 1.0)) { // the numerical integral for the triangular distribution can be innacurate, because // its locally low-polynomial behavior fools the integration routine into thinking it need // not integrate as much near the inflection point as it must; this is a problem // of the integration routine (or arguably the integral), not the triangular distribution, // so skip it here Console.WriteLine("skip (P={0}, Q={1})", P, Q); continue; } Console.WriteLine(" {0} v. {1}", P, distribution.LeftProbability(x)); Console.WriteLine(" {0} v. {1}", Q, distribution.RightProbability(x)); Assert.IsTrue(TestUtilities.IsNearlyEqual(P, distribution.LeftProbability(x))); Assert.IsTrue(TestUtilities.IsNearlyEqual(Q, distribution.RightProbability(x))); } } }
/// <summary> /// Get the calculated field value for the specified entities. /// </summary> /// <param name="fieldMetadata">The metadata for the calculated field.</param> /// <param name="entityIDs">Entities</param> /// <param name="evalSettings">Evaluation settings</param> /// <returns>List of results.</returns> private IReadOnlyCollection <CalculatedFieldSingleResult> GetSingleFieldValues(CalculatedFieldMetadata fieldMetadata, IReadOnlyCollection <long> entityIDs, EvaluationSettings evalSettings) { if (fieldMetadata == null) { throw new ArgumentNullException("fieldMetadata"); } if (entityIDs == null) { throw new ArgumentNullException("entityIDs"); } // Handle statically broken calculated-fields // (may be null due to not being a calculated field, or the script failing to compile) if (fieldMetadata.Expression == null) { // If the calculated field was somehow invalid, return null for values. return(entityIDs.Select(id => new CalculatedFieldSingleResult(id, null)).ToArray()); } // Load entities IReadOnlyCollection <IEntity> entities; entities = _entityRepository.Get(entityIDs); var results = new List <CalculatedFieldSingleResult>(entities.Count); // Perform calculations foreach (IEntity entity in entities) { ExpressionRunResult runResult; CalculatedFieldSingleResult singleResult; evalSettings.ContextEntity = entity; try { runResult = _expressionRunner.Run(fieldMetadata.Expression, evalSettings); singleResult = new CalculatedFieldSingleResult(entity.Id, runResult.Value); } catch (EvaluationException ex) { singleResult = new CalculatedFieldSingleResult(entity.Id, ex); } results.Add(singleResult); } return(results); }
public static bool IsNearlyEqual(AnyRectangularMatrix x, AnyRectangularMatrix y, EvaluationSettings s) { double m = x.FrobeniusNorm() + y.FrobeniusNorm(); double e = s.AbsolutePrecision + m * s.RelativePrecision; AnyRectangularMatrix D = x - y; return(D.FrobeniusNorm() <= e); }
public void DistributionCentralMomentIntegral() { foreach (Distribution distribution in distributions) { foreach (int n in TestUtilities.GenerateIntegerValues(2, 24, 8)) { // get the predicted central moment double C = distribution.MomentAboutMean(n); // don't try to integrate infinite moments if (Double.IsInfinity(C) || Double.IsNaN(C)) { continue; } if (C == 0.0) { continue; } EvaluationSettings settings = new EvaluationSettings(); if (C == 0.0) { // if moment is zero, use absolute precision settings.AbsolutePrecision = TestUtilities.TargetPrecision; settings.RelativePrecision = 0.0; } else { // if moment in non-zero, use relative precision settings.AbsolutePrecision = 0.0; settings.RelativePrecision = TestUtilities.TargetPrecision; } // do the integral double m = distribution.Mean; Func <double, double> f = delegate(double x) { return(distribution.ProbabilityDensity(x) * MoreMath.Pow(x - m, n)); }; try { double CI = FunctionMath.Integrate(f, distribution.Support, settings).Value; Console.WriteLine("{0} {1} {2} {3}", distribution.GetType().Name, n, C, CI); if (C == 0.0) { Assert.IsTrue(Math.Abs(CI) < TestUtilities.TargetPrecision); } else { double e = TestUtilities.TargetPrecision; // reduce required precision, because some distributions (e.g. Kolmogorov, Weibull) // have no analytic expressions for central moments, which must therefore be // determined via raw moments and are thus subject to cancelation error // can we revisit this later? if (distribution is WeibullDistribution) { e = Math.Sqrt(Math.Sqrt(e)); } if (distribution is KolmogorovDistribution) { e = Math.Sqrt(e); } if (distribution is KuiperDistribution) { e = Math.Sqrt(Math.Sqrt(e)); } if (distribution is TriangularDistribution) { e = Math.Sqrt(e); } Assert.IsTrue(TestUtilities.IsNearlyEqual(C, CI, e)); } } catch (NonconvergenceException) { Console.WriteLine("{0} {1} {2} {3}", distribution.GetType().Name, n, C, "NC"); // deal with these later; they are integration problems, not distribution problems } } } }