Linear() public static method

public static Linear ( float start, float distance, float elapsedTime, float duration ) : float
start float
distance float
elapsedTime float
duration float
return float
Example #1
0
        private static Task <Location> InterpolateLocationAsync(DateTime relativeTo, Location initialLocation, IEnumerable <Segment> segments)
        {
            IList <double> longitudes      = new List <double>();
            IList <double> latitudes       = new List <double>();
            IList <double> timeSpans       = new List <double>();
            TimeSpan       currentTimeSpan = TimeSpan.Zero;
            TimeSpan       myTimeSpan      = TimeSpan.Zero;

            longitudes.Add(initialLocation.Longitude);
            latitudes.Add(initialLocation.Latitude);
            timeSpans.Add(currentTimeSpan.TotalSeconds);
            foreach (Segment segment in segments)
            {
                longitudes.Add(segment.Longitude);
                latitudes.Add(segment.Latitude);
                currentTimeSpan += segment.TimeSpan;
                timeSpans.Add(currentTimeSpan.TotalSeconds);
            }

            myTimeSpan = relativeTo - initialLocation.DateTime;
            IInterpolation longitudesInterpolation = Interpolate.Linear(timeSpans, longitudes);
            IInterpolation latitudesInterpolation  = Interpolate.Linear(timeSpans, latitudes);

            return(Task.FromResult(
                       new Location
            {
                Longitude = longitudesInterpolation.Interpolate(myTimeSpan.TotalSeconds),
                Latitude = latitudesInterpolation.Interpolate(myTimeSpan.TotalSeconds),
                DateTime = relativeTo
            }));
        }
Example #2
0
        /// <summary>
        /// <para> 1. Load thrust data (time, force). </para>
        /// <para> 2. Generate interpolated thrust curve. </para>
        /// </summary>
        public IInterpolation LoadThrust()
        {
            var            timeList  = new List <double>();
            var            forceList = new List <double>();
            IInterpolation intpThrust;

            StreamReader sr            = new StreamReader(FilePath, Encoding.GetEncoding("SHIFT_JIS"));
            var          fileExtension = System.IO.Path.GetExtension(FilePath);

            // Open thrust file.
            while (sr.EndOfStream == false)
            {
                string   line      = sr.ReadLine();
                string[] splitData = null;

                if (fileExtension == ".txt")
                {
                    splitData = line.Split('\t');
                }
                else if (fileExtension == ".csv")
                {
                    splitData = line.Split(',');
                }

                // Omit comment lines
                if (double.TryParse(splitData[0], out double time) &&
                    double.TryParse(splitData[1], out double force))
                {
                    timeList.Add(time);
                    forceList.Add(force);
                }
            }

            // Convert List to Array.
            int listLen = timeList.Count;

            timeArray  = new double[listLen];
            forceArray = new double[listLen];

            timeArray  = timeList.ToArray();
            forceArray = forceList.ToArray();

            // Select interpolation method.
            switch (IntpMethod)
            {
            case "linear":
                intpThrust = Interpolate.Linear(timeArray, forceArray);
                break;

            case "cubic":
                intpThrust = Interpolate.CubicSpline(timeArray, forceArray);
                break;

            default:
                intpThrust = Interpolate.Linear(timeArray, forceArray);
                break;
            }

            return(intpThrust);
        }
        public TimeSeries <T> InterpolateSeria(TimeSpan dt)
        {
            if (typeof(T) != typeof(double))
            {
                return(null);
            }

            //RepositionDuplicatedTimeStamps();

            RemoveDuplicatedTimeStamps();

            List <DateTime> resDateTimeList = new List <DateTime>();

            DateTime      startTime           = lDateTimeStamps[0];
            List <double> currentDatetimeList =
                lDateTimeStamps.ConvertAll <double>(time => (time - startTime).TotalMilliseconds);
            //List<double> currentDataList =
            //    dataSeria.ConvertAll<double>(dVal => Convert.ToDouble(dVal));

            DateTime endTime         = lDateTimeStamps[lDateTimeStamps.Count - 1];
            int      dtCount         = Convert.ToInt32(((double)((endTime - startTime).TotalMilliseconds) / (double)(dt.TotalMilliseconds)));
            long     dtInternalTicks = Convert.ToInt64(((endTime - startTime).Ticks) / (double)dtCount);
            TimeSpan dtInternal      = new TimeSpan(dtInternalTicks);

            DateTime t = startTime;

            while (true)
            {
                resDateTimeList.Add(t);
                t += dtInternal;
                if (t > endTime)
                {
                    break;
                }
            }

            List <double> dataDoubleValues = dataSeria as List <double>;

            IInterpolation method;

            try
            {
                method = Interpolate.Linear(currentDatetimeList, dataDoubleValues);
            }
            catch (Exception)
            {
                return(this);
            }

            List <double> interpolatedValues = new List <double>();

            foreach (DateTime time in resDateTimeList)
            {
                interpolatedValues.Add(method.Interpolate((time - startTime).TotalMilliseconds));
            }

            return(new TimeSeries <T>(interpolatedValues as List <T>, resDateTimeList));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="WalkingTrail"/> class. For Internal Use ONLY!
        /// </summary>
        /// <param name="observedPoints">The observed locations.</param>
        /// <param name="velocityMagnitude">The velocity magnitude.</param>
        internal WalkingTrail(UV[] observedPoints, double velocityMagnitude)
        {
            this._length      = new double[observedPoints.Length];
            this._trailLength = 0;
            this._length[0]   = 0;
            for (int i = 0; i < observedPoints.Length - 1; i++)
            {
                double d = observedPoints[i].DistanceTo(observedPoints[i + 1]);
                this._length[i + 1] = this._length[i] + d;
            }
            this._trailLength = this._length[this._length.Length - 1];
            double[] observation_time = new double[this._length.Length];
            observation_time[0] = 0;
            for (int i = 0; i < observedPoints.Length - 1; i++)
            {
                double deltaT = observedPoints[i].DistanceTo(observedPoints[i + 1]) / velocityMagnitude;
                observation_time[i + 1] = observation_time[i] + deltaT;
            }

            this._trailInput      = TrailInput.Location;
            this._observationTime = observation_time;
            this._startTime       = _observationTime[0];
            this._endTime         = _observationTime[_observationTime.Length - 1];
            this._duration        = _observationTime[_observationTime.Length - 1] - _observationTime[0];
            this._timeToLength    = Interpolate.CubicSplineRobust(this._observationTime, this._length);
            this._lengthToTime    = Interpolate.CubicSplineRobust(this._length, this._observationTime);

            //create interpolations
            double[] location_U_values = new double[this._observationTime.Length];
            double[] location_V_values = new double[this._observationTime.Length];
            for (int i = 0; i < this._observationTime.Length; i++)
            {
                location_U_values[i] = observedPoints[i].U;
                location_V_values[i] = observedPoints[i].V;
            }
            this._interpolate_location_U = Interpolate.CubicSplineRobust(this._observationTime, location_U_values);
            this._ULinearInterpolation   = Interpolate.Linear(this._observationTime, location_U_values);

            this._interpolate_location_V = Interpolate.CubicSplineRobust(this._observationTime, location_V_values);
            this._VLinearInterpolation   = Interpolate.Linear(this._observationTime, location_V_values);


            this._observedStates = new StateBase[this._observationTime.Length];
            //this._controlPoints = new UV[this._time.Length];
            for (int i = 0; i < this._observedStates.Length; i++)
            {
                UV location  = observedPoints[i];
                UV velocity  = this.getVelocity(this._observationTime[i]);
                UV direction = this.getDirection(this._observationTime[i]);
                //this._controlPoints[i] = location;
                this._observedStates[i] = new StateBase(location, direction, velocity);
            }
            this.loadNormalizedStates();
            loadApproximatedPolyline();
        }
Example #5
0
        public void Should_CalculatePoint_ForLinearHalfStep()
        {
            var step = 0.5;
            var p    = Interpolate.Linear(
                new Vector3d(0, 0, 0),
                new Vector3d(1, 1, 1),
                step
                );

            Assert.AreEqual(new Vector3d(0.5, 0.5, 0.5), p);
        }
Example #6
0
        public void Should_CalculatePoint_ForLinearFullStep()
        {
            var step = 1.0;
            var p    = Interpolate.Linear(
                new Vector3d(0, 0, 0),
                new Vector3d(1, 1, 1),
                step
                );

            Assert.AreEqual(new Vector3d(1.0, 1.0, 1.0), p);
        }
Example #7
0
        private TimeSpan FindNearCornerRuntime(IEnumerable <JobEntity> entrys, int amount, double speed)
        {
            List <double> points = new List <double>();
            List <double> values = new List <double>();

            foreach (var speedEntry in Sort(entrys, speed))
            {
                points.Add(speedEntry.Key);
                values.Add(speedEntry.Value.Average(ce => ce.NormaizedTime.TotalMinutes));
            }

            return(TimeSpan.FromMinutes(Interpolate.Linear(points, values).Interpolate(speed) * (amount / 1000d)));
        }
Example #8
0
        public double CalculateSpeed(int drops)
        {
            if (_nodes.Count < 2)
            {
                return(0);
            }

            try
            {
                return(Math.Round(Interpolate.Linear(_nodes.Select(n => (double)n.Drops), _nodes.Select(n => n.Speed)).Interpolate(drops), 3));
            }
            catch (ArgumentException)
            {
                return(0);
            }
        }
Example #9
0
        public IInterpolation IntpParam(List <double> timeList, List <double> paramList)
        {
            // var timeList = new List<double>();
            // var paramList = new List<double>();
            IInterpolation intpVar;

            // Convert List to Array.
            int listLen    = timeList.Count;
            var timeArray  = new double[listLen];
            var paramArray = new double[listLen];

            timeArray  = timeList.ToArray();
            paramArray = paramList.ToArray();

            intpVar = Interpolate.Linear(timeArray, paramArray);

            return(intpVar);
        }
Example #10
0
        public void TestInterpolateSpeed()
        {
            double[] table = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f };
            var      s     = new Stopwatch();

            var dist = Utils.Linspace(0.0f, 1.0f, 999999);

            s.Restart();
            for (int i = 0; i < dist.Length; i++)
            {
                dist[i] = (double)Interpolate.Linear(dist[i], table);
            }
            s.Stop();
            var linear = s.ElapsedMilliseconds;

            dist = Utils.Linspace(0.0f, 1.0f, 999999);
            s.Restart();
            for (int i = 0; i < dist.Length; i++)
            {
                dist[i] = (double)Interpolate.Spline(dist[i], table);
            }
            s.Stop();
            var spline = s.ElapsedMilliseconds;

            dist = Utils.Linspace(0.0f, 1.0f, 999999);
            s.Restart();
            for (int i = 0; i < dist.Length; i++)
            {
                dist[i] = (double)Interpolate.CubicWrap(dist[i], table);
            }
            s.Stop();
            var cubic = s.ElapsedMilliseconds;

            dist = Utils.Linspace(0.0f, 1.0f, 999999);
            s.Restart();
            for (int i = 0; i < dist.Length; i++)
            {
                dist[i] = (double)Interpolate.Cosine(dist[i], table);
            }
            s.Stop();
            var cosine = s.ElapsedMilliseconds;

            MessageBox.Show("Linear: " + linear + "\nSpline: " + spline + "\nCubic: " + cubic + "\nCosine: " + cosine);
        }
Example #11
0
        /// <summary>
        /// Run example
        /// </summary>
        /// <seealso cref="http://en.wikipedia.org/wiki/Spline_interpolation">Spline interpolation</seealso>
        public void Run()
        {
            // 1. Generate 20 samples of the function x*x-2*x on interval [0, 10]
            Console.WriteLine(@"1. Generate 20 samples of the function x*x-2*x on interval [0, 10]");
            double[] points = Generate.LinearSpaced(20, 0, 10);
            var      values = Generate.Map(points, TargetFunction);

            Console.WriteLine();

            // 2. Create a linear spline interpolation based on arbitrary points
            var method = Interpolate.Linear(points, values);

            Console.WriteLine(@"2. Create a linear spline interpolation based on arbitrary points");
            Console.WriteLine();

            // 3. Check if interpolation support integration
            Console.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration);
            Console.WriteLine();

            // 4. Check if interpolation support differentiation
            Console.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation);
            Console.WriteLine();

            // 5. Differentiate at point 5.2
            Console.WriteLine(@"5. Differentiate at point 5.2 = {0}", method.Differentiate(5.2));
            Console.WriteLine();

            // 6. Integrate at point 5.2
            Console.WriteLine(@"6. Integrate at point 5.2 = {0}", method.Integrate(5.2));
            Console.WriteLine();

            // 7. Interpolate ten random points and compare to function results
            Console.WriteLine(@"7. Interpolate ten random points and compare to function results");
            var rng = new MersenneTwister(1);

            for (var i = 0; i < 10; i++)
            {
                // Generate random value from [0, 10]
                var point = rng.NextDouble() * 10;
                Console.WriteLine(@"Interpolate at {0} = {1}. Function({0}) = {2}", point.ToString("N05"), method.Interpolate(point).ToString("N05"), TargetFunction(point).ToString("N05"));
            }

            Console.WriteLine();
        }
Example #12
0
        public double GetValue(double value)
        {
            value = value + Bias;
            if (value < Min)
            {
                return(Table[0]);
            }
            if (value > Max)
            {
                return(Table[Table.Length - 1]);
            }

            var maxMin = 1 / (Max - Min);

            double idx    = (value - Min) * maxMin;
            double output = Interpolate.Linear(idx, Table);

            return(output);
        }
        public double GetPileLengthByBearingCapacity()
        {
            if (m_wantedPileBearing <= 0)
            {
                throw new ArgumentOutOfRangeException("m_wantedPileBearing");
            }
            Dictionary <double, double> pilelengthandbearingforce;

            GetPileCacluateInfo(out pilelengthandbearingforce);
            List <double> points = new List <double>(), values = new List <double>();

            foreach (var keyvalue in pilelengthandbearingforce)
            {
                points.Add(keyvalue.Key);
                values.Add(keyvalue.Value);
            }
            var interpolate = Interpolate.Linear(points, values);

            return(FindRoots.OfFunction(x => interpolate.Interpolate(x) - m_wantedPileBearing, points.Min(), points.Max()));
        }
Example #14
0
        public static string CurveInterpolation(this PointXy[] pointXy)
        {
            var listX = new List <double>();
            var listY = new List <double>();

            foreach (PointXy point in pointXy)
            {
                listX.Add(point.PointX);
                listY.Add(point.PointY);
            }

            var           result = Interpolate.Linear(listX, listY);
            StringBuilder sb     = new StringBuilder();

            for (var i = -9; i < 10; i++)
            {
                sb.AppendFormat("[X: {0} ; Y: {1}]", i, result.Interpolate(i));
                sb.AppendLine();
            }
            return(sb.ToString()?.TrimEnd());
        }
Example #15
0
        private void SetIntpThrust(List <double> timeList, List <double> forceList)
        {
            var dataNum    = timeList.Count;
            var timeArray  = timeList.ToArray();
            var forceArray = forceList.ToArray();

            // Select interpolation method.
            switch (IntpMethod)
            {
            case "linear":
                IntpThrust = Interpolate.Linear(timeArray, forceArray);
                break;

            case "cubic":
                IntpThrust = Interpolate.CubicSpline(timeArray, forceArray);
                break;

            default:
                IntpThrust = Interpolate.Linear(timeArray, forceArray);
                break;
            }
        }
Example #16
0
        public static double[] Interpolation(double[] input, int dataSize)
        {
            var points = Generate.LinearSpaced(input.Length, 0, input.Length - 1);
            var xs     = Generate.LinearSpaced(dataSize, 0, input.Length - 1);


            var output = new double[dataSize];

            if (input.Length == dataSize)
            {
                Array.Copy(input, output, dataSize);
            }
            else
            {
                //var method = Interpolate.CubicSpline(points, input);
                var method = Interpolate.Linear(points, input);
                for (int idx = 0; idx < dataSize; idx++)
                {
                    output[idx] = method.Interpolate(xs[idx]);
                }
            }
            return(output);
        }
Example #17
0
        public static void FitMoleculeToRef(Molecule molecule, bool saveChannel1Intensities, bool saveChannel2Intensities, string outputDir)
        {
            List <Tuple <int, int> > labelIdAlignmentPositions = XMAPParser.ParseAlignmentString(molecule.AlignmentString); //in each tuple item1 = ref, item2 = molecule

            string[]      molAlignmentLabelPositions = molecule.AlignmentChannelLabelPositions.Split('\t');
            List <double> refPositions = new List <double>();
            List <double> molPositions = new List <double>();
            //Dictionary<int, double> molFitPixelPositions = new Dictionary<int, double>();
            double currRefPosition, currMolPosition;

            foreach (Tuple <int, int> labelIdAlignment in labelIdAlignmentPositions)
            {
                currRefPosition = rCmapPositions[molecule.ChromId][labelIdAlignment.Item1 - 1];                      //position along chromosome in bp
                currMolPosition = double.Parse(molAlignmentLabelPositions[labelIdAlignment.Item2 - 1]) / bpPerPixel; //position along molecule in pixels
                if (!refPositions.Contains(currRefPosition) && !molPositions.Contains(currMolPosition))
                {
                    refPositions.Add(currRefPosition);
                    molPositions.Add(currMolPosition);
                }
            }
            if (molecule.Orientation == "-")
            {
                refPositions.Reverse();
                molPositions.Reverse();
            }
            IInterpolation linearInterpolation = Interpolate.Linear(molPositions, refPositions);

            if (saveChannel1Intensities)
            {
                SaveMoleculePixelsToFile(linearInterpolation, molecule, 1, outputDir);
            }
            if (saveChannel2Intensities)
            {
                SaveMoleculePixelsToFile(linearInterpolation, molecule, 2, outputDir);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="WalkingTrail"/> class.
        /// </summary>
        /// <param name="observation_time">The observation time.</param>
        /// <param name="observed_states">The observed states.</param>
        /// <param name="inputMode">The input mode.</param>
        /// <exception cref="ArgumentException">
        /// The size of observation time and observed states are not equal
        /// or
        /// The observation times are not in ascending order!
        /// or
        /// The observed states include null elements that cannot be used for generating a trail model
        /// or
        /// The observed states include null elements that cannot be used for generating a trail model
        /// or
        /// The observed states include null locations that cannot be used for generating a trail model
        /// </exception>
        public WalkingTrail(double[] observation_time, StateBase[] observed_states, TrailInput inputMode)
        {
            if (observation_time.Length != observed_states.Length)
            {
                throw new ArgumentException("The size of observation time and observed states are not equal");
            }
            for (int i = 0; i < observation_time.Length - 1; i++)
            {
                if (observation_time[i] >= observation_time[i + 1])
                {
                    throw new ArgumentException("The observation times are not in ascending order!");
                }
            }
            for (int i = 0; i < observed_states.Length; i++)
            {
                switch (inputMode)
                {
                case TrailInput.Location_Velocity_Direction:
                    if (observed_states[i].Velocity == null || observed_states[i].Direction == null || observed_states[i].Location == null)
                    {
                        throw new ArgumentException("The observed states include null elements that cannot be used for generating a trail model");
                    }
                    break;

                case TrailInput.Location_Direction:
                    if (observed_states[i].Direction == null || observed_states[i].Location == null)
                    {
                        throw new ArgumentException("The observed states include null elements that cannot be used for generating a trail model");
                    }
                    break;

                case TrailInput.Location:
                    if (observed_states[i].Location == null)
                    {
                        throw new ArgumentException("The observed states include null locations that cannot be used for generating a trail model");
                    }
                    break;
                }
            }

            this._trailInput      = inputMode;
            this._observationTime = observation_time;
            this._startTime       = _observationTime[0];
            this._endTime         = _observationTime[_observationTime.Length - 1];
            this._duration        = _observationTime[_observationTime.Length - 1] - _observationTime[0];

            this._length    = new double[observation_time.Length];
            this._length[0] = 0;
            for (int i = 0; i < observed_states.Length - 1; i++)
            {
                double d = observed_states[i].Location.DistanceTo(observed_states[i + 1].Location);
                this._length[i + 1] = this._length[i] + d;
            }
            this._trailLength  = this._length[this._length.Length - 1];
            this._timeToLength = Interpolate.CubicSplineRobust(this._observationTime, this._length);
            this._lengthToTime = Interpolate.CubicSplineRobust(this._length, this._observationTime);

            //create interpolations
            double[] location_U_values = new double[this._observationTime.Length];
            double[] location_V_values = new double[this._observationTime.Length];
            for (int i = 0; i < this._observationTime.Length; i++)
            {
                location_U_values[i] = observed_states[i].Location.U;
                location_V_values[i] = observed_states[i].Location.V;
            }
            this._interpolate_location_U = Interpolate.CubicSplineRobust(this._observationTime, location_U_values);
            this._ULinearInterpolation   = Interpolate.Linear(this._observationTime, location_U_values);

            this._interpolate_location_V = Interpolate.CubicSplineRobust(this._observationTime, location_V_values);
            this._VLinearInterpolation   = Interpolate.Linear(this._observationTime, location_V_values);

            double[] velocity_U_values;
            double[] velocity_V_values;

            double[] direction_U_values;
            double[] direction_V_values;

            switch (this._trailInput)
            {
            case TrailInput.Location_Velocity_Direction:
                velocity_U_values  = new double[this._observationTime.Length];
                velocity_V_values  = new double[this._observationTime.Length];
                direction_U_values = new double[this._observationTime.Length];
                direction_V_values = new double[this._observationTime.Length];
                for (int i = 0; i < this._observationTime.Length; i++)
                {
                    velocity_U_values[i] = observed_states[i].Velocity.U;
                    velocity_V_values[i] = observed_states[i].Velocity.V;
                    observed_states[i].Direction.Unitize();
                    direction_U_values[i] = observed_states[i].Direction.U;
                    direction_V_values[i] = observed_states[i].Direction.V;
                }
                this._interpolate_velocity_U  = Interpolate.CubicSplineRobust(this._observationTime, velocity_U_values);
                this._interpolate_velocity_V  = Interpolate.CubicSplineRobust(this._observationTime, velocity_V_values);
                this._interpolate_direction_U = Interpolate.CubicSplineRobust(this._observationTime, direction_U_values);
                this._interpolate_direction_V = Interpolate.CubicSplineRobust(this._observationTime, direction_V_values);
                break;

            case TrailInput.Location_Direction:
                direction_U_values = new double[this._observationTime.Length];
                direction_V_values = new double[this._observationTime.Length];
                for (int i = 0; i < this._observationTime.Length; i++)
                {
                    observed_states[i].Direction.Unitize();
                    direction_U_values[i] = observed_states[i].Direction.U;
                    direction_V_values[i] = observed_states[i].Direction.V;
                }
                this._interpolate_direction_U = Interpolate.CubicSplineRobust(this._observationTime, direction_U_values);
                this._interpolate_direction_V = Interpolate.CubicSplineRobust(this._observationTime, direction_V_values);
                break;

            case TrailInput.Location:
                //do nothing
                break;
            }
            this._observedStates = new StateBase[this._observationTime.Length];
            //this._controlPoints = new UV[this._time.Length];
            for (int i = 0; i < this._observedStates.Length; i++)
            {
                UV location = observed_states[i].Location;
                //this._controlPoints[i] = location;
                UV velocity = null;
                if (observed_states[i].Velocity == null)
                {
                    velocity = this.getVelocity(this._observationTime[i]);
                }
                else
                {
                    velocity = observed_states[i].Velocity;
                }
                UV direction = null;
                if (observed_states[i].Direction == null)
                {
                    direction = this.getDirection(this._observationTime[i]);
                }
                else
                {
                    direction = observed_states[i].Direction;
                }
                this._observedStates[i] = new StateBase(location, direction, velocity);
            }
            this.loadNormalizedStates();
            loadApproximatedPolyline();
        }
Example #19
0
        public IEnumerable <CitationChange> GetPrePostCitationChangeVector(Repository repository)
        {
            // 1st int is tool ID, 1st double is days, and 2nd double is citation count.
            var changes = new Dictionary <int, SortedDictionary <double, double> >();

            foreach (var association in repository.ToolAssociations)
            {
                var tool = association.Tool;
                Context.Entry(tool).Collection(x => x.PublicationAssociations).Load();
                foreach (var pub in tool.PublicationAssociations)
                {
                    if (pub.Publication.Citations != null && pub.Publication.Year >= EarliestPublicationYear)
                    {
                        if (pub.Publication.Citations.Count == 0 ||
                            (pub.Publication.Citations.Count == 1 && pub.Publication.Citations.First().Count == 0))
                        {
                            continue;
                        }

                        foreach (var citation in pub.Publication.Citations)
                        {
                            if (!changes.ContainsKey(tool.ID))
                            {
                                changes.Add(tool.ID, new SortedDictionary <double, double>());
                            }

                            var daysOffset = (citation.Date - association.DateAddedToRepository).Value.Days;
                            // This can be true when multiple publications per tool exist.
                            if (changes[tool.ID].ContainsKey(daysOffset))
                            {
                                changes[tool.ID][daysOffset] += citation.Count;
                            }
                            else
                            {
                                changes[tool.ID].Add(daysOffset,
                                                     citation.Count);
                            }
                        }
                    }
                }
            }

            // Normalize citation counts and date.
            var tools = changes.Keys.ToList();

            foreach (var toolID in tools)
            {
                var    citations     = changes[toolID];
                double minBeforeDays = 0;
                double maxAfterDays  = 0;
                foreach (var day in citations.Keys)
                {
                    minBeforeDays = Math.Min(minBeforeDays, day);
                    maxAfterDays  = Math.Max(maxAfterDays, day);
                }

                // Normalize citation count.
                var delta = maxAfterDays - minBeforeDays;
                var days  = citations.Keys.ToList();
                foreach (var day in days)
                {
                    citations[day] /= delta;
                }

                // Min-Max normalize date.
                var normalizedDates = new SortedDictionary <double, double>();
                foreach (var day in days)
                {
                    var count          = citations[day];
                    var normalizedDate = 0.0;
                    if (day <= 0)
                    {
                        normalizedDate = (-1) * ((day - maxAfterDays) / (minBeforeDays - maxAfterDays));
                    }
                    else
                    {
                        normalizedDate = (day - minBeforeDays) / (maxAfterDays - minBeforeDays);
                    }

                    normalizedDates.Add(normalizedDate, count);
                }

                changes[toolID] = normalizedDates;
            }

            var interpolatedCitations = new SortedDictionary <double, List <double> >();

            // Calculate in-betweens
            // First determine data points on x axis (i.e., days offset):
            var x = Generate.LinearSpaced(21, -1.0, 1.0);

            foreach (var item in x)
            {
                interpolatedCitations.Add(item, new List <double>());
            }

            foreach (var tool in changes)
            {
                if (tool.Value.Keys.Count < 2 || tool.Value.Values.Count < 2)
                {
                    continue;
                }
                // data samples to interpolate over
                var spline = Interpolate.Linear(tool.Value.Keys, tool.Value.Values);

                foreach (var item in x)
                {
                    var c = spline.Interpolate(item);
                    if (c < 0)
                    {
                        // todo: find a better alternative.
                        continue;
                    }
                    interpolatedCitations[item].Add(c);
                }
            }

            var rtv = new List <CitationChange>();

            foreach (var item in interpolatedCitations)
            {
                var c = new CitationChange();
                c.AddCitationCount(item.Value);
                c.DaysOffset = item.Key;
                // c.RemoveOutliers();
                rtv.Add(c);
            }

            return(rtv);
        }
        public override IEnumerable <IRow> Reduce(IRowset input, IUpdatableRow output)
        {
            var rows = (from r in input.Rows
                        select new SnotelRow
            {
                DatePart = r.Get <DateTime>("DatePart"),
                Date = r.Get <DateTime>("Date"),
                DateString = r.Get <String>("DateString"),
                StationName = r.Get <String>("StationName"),
                ElevationFt = r.Get <int>("ElevationFt"),
                Lat = r.Get <double>("Lat"),
                Lon = r.Get <double>("Lon"),
                SnowWaterEquivalentIn = r.Get <float?>("SnowWaterEquivalentIn"),
                PrecipitationAccumulation = r.Get <float?>("PrecipitationAccumulation"),
                SnowDepthIn = r.Get <int?>("SnowDepthIn"),
                AirTemperatureObservedF = r.Get <int?>("AirTemperatureObservedF"),
                SnotelState = r.Get <String>("SnotelState"),
                __fileHour = r.Get <int>("__fileHour"),
                __fileDate = r.Get <DateTime>("__fileDate")
            }).ToList();

            List <double> pointsSwe            = new List <double>();
            List <double> pointsPrecip         = new List <double>();
            List <double> pointsSnowDepth      = new List <double>();
            List <double> pointsAirTemp        = new List <double>();
            List <double> valuesSwe            = new List <double>();
            List <double> valuesPrecip         = new List <double>();
            List <double> valuesSnowDepth      = new List <double>();
            List <double> valuesAirTemp        = new List <double>();
            bool          interpolateSwe       = false;
            bool          interpolatePrecip    = false;
            bool          interpolateSnowDepth = false;
            bool          interpolateAirTemp   = false;

            for (int count = 0; count < rows.Count(); count++)
            {
                var row = rows.ElementAt(count);
                if (row.SnowWaterEquivalentIn != null)
                {
                    pointsSwe.Add(count);
                    valuesSwe.Add(row.SnowWaterEquivalentIn.Value);
                }
                else
                {
                    interpolateSwe = true;
                }

                if (row.PrecipitationAccumulation != null)
                {
                    pointsPrecip.Add(count);
                    valuesPrecip.Add(row.PrecipitationAccumulation.Value);
                }
                else
                {
                    interpolatePrecip = true;
                }

                if (row.SnowDepthIn != null)
                {
                    pointsSnowDepth.Add(count);
                    valuesSnowDepth.Add(row.SnowDepthIn.Value);
                }
                else
                {
                    interpolateSnowDepth = true;
                }

                if (row.AirTemperatureObservedF != null)
                {
                    pointsAirTemp.Add(count);
                    valuesAirTemp.Add(row.AirTemperatureObservedF.Value);
                }
                else
                {
                    interpolateAirTemp = true;
                }
            }

            var methodSwe       = (pointsSwe.Count > 1 && interpolateSwe ? Interpolate.Linear(pointsSwe, valuesSwe) : null);
            var methodPrecip    = (pointsPrecip.Count > 1 && interpolatePrecip ? Interpolate.Linear(pointsPrecip, valuesPrecip) : null);
            var methodSnowDepth = (pointsSnowDepth.Count > 1 && interpolateSnowDepth ? Interpolate.Linear(pointsSnowDepth, valuesSnowDepth) : null);
            var methodAirTemp   = (pointsAirTemp.Count > 1 && interpolateAirTemp ? Interpolate.Linear(pointsAirTemp, valuesAirTemp) : null);

            for (int count = 0; count < rows.Count(); count++)
            {
                var row = rows.ElementAt(count);
                if (row.SnowWaterEquivalentIn != null)
                {
                    output.Set <float?>("SnowWaterEquivalentIn", row.SnowWaterEquivalentIn.Value);
                }
                else if (row.SnowWaterEquivalentIn == null && methodSwe != null)
                {
                    float swe = (float)methodSwe.Interpolate(count);
                    output.Set <float?>("SnowWaterEquivalentIn", swe);
                }
                else
                {
                    output.Set <float?>("SnowWaterEquivalentIn", null);
                }


                if (row.PrecipitationAccumulation != null)
                {
                    output.Set <float?>("PrecipitationAccumulation", row.PrecipitationAccumulation.Value);
                }
                else if (row.PrecipitationAccumulation == null && methodPrecip != null)
                {
                    float precip = (float)methodPrecip.Interpolate(count);
                    output.Set <float?>("PrecipitationAccumulation", precip);
                }
                else
                {
                    output.Set <float?>("PrecipitationAccumulation", null);
                }

                if (row.SnowDepthIn != null)
                {
                    output.Set <int?>("SnowDepthIn", row.SnowDepthIn.Value);
                }
                else if (row.SnowDepthIn == null && methodSnowDepth != null)
                {
                    int depth = (int)methodSnowDepth.Interpolate(count);
                    output.Set <int?>("SnowDepthIn", depth);
                }
                else
                {
                    output.Set <int?>("SnowDepthIn", null);
                }

                if (row.AirTemperatureObservedF != null)
                {
                    output.Set <int?>("AirTemperatureObservedF", row.AirTemperatureObservedF.Value);
                }
                else if (row.AirTemperatureObservedF == null && methodAirTemp != null)
                {
                    int temp = (int)methodAirTemp.Interpolate(count);
                    output.Set <int?>("AirTemperatureObservedF", temp);
                }
                else
                {
                    output.Set <int?>("AirTemperatureObservedF", null);
                }

                output.Set <DateTime>("DatePart", row.DatePart);
                output.Set <DateTime>("Date", row.Date);
                output.Set <String>("DateString", row.DateString);
                output.Set <String>("StationName", row.StationName);
                output.Set <int>("ElevationFt", row.ElevationFt);
                output.Set <double>("Lat", row.Lat);
                output.Set <double>("Lon", row.Lon);
                output.Set <String>("SnotelState", row.SnotelState);
                output.Set <int>("__fileHour", row.__fileHour);
                output.Set <DateTime>("__fileDate", row.__fileDate);
                yield return(output.AsReadOnly());
            }
        }
Example #21
0
        public static string[] TesteMathNetInterpolation()
        {
            double DataPoints = 1000;

            // Create the data to be fitted
            //var x = new List<double> { 1, 8, 16, 25, 30 }; // 5 pontos

            var x = new List <double> {
                1, 2, 3, 4, 16, 30
            };                                                           // 5 pontos
            //var x = new List<double> { 1, 2, 3, 4, 5, 10, 15, 20, 25, 30 }; // 10 pontos

            var y = new List <double> {
                8.33, 9.25, 9.16, 8.43, 9.5, 9.14
            };
            //var y = new List<double> { 8.33, 9.37, 8.47, 9.32, 9.11, 9.04, 8.93, 9.49, 8.29, 8.88
            //var y = new List<double> { 10.255, 10.064, 9.961, 9.945, 9.930 , 9.37, 9.65, 9.95, 10.40, 10.88};
            //var y = new List<double> { 3, 3, 3, 3, 15, 40, 50, 60, 70, 80 };

            //Lembre-se sempre de modificar as variacoes de X e Y da plotagem

            var xAkima  = new List <double>();
            var yAkima  = new List <double>();
            var xLinear = new List <double>();
            var yLinear = new List <double>();

            /// Interpolação Linear
            var linearInterpolation = Interpolate.Linear(x.ToArray(), y.ToArray());

            /// Interpolação Polinomial
            //var PolinomialInterpolation = new NevillePolynomialInterpolation(x.ToArray(), y.ToArray());

            /// Interpolação Akima Spline
            var akimaInterpolation = CubicSpline.InterpolateAkima(x.ToArray(), y.ToArray());


            var ep = 0;
            var a  = x.Min();
            var b  = x.Max();

            #region Akima Interpolation
            for (int i = 0; i <= DataPoints; i++)
            {
                /// nomalizedForm = (b−a) (x−min / max − min) + a
                /// b = valor maximo do intervalo que os numeros devem ficar
                /// a = valor minimo do intervalo que os numeros devem ficar
                /// max = valor maximo do intervalo atual
                /// min = valor minimo do intervalo atual
                double normalized  = ((b + ep) - (a - ep)) * (i / DataPoints) + (a - ep);
                var    yInterpoled = akimaInterpolation.Interpolate(normalized);
                xAkima.Add(normalized);
                yAkima.Add(yInterpoled);
            }
            #endregion

            #region Linear Interpolation
            for (int i = 0; i <= DataPoints; i++)
            {
                double normalized  = ((b + ep) - (a - ep)) * (i / DataPoints) + (a - ep);
                var    yInterpoled = linearInterpolation.Interpolate(normalized);
                xLinear.Add(normalized);
                yLinear.Add(yInterpoled);
            }
            #endregion

            var pointsX = new List <double>();
            var pointSY = new List <double>();

            List <Point> logLinear = new List <Point>();
            List <Point> logAkima  = new List <Point>();

            #region Normalizar pontos dos periodos
            for (int i = 1; i <= 30; i++)
            {
                var cY = akimaInterpolation.Interpolate(i);

                pointsX.Add(i);
                pointSY.Add(cY);
                logAkima.Add(new Point(i, cY));
            }
            for (int i = 1; i <= 30; i++)
            {
                var cY = linearInterpolation.Interpolate(i);

                pointsX.Add(i);
                pointSY.Add(cY);
                logLinear.Add(new Point(i, cY));
            }
            #endregion

            //---plotar solução-- -
            PlotSolution(NameMethod,
                         x.ToArray(), y.ToArray(),
                         xAkima.ToArray(), yAkima.ToArray(),
                         xLinear.ToArray(), yLinear.ToArray(),
                         @"..\..\" + NameMethod + ".png");

            string[] output = new string[] { "", "" };
            foreach (Point p in logAkima)
            {
                output[0] += p.ToString() + "\n";
            }
            foreach (Point p in logLinear)
            {
                output[1] += p.ToString() + "\n";
            }

            return(output);
        }
Example #22
0
        /// <summary>
        ///[0. MNegativos, 1. MPositivos, 2. AceroRequeridoNegativo, 3. AceroRequeridoPosivo,
        /// 4. AceroAsignadoNegativo, 5. AceroAsignadoPositivo, 6. Cortante Positivo, 7. Cortante Negativo, 8. A/S Requerido Cortante, 9. A/S Asignado Cortante]        /// </summary>
        /// <param name="subTramo"></param>
        /// <param name="CantidadEstaciones"></param>
        /// <returns></returns>
        private static List <List <float[]> > InterpolacionSolicitaciones(cSubTramo subTramo, int CantidadEstaciones)
        {
            var ValuesX = subTramo.Estaciones.Select(y => y.CoordX).ToList().ConvertAll(Convert.ToDouble);
            var ValuesYMomentosPosit = subTramo.Estaciones.Select(y => y.Calculos.Envolvente.M3[0]).ToList().ConvertAll(Convert.ToDouble);
            var ValuesYMomentosNega  = subTramo.Estaciones.Select(y => y.Calculos.Envolvente.M3[1]).ToList().ConvertAll(Convert.ToDouble);
            var ValuesYCortate1      = subTramo.Estaciones.Select(y => y.Calculos.Envolvente.V2[1]).ToList().ConvertAll(Convert.ToDouble);
            var ValuesYCortante2     = subTramo.Estaciones.Select(y => y.Calculos.Envolvente.V2[0]).ToList().ConvertAll(Convert.ToDouble);
            var ValuesYArNegativo    = subTramo.Estaciones.Select(y => y.Calculos.Solicitacion_Asignado_Momentos.SolicitacionesSuperior.Area_Momento).ToList().ConvertAll(Convert.ToDouble);
            var ValuesYArPositivo    = subTramo.Estaciones.Select(y => y.Calculos.Solicitacion_Asignado_Momentos.SolicitacionesInferior.Area_Momento).ToList().ConvertAll(Convert.ToDouble);
            var ValuesYAAsNegativo   = subTramo.Estaciones.Select(y => y.Calculos.Solicitacion_Asignado_Momentos.AsignadoSuperior.Area_Momento).ToList().ConvertAll(Convert.ToDouble);
            var ValuesYAAsPositivo   = subTramo.Estaciones.Select(y => y.Calculos.Solicitacion_Asignado_Momentos.AsignadoInferior.Area_Momento).ToList().ConvertAll(Convert.ToDouble);
            var ValuesYARCortante    = subTramo.Estaciones.Select(y => y.Calculos.Solicitacion_Asignado_Cortante.SolicitacionesSuperior.Area_S).ToList().ConvertAll(Convert.ToDouble);
            var ValuesYAAsCortante   = subTramo.Estaciones.Select(y => y.Calculos.Solicitacion_Asignado_Cortante.AsignadoSuperior.Area_S).ToList().ConvertAll(Convert.ToDouble);

            var InterpoleteMPositivos  = Interpolate.Linear(ValuesX, ValuesYMomentosPosit);
            var InterpoleteMPNega      = Interpolate.Linear(ValuesX, ValuesYMomentosNega);
            var InterpoleteYCortante1  = Interpolate.Linear(ValuesX, ValuesYCortate1);
            var InterpoleteYCortante2  = Interpolate.Linear(ValuesX, ValuesYCortante2);
            var InterpoleteArNegativo  = Interpolate.Linear(ValuesX, ValuesYArNegativo);
            var InterpoleteArPositivo  = Interpolate.Linear(ValuesX, ValuesYArPositivo);
            var InterpoleteAAsNegativo = Interpolate.Linear(ValuesX, ValuesYAAsNegativo);
            var InterpoleteAAsPositivo = Interpolate.Linear(ValuesX, ValuesYAAsPositivo);
            var InterpoleteARCortante  = Interpolate.Linear(ValuesX, ValuesYARCortante);
            var InterpoleteAAsCortante = Interpolate.Linear(ValuesX, ValuesYAAsCortante);


            float L      = subTramo.Longitud;
            float DeltaL = L / (CantidadEstaciones - 1);
            float Xmin   = subTramo.Vistas.Perfil_AutoCAD.Reales.First().X;

            List <float[]> R1  = new List <float[]>();
            List <float[]> R2  = new List <float[]>();
            List <float[]> R3  = new List <float[]>();
            List <float[]> R4  = new List <float[]>();
            List <float[]> R5  = new List <float[]>();
            List <float[]> R6  = new List <float[]>();
            List <float[]> R7  = new List <float[]>();
            List <float[]> R8  = new List <float[]>();
            List <float[]> R9  = new List <float[]>();
            List <float[]> R10 = new List <float[]>();

            for (float Delta = 0; Math.Round(Delta, 2) <= L; Delta += DeltaL)
            {
                R1.Add(Interpolacion(Xmin, Delta, InterpoleteMPNega));
                R2.Add(Interpolacion(Xmin, Delta, InterpoleteMPositivos));
                R3.Add(Interpolacion(Xmin, Delta, InterpoleteArNegativo));
                R4.Add(Interpolacion(Xmin, Delta, InterpoleteArPositivo));
                R5.Add(Interpolacion(Xmin, Delta, InterpoleteAAsNegativo));
                R6.Add(Interpolacion(Xmin, Delta, InterpoleteAAsPositivo));
                R7.Add(Interpolacion(Xmin, Delta, InterpoleteYCortante1));
                R8.Add(Interpolacion(Xmin, Delta, InterpoleteYCortante2));
                R9.Add(Interpolacion(Xmin, Delta, InterpoleteARCortante));
                R10.Add(Interpolacion(Xmin, Delta, InterpoleteAAsCortante));
            }

            List <List <float[]> > Resultados = new List <List <float[]> >()
            {
                R1, R2, R3, R4, R5, R6, R7, R8, R9, R10
            };

            return(Resultados);
        }
Example #23
0
        /**
         * <summary>
         * <para>
         * Calculates knee points using the Kneedle algorithm. Returns the x value corresponding to the knee
         * point when successful, null otherwise.
         * </para>
         * <para>
         * Reference:
         *      Finding a ‘kneedle’in a haystack: Detecting knee points in system behavior.
         *      Satopaa, V and Albrecht, J and Irwin, D and Raghavan, B
         *      <see cref="https://raghavan.usc.edu/papers/kneedle-simplex11.pdf"/>
         * </para>
         *
         *  <list type="bullet">
         *  <param name="x">x: X axis values of the points. Points must be sorted in ascending order w.r.t. X axis.</param>
         *  <param name="y">y: Y axis values of the points.</param>
         *  <param name="direction">direction: If the curve is increasing or decreasing. Make sure to set this value according to the input curve.</param>
         *  <param name="concavity">concavity: Whether the curve has positive or negative curvature. In other words, concave or convex. Whether the tangent rotates clockwise or counterclockwise. Make sure to set this value according to the input curve.</param>
         *  <param name="sensitivity">sensitivity: Adjusts the knee detection threshold. Defaults to 1 as per the paper.</param>
         *  <param name="forceLinearInterpolation">forceLinearInterpolation: Interpolation is done using robust cubic splines. For some inputs, spline can overshoot. This param forces linear interpolation instead of cubic spline.</param>
         *  </list>
         *
         * Can return null when the algorithm fails to identify a knee/elbow for various reasons:
         *      - the number of data points is too small
         *      - there are no local maxima on the diffs, which means either the curve is a line, or the
         *        parameters provided are incompatible with the curve
         *
         *  <list type="bullet">
         *  2019-01-08: rename curvature enum to be easy to interpret and remember (Prashant Borole)
         *  2019-01-07: initial version (Prashant Borole)
         *  </list>
         *  </summary>
         */
        public static double?CalculateKneePoints(double[] x, double[] y, CurveDirection direction, Curvature concavity, double sensitivity = 1, bool forceLinearInterpolation = true)
        {
            if (x == null || y == null || x.Length != y.Length || x.Length < 2)
            {
                return(null);
            }

            var numPoints = x.Length;

            MathNet.Numerics.Interpolation.IInterpolation interpolator = null;
            if (numPoints > 5 && !forceLinearInterpolation)
            {
                interpolator = Interpolate.CubicSplineRobust(x, y);
            }
            else
            {
                interpolator = Interpolate.Linear(x, y);
            }
            var x_spaced = Generate.LinearSpaced(numPoints, x.Min(), x.Max());
            var y_spaced = Generate.Map(x_spaced, interpolator.Interpolate);

            var x_norm = MinMaxNormalize(x_spaced);
            var y_norm = MinMaxNormalize(y_spaced);

            var x_diff = x_norm;
            var y_diff = new double[numPoints];

            if (direction == CurveDirection.Decreasing)
            {
                for (int i = 0; i < numPoints; i++)
                {
                    y_diff[i] = x_norm[i] + y_norm[i];
                }
                if (concavity == Curvature.Counterclockwise)
                {
                    for (int i = 0; i < numPoints; i++)
                    {
                        y_diff[i] = 1 - y_diff[i];
                    }
                }
            }
            else
            {
                // increasing
                for (int i = 0; i < numPoints; i++)
                {
                    y_diff[i] = y_norm[i] - x_norm[i];
                }
                if (concavity == Curvature.Counterclockwise)
                {
                    for (int i = 0; i < numPoints; i++)
                    {
                        y_diff[i] = Math.Abs(y_diff[i]);
                    }
                }
            }


            // find local maxima
            var xmx_idxs = FindLocalExtrema(y_diff, true);

            if (xmx_idxs.Count == 0)
            {
                return(null);
            }
            var xmx = xmx_idxs.Select(idx => x_diff[idx]).ToArray();
            var ymx = xmx_idxs.Select(idx => y_diff[idx]).ToArray();

            // minima
            var xmn_idxs = FindLocalExtrema(y_diff, false);
            var xmn      = xmn_idxs.Select(idx => x_diff[idx]).ToArray();
            var ymn      = xmn_idxs.Select(idx => y_diff[idx]).ToArray();

            var tmx = Threshold(ymx, x_norm, sensitivity);

            // now find the knee point between each of the local maxima
            var    curMaximaIdx = 0;
            var    xmn_idxs_set = new HashSet <int>(xmn_idxs);
            double?knee         = null;

            for (int x_i = xmx_idxs[0] + 1; x_i < x.Length; x_i++)
            {
                if (curMaximaIdx < xmx_idxs.Count - 1 && x_i == xmx_idxs[curMaximaIdx + 1])
                {
                    curMaximaIdx++;
                    x_i++;
                    continue;
                }

                if (xmn_idxs_set.Contains(x_i))
                {
                    if (x_i < x.Length - 1 && y_diff[x_i + 1] > y_diff[x_i])
                    {
                        tmx[curMaximaIdx] = 0;
                    }
                }

                if (y_diff[x_i] < tmx[curMaximaIdx] || tmx[curMaximaIdx] < 0)
                {
                    knee = x[xmx_idxs[curMaximaIdx]];
                }
            }

            return(knee);
        }
Example #24
0
 public void Linear(double min, double max, double value, double expected)
 {
     Assert.AreEqual(expected, Interpolate.Linear(min, max, value).Value, 1E-6);
 }
        public override void ExecuteExample()
        {
            MathDisplay.WriteLine("<b>Linear interpolation between points</b>");

            // 1. Generate 20 samples of the function x*x-2*x on interval [0, 10]
            MathDisplay.WriteLine(@"1. Generate 20 samples of the function x*x-2*x on interval [0, 10]");
            double[] points = Generate.LinearSpaced(20, 0, 10);
            var      values = Generate.Map <double, double>(points, TargetFunction1);

            MathDisplay.WriteLine();

            // 2. Create a linear spline interpolation based on arbitrary points
            var method = Interpolate.Linear(points, values);

            MathDisplay.WriteLine(@"2. Create a linear spline interpolation based on arbitrary points");
            MathDisplay.WriteLine();

            // 3. Check if interpolation support integration
            MathDisplay.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration);
            MathDisplay.WriteLine();

            // 4. Check if interpolation support differentiation
            MathDisplay.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation);
            MathDisplay.WriteLine();

            // 5. Differentiate at point 5.2
            MathDisplay.WriteLine(@"5. Differentiate at point 5.2 = {0}", method.Differentiate(5.2));
            MathDisplay.WriteLine();

            // 6. Integrate at point 5.2
            MathDisplay.WriteLine(@"6. Integrate at point 5.2 = {0}", method.Integrate(5.2));
            MathDisplay.WriteLine();

            // 7. Interpolate ten random points and compare to function results
            MathDisplay.WriteLine(@"7. Interpolate ten random points and compare to function results");
            var rng = new MersenneTwister(1);

            for (var i = 0; i < 10; i++)
            {
                // Generate random value from [0, 10]
                var point = rng.NextDouble() * 10;
                MathDisplay.WriteLine(
                    @"Interpolate at {0} = {1}. Function({0}) = {2}",
                    point.ToString("N05"),
                    method.Interpolate(point).ToString("N05"),
                    TargetFunction1(point).ToString("N05"));
            }

            MathDisplay.WriteLine();


            // <seealso cref="http://en.wikipedia.org/wiki/Spline_interpolation">Spline interpolation</seealso>
            MathDisplay.WriteLine("<b>Akima spline interpolation</b>");

            // 1. Generate 10 samples of the function x*x-2*x on interval [0, 10]
            MathDisplay.WriteLine(@"1. Generate 10 samples of the function x*x-2*x on interval [0, 10]");
            points = Generate.LinearSpaced(10, 0, 10);
            values = Generate.Map <double, double>(points, TargetFunction1);
            MathDisplay.WriteLine();

            // 2. Create akima spline interpolation
            method = CubicSpline.InterpolateAkima(points, values);
            MathDisplay.WriteLine(@"2. Create akima spline interpolation based on arbitrary points");
            MathDisplay.WriteLine();

            // 3. Check if interpolation supports integration
            MathDisplay.WriteLine(@"3. Support integration = {0}", ((IInterpolation)method).SupportsIntegration);
            MathDisplay.WriteLine();

            // 4. Check if interpolation support differentiation
            MathDisplay.WriteLine(@"4. Support differentiation = {0}", ((IInterpolation)method).SupportsDifferentiation);
            MathDisplay.WriteLine();

            // 5. Differentiate at point 5.2
            MathDisplay.WriteLine(@"5. Differentiate at point 5.2 = {0}", method.Differentiate(5.2));
            MathDisplay.WriteLine();

            // 6. Integrate at point 5.2
            MathDisplay.WriteLine(@"6. Integrate at point 5.2 = {0}", method.Integrate(5.2));
            MathDisplay.WriteLine();

            // 7. Interpolate ten random points and compare to function results
            MathDisplay.WriteLine(@"7. Interpolate ten random points and compare to function results");
            rng = new MersenneTwister(1);
            for (var i = 0; i < 10; i++)
            {
                // Generate random value from [0, 10]
                var point = rng.NextDouble() * 10;
                MathDisplay.WriteLine(
                    @"Interpolate at {0} = {1}. Function({0}) = {2}",
                    point.ToString("N05"),
                    method.Interpolate(point).ToString("N05"),
                    TargetFunction1(point).ToString("N05"));
            }

            MathDisplay.WriteLine();


            MathDisplay.WriteLine("<b>Barycentric rational interpolation without poles</b>");

            // 1. Generate 10 samples of the function 1/(1+x*x) on interval [-5, 5]
            MathDisplay.WriteLine(@"1. Generate 10 samples of the function 1/(1+x*x) on interval [-5, 5]");
            points = Generate.LinearSpaced(10, -5, 5);
            values = Generate.Map <double, double>(points, TargetFunctionWithoutPolesEx);
            MathDisplay.WriteLine();

            // 2. Create a floater hormann rational pole-free interpolation based on arbitrary points
            // This method is used by default when create an interpolation using Interpolate.Common method
            method = Interpolate.RationalWithoutPoles(points, values);
            MathDisplay.WriteLine(@"2. Create a floater hormann rational pole-free interpolation based on arbitrary points");
            MathDisplay.WriteLine();

            // 3. Check if interpolation support integration
            MathDisplay.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration);
            MathDisplay.WriteLine();

            // 4. Check if interpolation support differentiation
            MathDisplay.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation);
            MathDisplay.WriteLine();

            // 5. Interpolate ten random points and compare to function results
            MathDisplay.WriteLine(@"5. Interpolate ten random points and compare to function results");
            rng = new MersenneTwister(1);
            for (var i = 0; i < 10; i++)
            {
                // Generate random value from [0, 5]
                var point = rng.NextDouble() * 5;
                MathDisplay.WriteLine(
                    @"Interpolate at {0} = {1}. Function({0}) = {2}",
                    point.ToString("N05"),
                    method.Interpolate(point).ToString("N05"),
                    TargetFunctionWithoutPolesEx(point).ToString("N05"));
            }

            MathDisplay.WriteLine();


            MathDisplay.WriteLine("<b>Rational interpolation with poles</b>");

            // 1. Generate 20 samples of the function f(x) = x on interval [-5, 5]
            MathDisplay.WriteLine(@"1. Generate 20 samples of the function f(x) = x on interval [-5, 5]");
            points = Generate.LinearSpaced(20, -5, 5);
            values = Generate.Map <double, double>(points, TargetFunctionWithPolesEx);
            MathDisplay.WriteLine();

            // 2. Create a burlish stoer rational interpolation based on arbitrary points
            method = Interpolate.RationalWithPoles(points, values);
            MathDisplay.WriteLine(@"2. Create a burlish stoer rational interpolation based on arbitrary points");
            MathDisplay.WriteLine();

            // 3. Check if interpolation support integration
            MathDisplay.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration);
            MathDisplay.WriteLine();

            // 4. Check if interpolation support differentiation
            MathDisplay.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation);
            MathDisplay.WriteLine();

            // 5. Interpolate ten random points and compare to function results
            MathDisplay.WriteLine(@"5. Interpolate ten random points and compare to function results");
            rng = new MersenneTwister(1);
            for (var i = 0; i < 10; i++)
            {
                // Generate random value from [0, 5]
                var point = rng.Next(0, 5);
                MathDisplay.WriteLine(
                    @"Interpolate at {0} = {1}. Function({0}) = {2}",
                    point.ToString("N05"),
                    method.Interpolate(point).ToString("N05"),
                    TargetFunctionWithPolesEx(point).ToString("N05"));
            }

            MathDisplay.WriteLine();
        }