public void CompareWithOriginalDenseMatrix()
        {
            var sparseMatrix = new SparseMatrix(3);

            sparseMatrix[0, 0] = -1;
            sparseMatrix[0, 1] = 5;
            sparseMatrix[0, 2] = 6;
            sparseMatrix[1, 0] = 3;
            sparseMatrix[1, 1] = -6;
            sparseMatrix[1, 2] = 1;
            sparseMatrix[2, 0] = 6;
            sparseMatrix[2, 1] = 8;
            sparseMatrix[2, 2] = 9;
            var ilu = new IncompleteLU();

            ilu.Initialize(sparseMatrix);
            var original = GetLowerTriangle(ilu).Multiply(GetUpperTriangle(ilu));

            for (var i = 0; i < sparseMatrix.RowCount; i++)
            {
                for (var j = 0; j < sparseMatrix.ColumnCount; j++)
                {
                    Assert.IsTrue(sparseMatrix[i, j].AlmostEqual(original[i, j], -Epsilon.Magnitude()), "#01-" + i + "-" + j);
                }
            }
        }
示例#2
0
        public override void Activate()
        {
            Status = StatusTypes.Active;

            // if this goal is reactivated then there may be some existing subgoals that must be removed
            RemoveAllSubgoals();

            // it is possible for the target to die while this goal is active so we
            // must test to make sure the agent always has an active target
            if (Agent.TargetingSystem.IsTargetPresent)
            {
                // grab a local copy of the last recorded position (LRP) of the target
                var lrp = Agent.TargetingSystem.LastRecordedPosition;

                // if the agent has reached the LRP and it still hasn't found the target
                // it starts to search by using the explore goal to move to random
                // map locations
                if (Epsilon.IsZero(lrp) || Agent.IsAtPosition(lrp))
                {
                    AddSubgoal(new Explore(Agent));
                }

                // else move to the LRP
                else
                {
                    AddSubgoal(new MoveToPosition(Agent, lrp));
                }
            }

            // if there is no active target then this goal can be removed from the queue
            else
            {
                Status = StatusTypes.Completed;
            }
        }
示例#3
0
        public void bind_builder_types()
        {
            // Demonstrates that the builder indirection can be used

            PropertyTreeReader pt = LoadContent("epsilon-builder.xml");

            Assert.True(pt.Read());

            Epsilon e = pt.Bind <Epsilon>();

            Assert.True(e is EpsilonAlpha);
            Assert.Equal(256, e.A);
            Assert.Equal(TimeSpan.Parse("2.5:05:05.200"), e.B);
            Assert.Equal(2256.231250002, e.C);
            Assert.Equal(293680235, e.D);

            Assert.IsInstanceOf <EpsilonExtended>(e.E);

            EpsilonExtended f = (EpsilonExtended)e.E;

            Assert.Equal(1256, f.A);
            Assert.Equal(TimeSpan.Parse("12.5:05:05.200"), f.B);
            Assert.Equal(12256.231250002, f.C);
            Assert.Equal(1293680235, f.D);
            Assert.Equal(DateTime.Parse("2011-05-12 8:45AM"), f.F);
        }
示例#4
0
        /// <summary>
        ///     Returns the degree of membership in this set of the given value. This does not set
        ///     <see cref="FuzzySet._dom" /> to the degree of membership of the value passed as the
        ///     parameter. This is because the centroid defuzzification method also uses this method to
        ///     determine the DOMs of the values it uses as its sample points.
        /// </summary>
        /// <param name="givenValue">The given value.</param>
        /// <returns>
        ///     The degree of membership in this set of the given value.
        /// </returns>
        public override float CalculateDom(float givenValue)
        {
            // test for the case where the triangle's left or right offsets are
            // zero (to prevent divide by zero errors below)
            if (Epsilon.IsEqual(RightOffset, 0.0f) && Epsilon.IsEqual(PeakPoint, givenValue) ||
                Epsilon.IsEqual(LeftOffset, 0.0f) && Epsilon.IsEqual(PeakPoint, givenValue))
            {
                return(1.0f);
            }

            // find DOM if left of center
            if (givenValue <= PeakPoint && givenValue >= PeakPoint - LeftOffset)
            {
                var leftGrad = 1.0f / LeftOffset;
                return(leftGrad * (givenValue - (PeakPoint - LeftOffset)));
            }

            // find DOM if right of center
            if (!(givenValue > PeakPoint) || !(givenValue < PeakPoint + RightOffset))
            {
                return(0.0f);
            }
            var rightGrad = 1.0f / -RightOffset;

            return(rightGrad * (givenValue - PeakPoint) + 1.0f);

            // out of range of this FLV, return zero
        }
示例#5
0
        /// <summary>
        ///     Returns the degree of membership in this set of the given value. This does not set
        ///     <see cref="FuzzySet._dom" /> to the degree of membership of the value passed as the
        ///     parameter. This is because the centroid defuzzification method also uses this method to
        ///     determine the DOMs of the values it uses as its sample points.
        /// </summary>
        /// <param name="givenValue">The given value.</param>
        /// <returns>
        ///     The degree of membership in this set of the given value.
        /// </returns>
        public override float CalculateDom(float givenValue)
        {
            // test for the case where the left or right offsets are zero
            // (to prevent divide by zero errors below)
            if (Epsilon.IsEqual(RightOffset, 0.0f) && Epsilon.IsEqual(PeakPoint, givenValue) ||
                Epsilon.IsEqual(LeftOffset, 0.0f) && Epsilon.IsEqual(PeakPoint, givenValue))
            {
                return(1.0f);
            }

            // find DOM if left of center
            if (givenValue <= PeakPoint && givenValue > PeakPoint - LeftOffset)
            {
                var grad = 1.0f / LeftOffset;
                return(grad * (givenValue - (PeakPoint - LeftOffset)));
            }

            // find DOM if right of center and less than center + right offset
            if (givenValue > PeakPoint && givenValue <= PeakPoint + RightOffset)
            {
                return(1.0f);
            }

            // out of range of this FLV, return zero
            return(0f);
        }
示例#6
0
        public void IntersectsWithDomain()
        {
            FltDomain a  = new FltDomain(new double[] { 0, 10, 20, 30 });
            FltDomain a1 = new FltDomain(new double[] { -10, Epsilon.Prev(0), Epsilon.Next(10), Epsilon.Prev(20), Epsilon.Next(30), 40 });

            Assert.IsFalse(a.IntersectsWith(a1));
            Assert.IsFalse(a1.IntersectsWith(a));
        }
示例#7
0
        public void CompareWithOriginalDenseMatrixWithoutPivoting()
        {
            var sparseMatrix = new SparseMatrix(3);

            sparseMatrix[0, 0] = -1;
            sparseMatrix[0, 1] = 5;
            sparseMatrix[0, 2] = 6;
            sparseMatrix[1, 0] = 3;
            sparseMatrix[1, 1] = -6;
            sparseMatrix[1, 2] = 1;
            sparseMatrix[2, 0] = 6;
            sparseMatrix[2, 1] = 8;
            sparseMatrix[2, 2] = 9;
            var ilu = new ILUTPPreconditioner
            {
                PivotTolerance = 0.0,
                DropTolerance  = 0,
                FillLevel      = 10
            };

            ilu.Initialize(sparseMatrix);
            var l = GetLowerTriangle(ilu);

            // Assert l is lower triagonal
            for (var i = 0; i < l.RowCount; i++)
            {
                for (var j = i + 1; j < l.RowCount; j++)
                {
                    Assert.IsTrue(0.0.AlmostEqualNumbersBetween(l[i, j].Magnitude, -Epsilon.Magnitude()), "#01-" + i + "-" + j);
                }
            }

            var u = GetUpperTriangle(ilu);

            // Assert u is upper triagonal
            for (var i = 0; i < u.RowCount; i++)
            {
                for (var j = 0; j < i; j++)
                {
                    Assert.IsTrue(0.0.AlmostEqualNumbersBetween(u[i, j].Magnitude, -Epsilon.Magnitude()), "#02-" + i + "-" + j);
                }
            }

            var original = l.Multiply(u);

            for (var i = 0; i < sparseMatrix.RowCount; i++)
            {
                for (var j = 0; j < sparseMatrix.ColumnCount; j++)
                {
                    Assert.IsTrue(sparseMatrix[i, j].Real.AlmostEqualNumbersBetween(original[i, j].Real, -Epsilon.Magnitude()), "#03-" + i + "-" + j);
                    Assert.IsTrue(sparseMatrix[i, j].Imaginary.AlmostEqualNumbersBetween(original[i, j].Imaginary, -Epsilon.Magnitude()), "#04-" + i + "-" + j);
                }
            }
        }
示例#8
0
        public override void Update()
        {
            double min0 = Math.Min(Var0.Min, Epsilon.Prev(Var1.Min));
            double max0 = Math.Min(Var0.Max, Epsilon.Prev(Var1.Max));

            double min1 = Math.Max(Epsilon.Next(Var0.Min), Var1.Min);
            double max1 = Math.Max(Epsilon.Next(Var0.Max), Var1.Max);

            Var0.Intersect(min0, max0);
            Var1.Intersect(min1, max1);
        }
示例#9
0
        public void IntersectsWith4()
        {
            FltDomain a = new FltDomain(new double[] { 0, 15, 48, 63 });

            Assert.IsFalse(a.IntersectsWith(new FltInterval(-10, Epsilon.Prev(0))));
            Assert.IsFalse(a.IntersectsWith(new FltInterval(Epsilon.Next(15), Epsilon.Prev(48))));
            Assert.IsFalse(a.IntersectsWith(new FltInterval(Epsilon.Next(63), 80)));

            Assert.IsTrue(a.IntersectsWith(new FltInterval(15, Epsilon.Prev(48))));
            Assert.IsTrue(a.IntersectsWith(new FltInterval(Epsilon.Next(15), 48)));
        }
示例#10
0
        public void CompareWithOriginalDenseMatrixWithoutPivoting()
        {
            var sparseMatrix = new SparseMatrix(3);

            sparseMatrix[0, 0] = -1;
            sparseMatrix[0, 1] = 5;
            sparseMatrix[0, 2] = 6;
            sparseMatrix[1, 0] = 3;
            sparseMatrix[1, 1] = -6;
            sparseMatrix[1, 2] = 1;
            sparseMatrix[2, 0] = 6;
            sparseMatrix[2, 1] = 8;
            sparseMatrix[2, 2] = 9;
            var ilu = new Ilutp
            {
                PivotTolerance = 0.0,
                DropTolerance  = 0,
                FillLevel      = 10
            };

            ilu.Initialize(sparseMatrix);
            var l = GetLowerTriangle(ilu);

            // Assert l is lower triagonal
            for (var i = 0; i < l.RowCount; i++)
            {
                for (var j = i + 1; j < l.RowCount; j++)
                {
                    Assert.IsTrue(0.0.AlmostEqual(l[i, j], -Epsilon.Magnitude()), "#01-" + i + "-" + j);
                }
            }

            var u = GetUpperTriangle(ilu);

            // Assert u is upper triagonal
            for (var i = 0; i < u.RowCount; i++)
            {
                for (var j = 0; j < i; j++)
                {
                    Assert.IsTrue(0.0.AlmostEqual(u[i, j], -Epsilon.Magnitude()), "#02-" + i + "-" + j);
                }
            }

            var original = l.Multiply(u);

            for (var i = 0; i < sparseMatrix.RowCount; i++)
            {
                for (var j = 0; j < sparseMatrix.ColumnCount; j++)
                {
                    Assert.IsTrue(((double)sparseMatrix[i, j]).AlmostEqualInDecimalPlaces(original[i, j], 5), "#03-" + i + "-" + j);
                }
            }
        }
示例#11
0
        public FltInterval Difference(FltInterval interval)
        {
            if (interval.IsEmpty())
            {
                return(this);
            }

            if (IsEmpty())
            {
                return(this);
            }

            // 4 : cannot divide into two intervals...
            if ((interval.m_Min > m_Min) && (interval.m_Max < m_Max))
            {
                return(this);
            }

            // 1, 6 : completely before or after
            if ((interval.m_Max < m_Min) || (interval.m_Min > m_Max))
            {
                return(this);
            }

            // 3 : completely remove interval => empty
            if (interval.Contains(this))
            {
                return(m_Empty);
            }

            // 2 : left overlap
            if (IntersectsWith(interval) &&
                (interval.m_Max < m_Max))
            {
                double min = Epsilon.Next(interval.m_Max);
                double max = m_Max;

                return(new FltInterval(min, max));
            }

            // 5 : right overlap
            if (IntersectsWith(interval) &&
                (interval.m_Min > m_Min))
            {
                double min = m_Min;
                double max = Epsilon.Prev(interval.m_Min);

                return(new FltInterval(min, max));
            }

            return(m_Empty);
        }
示例#12
0
        public FltInterval Exp()
        {
            if (IsEmpty())
            {
                return(FltInterval.Empty);
            }

            // slightly enlarge interval
            double min = Epsilon.PrevOne(Math.Exp(m_Min));
            double max = Epsilon.NextOne(Math.Exp(m_Max));

            return(new FltInterval(min, max));
        }
        /// <summary>
        /// Check the result.
        /// </summary>
        /// <param name="preconditioner">Specific preconditioner.</param>
        /// <param name="matrix">Source matrix.</param>
        /// <param name="vector">Initial vector.</param>
        /// <param name="result">Result vector.</param>
        protected override void CheckResult(IPreConditioner preconditioner, SparseMatrix matrix, Vector <double> vector, Vector <double> result)
        {
            Assert.AreEqual(typeof(Diagonal), preconditioner.GetType(), "#01");

            // Compute M * result = product
            // compare vector and product. Should be equal
            var product = new DenseVector(result.Count);

            matrix.Multiply(result, product);
            for (var i = 0; i < product.Count; i++)
            {
                Assert.IsTrue(vector[i].AlmostEqual(product[i], -Epsilon.Magnitude()), "#02-" + i);
            }
        }
示例#14
0
        public void DifferenceInterval()
        {
            FltDomain a  = new FltDomain(new double[] { 0, 10, 20, 30 });
            FltDomain a1 = a.Difference(a.Interval);                                                                                                   Assert.AreEqual(FltDomain.Empty, a1);
            FltDomain a2 = a.Difference(new FltInterval(-10, Epsilon.Prev(0)));                                    Assert.AreEqual(a, a2);                      // 6
            FltDomain a3 = a.Difference(new FltInterval(Epsilon.Next(10), Epsilon.Prev(20)));    Assert.AreEqual(a, a3);                                        // 4
            FltDomain a4 = a.Difference(new FltInterval(Epsilon.Next(30), 40));                                    Assert.AreEqual(a, a4);                      // 1
            FltDomain a5 = a.Difference(new FltInterval(-10, 0));                                                                    AssertEqual(a5, new double[] { Epsilon.Next(0), 10, 20, 30 });

            FltDomain b  = new FltDomain(new double[] { 0, 30 });
            FltDomain b1 = b.Difference(new FltInterval(10, 20));            AssertEqual(b1, new FltInterval[] { new FltInterval(0, Epsilon.Prev(10)), new FltInterval(Epsilon.Next(20), 30) });
            FltDomain b2 = b.Difference(new FltInterval(-10, 10));           AssertEqual(b2, new FltInterval[] { new FltInterval(Epsilon.Next(10), 30) });
            FltDomain b3 = b.Difference(new FltInterval(20, 40));            AssertEqual(b3, new FltInterval[] { new FltInterval(0, Epsilon.Prev(20)) });
        }
        protected override void CheckResult(IPreConditioner <Complex> preconditioner, SparseMatrix matrix, Vector <Complex> vector, Vector <Complex> result)
        {
            Assert.AreEqual(typeof(Ilutp), preconditioner.GetType(), "#01");

            // Compute M * result = product
            // compare vector and product. Should be equal
            Vector <Complex> product = new DenseVector(result.Count);

            matrix.Multiply(result, product);
            for (var i = 0; i < product.Count; i++)
            {
                Assert.IsTrue(vector[i].Real.AlmostEqual(product[i].Real, -Epsilon.Magnitude()), "#02-" + i);
                Assert.IsTrue(vector[i].Imaginary.AlmostEqual(product[i].Imaginary, -Epsilon.Magnitude()), "#03-" + i);
            }
        }
示例#16
0
            private double calculateSinglePeriodAccrualOnDefault(int paymentIndex, PiecewiseconstantHazardRate creditCurve)
            {
                double[] knots = _premLegIntPoints[paymentIndex];
                if (knots == null)
                {
                    return(0.0);
                }
                double[] df       = _premDF[paymentIndex];
                double[] deltaT   = _premDt[paymentIndex];
                double[] rt       = _rt[paymentIndex];
                double   accRate  = _accRate[paymentIndex];
                double   accStart = _offsetAccStart[paymentIndex];

                double t   = knots[0];
                double ht0 = creditCurve.getRT_(t);
                double rt0 = rt[0];
                double b0  = df[0] * Math.Exp(-ht0);

                double t0     = t - accStart + _omega;
                double pv     = 0.0;
                int    nItems = knots.Length;

                for (int j = 1; j < nItems; ++j)
                {
                    t = knots[j];
                    double ht1 = creditCurve.getRT_(t);
                    double rt1 = rt[j];
                    double b1  = df[j] * Math.Exp(-ht1);
                    double dt  = deltaT[j - 1];

                    double dht  = ht1 - ht0;
                    double drt  = rt1 - rt0;
                    double dhrt = dht + drt + 1e-50; // to keep consistent with ISDA c code

                    double tPV;

                    if (Math.Abs(dhrt) < 1e-5)
                    {
                        tPV = dht * dt * b0 * Epsilon.epsilonP(-dhrt);
                    }
                    else
                    {
                        tPV = dht * dt / dhrt * ((b0 - b1) / dhrt - b1);
                    }
                }

                return(accRate * pv);
            }
示例#17
0
 public SweData(SEFLG iflag, DateTime dateTimeInUTC, EarthOrientationParameters eop, bool interpolateNutation = false)
 {
     Iflag                      = iflag;
     CalculationDate            = dateTimeInUTC;
     Eop                        = eop;
     InterpolateNutation        = interpolateNutation;
     CalculationJulianDayNumber = JulianDayNumber.FromDate(dateTimeInUTC);
     TidalAcc                   = TidalAcceleration.Get(TidalAccelerationMode.Default);
     IsManualTidalAcc           = false;
     LongtermPrecessionMode     = PrecessionModel.Default;
     ShorttermPrecessionMode    = PrecessionModel.Default;
     JplHorizonsMode            = JplHorizonsMode.Default;
     NutationModel              = NutationModel.Default;
     oec                        = Epsilon.Calc(CalculationJulianDayNumber, iflag, this);
     oec2000                    = Epsilon.Calc(JulianDayNumber.J2000, iflag, this);
 }
        /// <summary>
        ///     Defuzzify the variable using the centroid method.
        /// </summary>
        /// <param name="sampleCount">The number of samples to use.</param>
        /// <returns>A crisp value.</returns>
        public float DeFuzzifyCentroid(int sampleCount)
        {
            // calculate the step size
            var stepSize = (MaxRange - MinRange) / sampleCount;

            var totalArea    = 0.0f;
            var sumOfMoments = 0.0f;

            // step through the range of this variable in increments equal to
            // stepSize adding up the contribution (lower of CalculateDOM or
            // the actual DOM of this variable's fuzzified value) for each
            // subset. This gives an approximation of the total area of the
            // fuzzy manifold. (This is similar to how the area under a curve
            // is calculated using calculus... the heights of lots of 'slices'
            // are summed to give the total area.)
            //
            // In addition the moment of each slice is calculated and summed.
            // Dividing the total area by the sum of the moments gives the
            // centroid. (Just like calculating the center of mass of an object)
            for (var sample = 1; sample <= sampleCount; ++sample)
            // for each set get the contribution to the area. This is the
            // lower of the value returned from CalculateDOM or the actual
            // DOM of the fuzzified value itself
            {
                foreach (var kvp in MemberSets)
                {
                    var contribution =
                        Mathf.Min(
                            kvp.Value.CalculateDom(MinRange + sample * stepSize),
                            kvp.Value.Dom);

                    totalArea += contribution;

                    sumOfMoments += (MinRange + sample * stepSize) * contribution;
                }
            }

            // make sure total area is not equal to zero
            if (Epsilon.IsEqual(0, totalArea))
            {
                return(0.0f);
            }

            return(sumOfMoments / totalArea);
        }
示例#19
0
        public FltInterval Log()
        {
            if (IsEmpty())
            {
                return(FltInterval.Empty);
            }

            if (m_Max < 0)
            {
                return(FltInterval.Empty);
            }

            double min = m_Min < 0 ? double.MinValue
                                                : m_Min == 0 ? 0
                                                : Epsilon.PrevOne(Math.Log(m_Min));
            double max = Epsilon.NextOne(Math.Log(m_Max));

            return(new FltInterval(min, max));
        }
示例#20
0
        public void CompareWithOriginalDenseMatrixWithPivoting()
        {
            var sparseMatrix = new SparseMatrix(3);

            sparseMatrix[0, 0] = -1;
            sparseMatrix[0, 1] = 5;
            sparseMatrix[0, 2] = 6;
            sparseMatrix[1, 0] = 3;
            sparseMatrix[1, 1] = -6;
            sparseMatrix[1, 2] = 1;
            sparseMatrix[2, 0] = 6;
            sparseMatrix[2, 1] = 8;
            sparseMatrix[2, 2] = 9;
            var ilu = new Ilutp
            {
                PivotTolerance = 1.0,
                DropTolerance  = 0,
                FillLevel      = 10
            };

            ilu.Initialize(sparseMatrix);
            var l      = GetLowerTriangle(ilu);
            var u      = GetUpperTriangle(ilu);
            var pivots = GetPivots(ilu);
            var p      = new SparseMatrix(l.RowCount);

            for (var i = 0; i < p.RowCount; i++)
            {
                p[i, pivots[i]] = 1.0;
            }

            var temp     = l.Multiply(u);
            var original = temp.Multiply(p);

            for (var i = 0; i < sparseMatrix.RowCount; i++)
            {
                for (var j = 0; j < sparseMatrix.ColumnCount; j++)
                {
                    Assert.IsTrue(sparseMatrix[i, j].AlmostEqual(original[i, j], -Epsilon.Magnitude()), "#01-" + i + "-" + j);
                }
            }
        }
        /// <summary>
        ///     Defuzzifies the value by averaging the maxima of the sets that have fired.
        /// </summary>
        /// <returns>Sum (maxima * DOM) / sum (DOMs).</returns>
        public float DeFuzzifyMaxAv()
        {
            var bottom = 0.0f;
            var top    = 0.0f;

            foreach (var kvp in MemberSets)
            {
                bottom += kvp.Value.Dom;

                top += kvp.Value.RepresentativeValue * kvp.Value.Dom;
            }

            // make sure bottom is not equal to zero
            if (Epsilon.IsEqual(0, bottom))
            {
                return(0.0f);
            }

            return(top / bottom);
        }
示例#22
0
 public float getMaxHeight()
 {
     if (this.maxHeight == null)
     {
         Epsilon eps = new Epsilon(0.01);
         List<short> keys = getTileKeys();
         foreach (short key in keys)
         {
             HfzTile tile = mapData.ElementAt(key).Value;
             List<float> tileData = tile.tileData;
             foreach (float data in tileData)
             {
                 if (!this.maxHeight.HasValue || RealExtensions.GT(data, this.maxHeight.Value, eps))
                 {
                     this.maxHeight = data;
                 }
             }
         }
     }
     return this.maxHeight.Value;
 }
示例#23
0
        public FltInterval Inflate()
        {
            if (IsEmpty())
            {
                return(m_Empty);
            }

            double min = m_Min;
            double max = m_Max;

            if (!double.IsNegativeInfinity(min))
            {
                min = Epsilon.Prev(min);
            }

            if (!double.IsPositiveInfinity(max))
            {
                max = Epsilon.Next(max);
            }

            return(new FltInterval(min, max));
        }
示例#24
0
        private static double[,] nut_matrix(double longitude, double obliquity, Epsilon oe)
        {
            var psi     = longitude;
            var eps     = oe.Eps + obliquity;
            var sinpsi  = Math.Sin(psi);
            var cospsi  = Math.Cos(psi);
            var sineps0 = oe.SinEps;
            var coseps0 = oe.CosEps;
            var sineps  = Math.Sin(eps);
            var coseps  = Math.Cos(eps);
            var matrix  = new double[3, 3];

            matrix[0, 0] = cospsi;
            matrix[0, 1] = sinpsi * coseps;
            matrix[0, 2] = sinpsi * sineps;
            matrix[1, 0] = -sinpsi * coseps0;
            matrix[1, 1] = cospsi * coseps * coseps0 + sineps * sineps0;
            matrix[1, 2] = cospsi * sineps * coseps0 - coseps * sineps0;
            matrix[2, 0] = -sinpsi * sineps0;
            matrix[2, 1] = cospsi * coseps * sineps0 - sineps * coseps0;
            matrix[2, 2] = cospsi * sineps * sineps0 + coseps * coseps0;
            return(matrix);
        }
示例#25
0
            public double protectionLeg(PiecewiseconstantHazardRate creditCurve)
            {
                double ht0 = creditCurve.getRT_(_proLegIntPoints[0]);
                double rt0 = _proYieldCurveRT[0];
                double b0  = _proDF[0] * Math.Exp(-ht0);

                double pv = 0.0;

                for (int i = 1; i < _nProPoints; ++i)
                {
                    double ht1  = creditCurve.getRT_(_proLegIntPoints[i]);
                    double rt1  = _proYieldCurveRT[i];
                    double b1   = _proDF[i] * Math.Exp(-ht1);
                    double dht  = ht1 - ht0;
                    double drt  = rt1 - rt0;
                    double dhrt = dht + drt;

                    // this is equivalent to the ISDA code without explicitly calculating the time step - it also handles the limit
                    double dPV;
                    if (Math.Abs(dhrt) < 1e-5)
                    {
                        dPV = dht * b0 * Epsilon.epsilon(-dhrt);
                    }
                    else
                    {
                        dPV = (b0 - b1) * dht / dhrt;
                    }
                    pv += dPV;
                    ht0 = ht1;
                    rt0 = rt1;
                    b0  = b1;
                }
                pv *= _lgdDF; // multiply by LGD and adjust to valuation date

                return(pv);
            }
示例#26
0
 public override void Update()
 {
     Var0.Intersect(double.MinValue, Epsilon.Prev(m_Value));
 }
示例#27
0
 private HfzHeader validateHeader(HfzFile file)
 {
     Epsilon epsilon = new Epsilon(1E-3);
     HfzHeader header = file.header;
     if(header != null)
     {
         float precis = header.Precis;
         ushort tileSize = header.TileSize;
         UInt32 nx = header.nx;
         UInt32 ny = header.ny;
         if(!RealExtensions.LE(precis, 0.0, epsilon))
         {
             if (tileSize < 8 || tileSize > 65535)
             {
                 throw new Exception("Invalid tilesize: " + tileSize);
             }
             else
             {
                 if (nx <= 0 || ny <= 0)
                 {
                     throw new Exception("Invalid mapsize: " + nx + "," + ny);
                 }
             }
         }
         else
         {
             throw new Exception("Invalid precis: " + precis);
         }
     }
     else
     {
         throw new Exception("No header found in file");
     }
     return header;
 }
示例#28
0
        private HfzTile hfzReadTile(EndianBinaryReader reader, HfzHeader fh, UInt32 TileX, UInt32 TileY, Boolean extraPixelBullshit)
        {
            debugLine("TileX: "+ TileX +", TileY: " + TileY);
            List<float> pTileData = new List<float>();
            UInt32 i = 0, j = 0;

            UInt32 TileSize = fh.TileSize;
            UInt32 mapWidth = fh.nx;
            UInt32 mapHeight = fh.ny;
            UInt32 Rows = TileSize;
            UInt32 RowSize = TileSize-1;

            if (extraPixelBullshit)
            {
                Epsilon e = new Epsilon(1E-3);
                if (RealExtensions.EQ(TileX, (mapWidth / TileSize), e))
                {
                    debugLine("Entering X on " + TileX + "," + TileY);
                    debugLine("result: " + (TileSize - (((TileX + 1) * TileSize) - mapWidth)));
                    Rows = TileSize;
                    RowSize = (TileSize - (((TileX + 1) * TileSize) - mapWidth)) - 1;
                }

                if (RealExtensions.EQ(TileY, (mapHeight / TileSize), e))
                {
                    debugLine("Entering Y on " + TileX + "," + TileY);
                    debugLine("result: " + (TileSize - (((TileY + 1) * TileSize) - mapHeight)));
                    Rows =  TileSize - (((TileY + 1) * TileSize) - mapHeight);
                    RowSize = TileSize - 1;
                }

                if (RealExtensions.EQ(TileX, (mapWidth / TileSize), e) && RealExtensions.EQ(TileY, (mapHeight / TileSize), e))
                {
                    debugLine("Entering X,Y on " + TileX + "," + TileY);
                    debugLine("result: " + (TileSize - (((TileY + 1) * TileSize) - mapHeight)));
                    debugLine("result: " + ((TileSize - (((TileX + 1) * TileSize) - mapWidth)) - 1));
                    Rows = TileSize - (((TileY + 1) * TileSize) - mapHeight);
                    RowSize = (TileSize - (((TileX + 1) * TileSize) - mapWidth)) - 1;
                }
            }

            // read vert offset and sale
            byte LineDepth = 0;
            Int32 FirstVal = 0;
            int tileValues = 0;
            int firstValues = 0;
            try
            {
                float VertScale = reader.ReadSingle();
                float VertOffset = reader.ReadSingle();

                for (j = 0; j < Rows; j++)
                {
                    LineDepth = reader.ReadByte(); // 1, 2, or 4
                    debugLine("Linedepth " + LineDepth);
                    FirstVal = reader.ReadInt32();
                    debugLine("FirstVal " + FirstVal);
                    tileValues++;
                    firstValues++;

                    float pixelValue = (float)FirstVal * VertScale + VertOffset;

                    // set first pixel
                    pTileData.Add(pixelValue);
                    debugLine("FirstValue: " + pixelValue);

                    Int32 LastVal = FirstVal;
                    Int32 li;

                    for (i = 0; i < RowSize; i++)
                    {
                        switch (LineDepth)
                        {
                            case 1:
                                sbyte bvalue = reader.ReadSByte();
                                li = (Int32)bvalue;
                                break;
                            case 2:
                                short svalue = reader.ReadInt16();
                                li = (Int32)svalue;
                                break;
                            default:
                                li = reader.ReadInt32();
                                break;
                        }

                        pixelValue = (float)(li + LastVal) * VertScale + VertOffset;
                        LastVal = li + LastVal;

                        pTileData.Add(pixelValue);
                        tileValues++;
                        debugLine("v: " + pixelValue);
                    }
                }
                debugLine("TileValues: " + tileValues);
                debugLine("FirstValues: " + firstValues);
            }
            catch (Exception)
            {
                System.Console.WriteLine("TileSize: " + TileSize);
                System.Console.WriteLine("x: " + TileX);
                System.Console.WriteLine("y: " + TileY);
                System.Console.WriteLine("j: " + j);
                System.Console.WriteLine("i: " + i);
                System.Console.WriteLine("LineDepth: " + LineDepth);
                System.Console.WriteLine("FirstVal: " + FirstVal);
                throw;
            }
            debugLine("total tilevalues " + tileValues);
            debugLine("total firstvalues " + firstValues);
            return new HfzTile(TileX, TileY, RowSize+1, Rows, pTileData);
        }
示例#29
0
        private void hfzWriteTile(ref EndianBinaryWriter writer, HfzHeader fh, HfzTile tile)
        {
            List<float> pTileData = tile.tileData;

            Int32 i=0, TempInt, FirstVal;
            float f, HFmin, HFmax, VertScale, VertOffset;
            sbyte c;
            short s;

            UInt32 nx = fh.nx;
            UInt32 ny = fh.ny;
            UInt32 TileSize = fh.TileSize;
            float Precis = fh.Precis;
            // get min/max alt in block (used for vert scale)
            HFmin = 0;
            HFmax = 0;
            Epsilon epsilon = new Epsilon(1E-3);

            for (i = 0; i < pTileData.Count; i++)
            {
                // find max diff in line

                f = pTileData.ElementAt(i);

                if (i == 0)
                {
                    HFmin = HFmax = f;
                }
                else
                {
                    if (RealExtensions.LT(f, HFmin, epsilon))
                    {
                        HFmin = f;
                    }

                    if (RealExtensions.GT(f, HFmax, epsilon))
                    {
                        HFmax = f;
                    }
                }
            }

            // number of int levels required for this block
            float BlockLevels = ((HFmax - HFmin) / Precis) + 1;

            // calc scale
            VertScale = (HFmax - HFmin) / BlockLevels;
            VertOffset = HFmin;
            if (RealExtensions.LE(VertScale, 0, epsilon))
            {
                VertScale = 1.0f; // this is for niceness
            }

            writer.Write(VertScale);
            writer.Write(VertOffset);

            // determine number of blocks
            Int32 nBlocksX = ((int)fh.nx / fh.TileSize) - 1;  // -1 due to index starting at 0
            Int32 exBlocksX = -1;
            Int32 nBlocksY = ((int)fh.ny / fh.TileSize) - 1;  // -1 due to index starting at 0
            Int32 exBlocksY = -1;

            if (fh.nx % fh.TileSize > 0)
            {
                exBlocksX = nBlocksX + 1;
            }

            if (fh.ny % fh.TileSize > 0)
            {
                exBlocksY = nBlocksY + 1;
            }

            UInt32 rows = TileSize;
            if(tile.x != exBlocksX && tile.y == exBlocksY || tile.x == exBlocksX && tile.y == exBlocksY)
            {
                rows = (uint)(TileSize - (((exBlocksY+1) * TileSize) - ny));
            }
            else if (tile.x == exBlocksX && tile.y != exBlocksY)
            {
                rows = calculateRows(tile, ny, TileSize, rows);
            }

            int rowCount = 0;
            int rowZeroElement = 0;
            try
            {
                for (rowCount = 0; rowCount < rows; rowCount++)
                {
                    List<float> row = null;

                    int range = calculateRange(tile, nx, TileSize);

                    rowZeroElement = (int)(rowCount * range);
                    row = pTileData.GetRange(rowZeroElement, range);

                    f = row.ElementAt(0);
                    FirstVal = Convert.ToInt32(Math.Truncate((f - VertOffset) / VertScale));
                    Int32 LastVal = FirstVal;

                    // find max diff in line
                    Int32 Diff;
                    Int32 MaxDev = 0;
                    List<Int32> pDiffBuf = new List<Int32>();
                    for (int rowElementCounter = 1; rowElementCounter < row.Count; rowElementCounter++)
                    {

                        // find max diff in line
                        f = row.ElementAt(rowElementCounter);
                        TempInt = Convert.ToInt32(Math.Truncate((f - VertOffset) / VertScale));
                        Diff = TempInt - LastVal;

                        pDiffBuf.Add(Diff);
                        LastVal = TempInt;
                        MaxDev = MaxDev > Math.Abs(Diff) ? MaxDev : Math.Abs(Diff);
                    }

                    // should we use 8, 16 or 32 bit pixels?
                    byte LineDepth = 4;
                    if (MaxDev <= 127)
                    {
                        LineDepth = 1;
                    }
                    else
                        if (MaxDev <= 32767)
                        {
                            LineDepth = 2;
                        }

                    writer.Write(LineDepth);
                    writer.Write(FirstVal);

                    for (int rowElementCounter = 0; rowElementCounter < pDiffBuf.Count; rowElementCounter++)
                    {
                        Diff = pDiffBuf.ElementAt(rowElementCounter);
                        switch (LineDepth)
                        {
                            case 1:
                                c = Convert.ToSByte(Diff);
                                writer.Write(c);
                                break;
                            case 2:
                                s = Convert.ToInt16(Diff);
                                writer.Write(s);
                                break;
                            case 4:
                                writer.Write(Diff);
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("Tile x :" + tile.x);
                System.Console.WriteLine("Tile y :" + tile.y);
                System.Console.WriteLine("Rows :" + rows);
                System.Console.WriteLine("RowCount :" + rowCount);
                System.Console.WriteLine("RowZeroElement :" + rowZeroElement);
                System.Console.WriteLine("exBlocksX :" + exBlocksX);
                System.Console.WriteLine("exBlocksY :" + exBlocksY);
                System.Console.WriteLine("pTileData count :" + pTileData.Count);
                throw ex;
            }
        }
示例#30
0
 public static bool NE(this double a, double b, Epsilon e)
 {
     return e.IsNotEqual(a, b);
 }
示例#31
0
        public void CompareWithOriginalSparseMatrix()
        {
            var sparseMatrix = new SparseMatrix(3);

            sparseMatrix[0, 0] = -1;
            sparseMatrix[0, 1] = 5;
            sparseMatrix[0, 2] = 6;
            sparseMatrix[1, 0] = 3;
            sparseMatrix[1, 1] = -6;
            sparseMatrix[1, 2] = 1;
            sparseMatrix[2, 0] = 6;
            sparseMatrix[2, 1] = 8;
            sparseMatrix[2, 2] = 9;
            var ilu = new ILU0Preconditioner();

            ilu.Initialize(sparseMatrix);
            var original = GetLowerTriangle(ilu).Multiply(GetUpperTriangle(ilu));

            for (var i = 0; i < sparseMatrix.RowCount; i++)
            {
                for (var j = 0; j < sparseMatrix.ColumnCount; j++)
                {
                    Assert.IsTrue(sparseMatrix[i, j].Real.AlmostEqualNumbersBetween(original[i, j].Real, -Epsilon.Magnitude()), "#01-" + i + "-" + j);
                    Assert.IsTrue(sparseMatrix[i, j].Imaginary.AlmostEqualNumbersBetween(original[i, j].Imaginary, -Epsilon.Magnitude()), "#02-" + i + "-" + j);
                }
            }
        }
示例#32
0
        public IDictionary <string, IDictionary <string, IDictionary <string, List <double> > > > GetIndicators()
        {
            GenerateReferenceParetoFronts();

            var         indicators = new Dictionary <string, IDictionary <string, IDictionary <string, List <double> > > >();
            MetricsUtil utils      = new MetricsUtil();

            for (int i = 0, li = experiment.QualityIndicators.Count; i < li; i++)
            {
                string indicatorString = experiment.QualityIndicators[i].ToUpper();
                double value           = 0;

                var problems = new Dictionary <string, IDictionary <string, List <double> > >();
                indicators.Add(indicatorString, problems);

                foreach (var problem in experiment.ExperimentProblems)
                {
                    var algorithm = new Dictionary <string, List <double> >();
                    problems.Add(problem.Alias, algorithm);

                    var trueFront = utils.ReadFront(problem.ParetoFront);

                    foreach (var algorithmDictionary in problem.AlgorithmDictionary)
                    {
                        var indicator = new List <double>();

                        algorithm.Add(algorithmDictionary.Key, indicator);

                        foreach (var alg in algorithmDictionary.Value)
                        {
                            var solutionFront = alg.Result.GetObjectives();

                            switch (indicatorString)
                            {
                            case "HV":
                                HyperVolume hv = new HyperVolume();
                                value = hv.Hypervolume(solutionFront, trueFront, trueFront[0].Length);
                                break;

                            case "SPREAD":
                                Spread spread = new Spread();
                                value = spread.CalculateSpread(solutionFront, trueFront, trueFront[0].Length);
                                break;

                            case "IGD":
                                InvertedGenerationalDistance igd = new InvertedGenerationalDistance();
                                value = igd.CalculateInvertedGenerationalDistance(solutionFront, trueFront, trueFront[0].Length);
                                break;

                            case "EPSILON":
                                Epsilon epsilon = new Epsilon();
                                value = epsilon.CalcualteEpsilon(solutionFront, trueFront, trueFront[0].Length);
                                break;
                            }

                            indicator.Add(value);
                        }
                    }
                }
            }
            return(indicators);
        }
示例#33
0
 public static bool EQ(this double a, double b, Epsilon e)
 {
     return e.IsEqual   (a, b);
 }
 public override bool IsViolated()
 {
     return(IsBound() &&
            !Epsilon.Equal(IntVar.Value, FltVar.Value));
 }
 public void Visit(Epsilon epsilon)
 {
 }
示例#36
0
 public QNetAgent()
 {
     memoryBank = new List <ReplayMemory>();
     epsilon    = new ConstantEpsilon(.5);
 }