示例#1
0
        public void calc()
        {
            int len = Barray.Length;
            // table phid-fz
            Vector <double> Fz_vector      = mybuilder.Dense(len, i => Harray[i] * lz);
            Vector <double> phid_Fz_vector = mybuilder.Dense(len, i => Barray[i] * Sz + Fz_vector[i] * Pslot);

            // table phid-fy
            Vector <double> Fy_vector      = mybuilder.Dense(len, i => Harray[i] * ly);
            Vector <double> phid_Fy_vector = mybuilder.Dense(len, i => Barray[i] * Sy);

            // reshape phid-fy, using interpolation to create new vector corresponding with phid_fy = phid_fz
            Vector <double> phid_vector = mybuilder.DenseOfVector(phid_Fz_vector);//same phid table for all

            LinearSpline    ls           = LinearSpline.Interpolate(phid_Fy_vector.ToArray(), Fy_vector.ToArray());
            Vector <double> eqvFy_vector = mybuilder.Dense(len, i => ls.Interpolate(phid_vector[i]));

            // table f_phid
            Vector <double> f_phid = mybuilder.Dense(len, i => phid_vector[i] / Pd + Fz_vector[i] + eqvFy_vector[i] - (phiR - phiHFe - phid_vector[i]) / (PM + PFe + Pb));

            // calc phiD
            ls    = LinearSpline.Interpolate(f_phid.ToArray(), phid_vector.ToArray());
            phiD  = ls.Interpolate(0);
            FM    = (phiR - phiHFe - phiD) / (PM + PFe + Pb);
            phib  = FM * Pb;
            phiFe = phiHFe + FM * PFe;
            phiM  = phiD + phib + phiFe;

            ls = LinearSpline.Interpolate(phid_vector.ToArray(), Fz_vector.ToArray());
            Fz = ls.Interpolate(phiD);
            ls = LinearSpline.Interpolate(phid_vector.ToArray(), eqvFy_vector.ToArray());
            Fy = ls.Interpolate(phiD);
        }
        /// <summary>
        /// Creates a curve.  The curve will be flat from the anchor date to the first date and from the last date in dates until maximumDate
        /// </summary>
        /// <param name="currency"></param>
        /// <param name="anchorDate">Date from which the curve applies.  Interpolation before this date won't work.</param>
        /// <param name="dates">Must be sorted in increasing order.</param>
        /// <param name="rates">The rates.  If the curve is going to be used to supply discount factors then these rates must be continuously compounded.</param>
        /// <param name="maximumDate">The date beyond which interpolation will not be allowed.  If it is null or left out then the last date in dates will be used.</param>
        public DatesAndRates(Currency currency, Date anchorDate, Date[] dates, double[] rates, Date maximumDate = null)
        {
            this.anchorDate = anchorDate;
            for (int i = 1; i < dates.Length; i++)
            {
                if (dates[i].value <= dates[i - 1].value)
                {
                    throw new ArgumentException("Dates must be strictly increasing");
                }
            }
            List <double> datesList = new List <double>(dates.GetValues());
            List <double> ratesList = new List <double>(rates.Clone() as double[]);

            if (dates[0] > anchorDate)
            {
                datesList.Insert(0, anchorDate.value);
                ratesList.Insert(0, rates[0]);
            }
            if (maximumDate != null)
            {
                datesList.Add(maximumDate);
                ratesList.Add(rates.Last());
            }
            this.anchorDateValue = anchorDate;
            this.dates           = datesList.ToArray();
            this.rates           = ratesList.ToArray();
            this.currency        = currency;
            spline = LinearSpline.InterpolateSorted(this.dates, this.rates);
        }
示例#3
0
        private double computeTapValue()
        {
            double modifiedAcc = getModifiedAcc();

            // Assume SS for non-stream parts
            double accOnStreams = 1 - (1 - modifiedAcc) * totalHits / Attributes.StreamNoteCount;

            double mashLevel = 1 - SpecialFunctions.Logistic((accOnStreams - 0.75) / 0.1) / SpecialFunctions.Logistic(2.5);

            double tapSkill = LinearSpline.InterpolateSorted(Attributes.MashLevels, Attributes.TapSkills)
                              .Interpolate(mashLevel);

            double tapValue = tapSkillToPP(tapSkill);

            // Buff high acc
            double accBuff = Math.Exp((accOnStreams - 1) * 60) * tapValue * 0.2f;

            tapValue += accBuff;

            // Penalize misses exponentially
            tapValue *= Math.Pow(0.93f, countMiss);

            double approachRateFactor = 1.0f;

            if (Attributes.ApproachRate > 10.33f)
            {
                approachRateFactor += 0.2f * (Attributes.ApproachRate - 10.33f);
            }
            tapValue *= approachRateFactor;

            return(tapValue);
        }
示例#4
0
        public PiecewiseLinearInjectWithdrawConstraint([NotNull] IEnumerable <InjectWithdrawRangeByInventory> injectWithdrawRanges)
        {
            if (injectWithdrawRanges == null)
            {
                throw new ArgumentNullException(nameof(injectWithdrawRanges));
            }

            _injectWithdrawRanges = injectWithdrawRanges.OrderBy(injectWithdrawRange => injectWithdrawRange.Inventory)
                                    .ToArray();

            if (_injectWithdrawRanges.Length < 2)
            {
                throw new ArgumentException("Inject/withdraw ranges collection must contain at least two elements.", nameof(injectWithdrawRanges));
            }

            double[] inventories = _injectWithdrawRanges.Select(injectWithdrawRange => injectWithdrawRange.Inventory)
                                   .ToArray();

            double[] maxInjectWithdrawRates = _injectWithdrawRanges
                                              .Select(injectWithdrawRange => injectWithdrawRange.InjectWithdrawRange.MaxInjectWithdrawRate)
                                              .ToArray();

            double[] minInjectWithdrawRates = _injectWithdrawRanges
                                              .Select(injectWithdrawRange => injectWithdrawRange.InjectWithdrawRange.MinInjectWithdrawRate)
                                              .ToArray();

            _maxInjectWithdrawLinear = LinearSpline.InterpolateSorted(inventories, maxInjectWithdrawRates);
            _minInjectWithdrawLinear = LinearSpline.InterpolateSorted(inventories, minInjectWithdrawRates);
        }
示例#5
0
            protected void UpdateInterpolation()
            {
                int count = _keyFrames.Count;
                var xs    = new double[count];
                var ys    = new double[count];

                for (int i = 0; i < count; ++i)
                {
                    xs[i] = (double)_keyFrames[i].time;
                    ys[i] = (double)_keyFrames[i].value;
                }
                if (count <= 1)
                {
                    _interpolation = StepInterpolation.Interpolate(xs, ys);
                }
                else if (count <= 2)
                {
                    _interpolation = LinearSpline.Interpolate(xs, ys);
                }
                else if (count <= 3)
                {
                    _interpolation = MathNet.Numerics.Interpolate.Polynomial(xs, ys);
                }
                else if (count <= 4)
                {
                    _interpolation = CubicSpline.InterpolateNatural(xs, ys);
                }
                else
                {
                    _interpolation = CubicSpline.InterpolateAkima(xs, ys);
                }
            }
示例#6
0
        public static IInterpolation GetLinearInterpolationMethod(Peak peak)
        {
            peak.GetXAndYValuesAsLists(out var xValues, out var yValues);

            IInterpolation interpolation = LinearSpline.Interpolate(xValues, yValues);

            return(interpolation);
        }
        private IInterpolation interpolation_U(UV point, Index index)
        {
            IndexRange horizontalExpansion = this.horizontalRange(index);

            //getting all vertical ranges of the horizontal
            IndexRange[] verticals = new IndexRange[horizontalExpansion.Length];
            Index        next      = horizontalExpansion.Min.Copy();

            for (int i = 0; i < horizontalExpansion.Length; i++)
            {
                verticals[i] = this.verticalRange(next);
                next.I++;
            }
            //getting interpolators for u values
            IInterpolation[] verticalsU = new IInterpolation[horizontalExpansion.Length];
            for (int i = 0; i < verticals.Length; i++)
            {
                verticalsU[i] = this.toInterpolation(verticals[i]);
            }
            //generating u interpolation
            double[] x = new double[horizontalExpansion.Length];
            double[] y = new double[horizontalExpansion.Length];
            next = horizontalExpansion.Min.Copy();
            for (int i = 0; i < horizontalExpansion.Length; i++)
            {
                x[i] = this._cellularFloor.FindCell(next).U;
                y[i] = verticalsU[i].Interpolate(point.V);
                next.I++;
            }
            IInterpolation interpolatorU = null;

            switch (Activity.InterpolationMethod)
            {
            case SpatialAnalysis.FieldUtility.InterpolationMethod.CubicSpline:
                if (x.Length > 1)
                {
                    interpolatorU = CubicSpline.InterpolateBoundariesSorted(x, y,
                                                                            SplineBoundaryCondition.Natural, 0,
                                                                            SplineBoundaryCondition.Natural, 0);
                }
                else
                {
                    interpolatorU = LinearSpline.InterpolateSorted(x, y);
                }
                break;

            //case FieldUtility.InterpolationMethod.Barycentric:
            //    interpolatorU = Barycentric.InterpolatePolynomialEquidistantSorted(x, y);
            //    break;
            case SpatialAnalysis.FieldUtility.InterpolationMethod.Linear:
                interpolatorU = LinearSpline.InterpolateSorted(x, y);
                break;

            default:
                break;
            }
            return(interpolatorU);
        }
示例#8
0
        private void InterpolateCvY(double value)
        {
            var interpColumnName = CvYColumnConverter.NameFromValue(value);

            var interpTable = new TableProcessing.Table("Interpolate " + interpColumnName);

            interpTable.AddColumn(tables.OrdinKtgr.Column("PY"));

            var floorValue = double.NegativeInfinity;
            var ceilValue  = double.PositiveInfinity;

            for (var i = 0; i < tables.OrdinKtgr.DataTable.Columns.Count; i++)
            {
                var column = tables.OrdinKtgr.DataTable.Columns[i];

                if (column.ColumnName.IndexOf("CvY_", StringComparison.Ordinal) != 0)
                {
                    continue;
                }

                var CV_value = CvYColumnConverter.ValueFromName(column.ColumnName);

                if (CV_value < value)
                {
                    floorValue = CV_value;
                }
                else if (CV_value > value)
                {
                    ceilValue = CV_value;
                    break;
                }
            }

            var floorStr = CvYColumnConverter.NameFromValue(floorValue);

            var ceilStr = CvYColumnConverter.NameFromValue(ceilValue);

            interpTable.AddColumn(tables.OrdinKtgr.Column(floorStr));
            var column_res = interpTable.Column(interpColumnName);

            interpTable.AddColumn(tables.OrdinKtgr.Column(ceilStr));

            interpTable.IterateRows(row =>
            {
                double[] x = { floorValue, ceilValue };
                double[] y =
                {
                    row[floorStr].DoubleValue,
                    row[ceilStr].DoubleValue
                };

                var res = LinearSpline.Interpolate(x, y).Interpolate(value);
                row.Set(column_res.Name, res);
            }, column_res.Name);

            tables.OrdinKtgr.AddColumn(interpTable.Column(interpColumnName));
        }
示例#9
0
            /// <summary>
            /// Get max speed possible for given torque. Condition: Umax, Imax and max-torque-per-ample
            /// </summary>
            /// <param name="t"></param>
            /// <returns></returns>
            public double GetMaxSpeedForTorque(double t)
            {
                if (speed_spline == null)
                {
                    speed_spline = LinearSpline.Interpolate(torques, speeds);
                }

                return(speed_spline.Interpolate(t));
            }
示例#10
0
 private void checkAndCreateSpline()
 {
     if (id_spline == null)
     {
         id_spline        = LinearSpline.Interpolate(max_torques, idqs.Select(f => f.d));
         iq_spline        = LinearSpline.Interpolate(max_torques, idqs.Select(f => f.q));
         maxTorque_spline = LinearSpline.Interpolate(idqs.Select(f => f.Magnitude), max_torques);
     }
 }
示例#11
0
        public void FitsAtSamplePoints()
        {
            IInterpolation ip = LinearSpline.Interpolate(_t, _y);

            for (int i = 0; i < _y.Length; i++)
            {
                Assert.AreEqual(_y[i], ip.Interpolate(_t[i]), "A Exact Point " + i);
            }
        }
 public void SetRate(int index, double rate)
 {
     if (dateOffset == 1 && index == 0)
     {
         rates[0] = rate;
     }
     rates[index + dateOffset] = rate;
     spline = LinearSpline.InterpolateSorted(dateValues, rates);
 }
        public override void Calculate()
        {
            Times = Generate.LinearSpaced(base.Samples, base.Start, base.Start + base.Duration);

            LinearSpline interpolator = (UserTimes.Length < 2)
                                ? LinearSpline.InterpolateSorted(new double[] { UserTimes[0] + 1, UserTimes[0] }, new double[] { UserValues[0], UserValues[0] })
                                : LinearSpline.InterpolateSorted(UserTimes, UserValues);

            values = Times.Select(t => interpolator.Interpolate(t)).ToArray();
        }
示例#14
0
        public void SupportsLinearCase(int samples)
        {
            double[] x, y, xtest, ytest;
            LinearInterpolationCase.Build(out x, out y, out xtest, out ytest, samples);

            IInterpolation ip = LinearSpline.Interpolate(x, y);

            for (int i = 0; i < xtest.Length; i++)
            {
                Assert.AreEqual(ytest[i], ip.Interpolate(xtest[i]), 1e-15, "Linear with {0} samples, sample {1}", samples, i);
            }
        }
示例#15
0
        public Func <double, double> MakeInterpolator(IEnumerable <double> x, IEnumerable <double> y)
        {
            SplineBoundaryCondition bc;
            int xlength = x.Count();
            int mode    = InterpolationModeComboBox.SelectedIndex;

            if (mode == 0 || mode == 1)
            {
                int order;
                order = mode * 2 + 1; // linear => 1; cubic => 3
                int npoints;
                if (!int.TryParse(extrapolationPointsTextBox.Text, out npoints))
                {
                    throw new Exception("Cannot parse number of points");
                }
                if (npoints > xlength)
                {
                    throw new Exception("Too many points required");
                }
                if (npoints < order)
                {
                    throw new Exception("More points must be used");
                }
                var leftInterp = Fit.PolynomialFunc(x.Take(npoints).ToArray(), y.Take(npoints).ToArray(),
                                                    order);
                var rightInterp = Fit.PolynomialFunc(x.Reverse().Take(npoints).Reverse().ToArray(),
                                                     y.Reverse().Take(npoints).Reverse().ToArray(),
                                                     order);
                double middlex = x.Skip((int)(xlength / 2)).First();
                return(x2 => (x2 < middlex)?leftInterp(x2) : rightInterp(x2));
            }
            else if (mode == 5)
            {
                IInterpolation I = LinearSpline.Interpolate(x, y);
                return(x2 => I.Interpolate(x2));
            }
            else
            {
                if (InterpolationModeComboBox.SelectedIndex == 1)
                {
                    bc = SplineBoundaryCondition.ParabolicallyTerminated;
                }
                else
                {
                    bc = SplineBoundaryCondition.Natural;
                }

                IInterpolation I = CubicSpline.InterpolateBoundaries(
                    x, y,
                    bc, 0, bc, 0); // Values are unused for natural and parabolic termination
                return(x2 => I.Interpolate(x2));
            }
        }
示例#16
0
        // This evaluates the SQUARED intergral of (S*Etan)
        public static double TFInt(
            Vector <Double> ETan_Z,
            Vector <Complex> ETan_RMS,
            Vector <Double> TF_Z,
            Vector <Complex> TF_Sr
            )
        {
            int    num_points = 5000;
            double zmin       = Math.Max(TF_Z.Minimum(), ETan_Z.Minimum());
            double zmax       = Math.Min(TF_Z.Maximum(), ETan_Z.Maximum());

            LinearSpline etansinterpR = LinearSpline.Interpolate(
                ETan_Z, ETan_RMS.Real());
            LinearSpline etansinterpI = LinearSpline.Interpolate(
                ETan_Z, ETan_RMS.Imaginary());
            LinearSpline TF_SrInterpR = LinearSpline.Interpolate(
                TF_Z, TF_Sr.Real());
            LinearSpline TF_SrInterpI = LinearSpline.Interpolate(
                TF_Z, TF_Sr.Imaginary());

            /*var ETanGridded = CreateVector.DenseOfEnumerable(
             *  zvals.Select(z => new Complex(
             *     etansinterpR.Interpolate(z), etansinterpI.Interpolate(z)))
             *     );
             * var SrGridded = CreateVector.DenseOfEnumerable(
             *  zvals.Select(z => new Complex(
             * TF_SrInterpR.Interpolate(z), TF_SrInterpI.Interpolate(z)))
             * );*/
            //var Z = SrGridded.PointwiseMultiply(ETanGridded);
            // This is the integrand, SR*Etan
            Func <double, Complex> SrEtan = (z) =>
            {
                var s = new Complex(
                    TF_SrInterpR.Interpolate(z), TF_SrInterpI.Interpolate(z));
                var e = new Complex(
                    etansinterpR.Interpolate(z), etansinterpI.Interpolate(z));
                return(s * e);
            };
            // And to integrate it, the real and imaginary components must be
            // separately computed.
            Complex sum =
                new Complex(
                    NewtonCotesTrapeziumRule.IntegrateComposite(
                        (z => SrEtan(z).Real), zmin, zmax, num_points),
                    NewtonCotesTrapeziumRule.IntegrateComposite(
                        (z => SrEtan(z).Imaginary), zmin, zmax, num_points)
                    );
            // Usually we need the magnitude squared (for the temperature calculations)
            // But, the caller may find the square root, if needed, for example for voltages
            double dT = sum.MagnitudeSquared();

            return(dT);
        }
示例#17
0
        /// <summary>
        /// Interpolation of the interface points onto the equidistant Fourier points
        /// </summary>
        protected void InterpolateOntoFourierPoints(MultidimensionalArray interP, double[] samplP)
        {
            int numP = interP.Lengths[0];

            // set interpolation data
            double[] independentVal = new double[numP + 2];
            double[] dependentVal   = new double[numP + 2];
            for (int sp = 1; sp <= numP; sp++)
            {
                independentVal[sp] = interP[sp - 1, 0];
                dependentVal[sp]   = interP[sp - 1, 1];
            }
            // extend the interpolation data for sample points at the boundary of the domain
            independentVal[0]        = interP[numP - 1, 0] - DomainSize;
            dependentVal[0]          = interP[numP - 1, 1];
            independentVal[numP + 1] = interP[0, 0] + DomainSize;
            dependentVal[numP + 1]   = interP[0, 1];

            switch (this.InterpolationType)
            {
            case Interpolationtype.LinearSplineInterpolation:

                //LinearSplineInterpolation LinSpline = new LinearSplineInterpolation();
                //LinSpline.Initialize(independentVal, dependentVal);
                var LinSpline = LinearSpline.Interpolate(independentVal, dependentVal);

                for (int sp = 0; sp < numFp; sp++)
                {
                    samplP[sp] = LinSpline.Interpolate(FourierP[sp]);
                    //invDFT_coeff[sp] = (Complex)samplP[sp];
                }

                break;

            case Interpolationtype.CubicSplineInterpolation:

                //CubicSplineInterpolation CubSpline = new CubicSplineInterpolation();
                //CubSpline.Initialize(independentVal, dependentVal);
                var CubSpline = CubicSpline.InterpolateNatural(independentVal, dependentVal);

                for (int sp = 0; sp < numFp; sp++)
                {
                    samplP[sp] = CubSpline.Interpolate(FourierP[sp]);
                    //invDFT_coeff[sp] = (Complex)samplP[sp];
                }

                break;

            default:
                throw new NotImplementedException();
            }
        }
示例#18
0
 public double Interpolate(double x)
 {
     //double value = interpolation.Interpolate(x);
     if (_xRange.Length < 3 || _yRange.Length < 3)
     {
         //return LinearSpline.InterpolateSorted(_xRange, _yRange).Interpolate(x);
         return(LinearSpline.Interpolate(_xRange, _yRange).Interpolate(x));
     }
     else
     {
         return(CubicSpline.InterpolateNatural(_xRange, _yRange).Interpolate(x));
     }
 }
示例#19
0
        /// <summary>
        /// Test using transient simulation
        /// The netlist should contain a transient simulation. The first exporter is tested to the reference
        /// </summary>
        /// <param name="netlist">Netlist</param>
        /// <param name="reft">Reference time values</param>
        /// <param name="refv">Reference values</param>
        protected void TestTransient(Netlist netlist, double[] reft, double[] refv)
        {
            var interpolation = LinearSpline.Interpolate(reft, refv);

            netlist.OnExportSimulationData += (object sender, SimulationData data) =>
            {
                double time     = data.GetTime();
                double actual   = netlist.Exports[0].Extract(data);
                double expected = interpolation.Interpolate(time);
                double tol      = Math.Max(Math.Abs(actual), Math.Abs(expected)) * 1e-3 + 1e-12;
                Assert.AreEqual(expected, actual, tol);
            };
            netlist.Simulate();
        }
示例#20
0
        public void FirstDerivative()
        {
            IInterpolation ip = LinearSpline.Interpolate(_t, _y);

            Assert.That(ip.Differentiate(-3.0), Is.EqualTo(1.0));
            Assert.That(ip.Differentiate(-2.0), Is.EqualTo(1.0));
            Assert.That(ip.Differentiate(-1.5), Is.EqualTo(1.0));
            Assert.That(ip.Differentiate(-1.0), Is.EqualTo(-3.0));
            Assert.That(ip.Differentiate(-0.5), Is.EqualTo(-3.0));
            Assert.That(ip.Differentiate(0.0), Is.EqualTo(1.0));
            Assert.That(ip.Differentiate(0.5), Is.EqualTo(1.0));
            Assert.That(ip.Differentiate(1.0), Is.EqualTo(1.0));
            Assert.That(ip.Differentiate(2.0), Is.EqualTo(1.0));
            Assert.That(ip.Differentiate(3.0), Is.EqualTo(1.0));
        }
示例#21
0
 /// <summary>
 /// Interpolate the curve.
 /// </summary>
 /// <param name="date">The date at which the rate is required.</param>
 /// <returns></returns>
 public double InterpAtDate(Date date)
 {
     if (spline == null)
     {
         spline = LinearSpline.InterpolateSorted(this.dates, this.rates);
     }
     if (date.value < anchorDateValue)
     {
         throw new ArgumentException("Interpolation date  (" + date.ToString() + ") is before the anchor date of the curve.(" + (new Date(anchorDateValue)).ToString() + ")");
     }
     if (date.value > dates.Last())
     {
         throw new ArgumentException("Interpolation date (" + date.ToString() + ") is after the last date on the curve.(" + (new Date(dates.Last())).ToString() + ")");
     }
     return(spline.Interpolate(date));
 }
示例#22
0
        private static IInterpolation GetInterpolator(ColorInterpolation interpolation, double[] x, double[] y)
        {
            switch (interpolation)
            {
            case ColorInterpolation.Akima:
                return(CubicSpline.InterpolateAkimaSorted(x, y));

            case ColorInterpolation.Spline:
                return(CubicSpline.InterpolateNaturalSorted(x, y));

            case ColorInterpolation.Linear:
                return(LinearSpline.InterpolateSorted(x, y));

            default:
                throw new ArgumentException("interpolation");
            }
        }
 public void SetDates(Date[] dates)
 {
     if (dates[0] > anchorDate)
     {
         List <Date> dateList = dates.ToList();
         dateList.Insert(0, anchorDate);
         this.dates = dateList.ToArray();
         dateOffset = 1;
     }
     else
     {
         this.dates = dates;
     }
     dateValues = this.dates.GetValues();
     rates      = Vector.Ones(this.dates.Length).Multiply(0.02);
     spline     = LinearSpline.InterpolateSorted(dateValues, rates);
 }
示例#24
0
        public static object[,] InterpLinear([ExcelArgument(Description = "A vector of x values.  Must be in increasing order")] double[] knownX,
                                             [ExcelArgument(Description = "A vector of y values.  Must be the same length as knownX")] Double[] knownY,
                                             [ExcelArgument(Description = "x values at which interpolation is required.")] Double[,] requiredX)
        {
            LinearSpline spline = LinearSpline.InterpolateSorted(knownX, knownY);

            object[,] result = new object[requiredX.GetLength(0), requiredX.GetLength(1)];

            for (int x = 0; x < requiredX.GetLength(0); x += 1)
            {
                for (int y = 0; y < requiredX.GetLength(1); y += 1)
                {
                    result[x, y] = spline.Interpolate(requiredX[x, y]);
                }
            }
            return(result);
        }
        /// <summary>
        /// Interpolates linear piecewise between the given points
        /// this class is a wrapper to provide .NET XML Functions to the MathDotNet Library
        /// </summary>
        /// <param name="x">there are the supporting points</param>
        /// <param name="y">the value at each supporting point. Must have the same length as the x-values</param>
        public LinearInterpolation(double[] x, double[] y)
        {
            //sort the values ascending
            bool isAscending = false;

            while (!isAscending)
            {
                for (int i = 1; i < x.Length; i++)
                {
                    if (x[i - 1] > x[i]) //compare whether each value is bigger than the previous
                    {
                        for (int j = 0; j < i; j++)
                        {
                            if (x[j] > x[i]) //if the value at j is bigger than the value at i the correct position was found
                            {
                                //displace the value;
                                List <double> listX = x.ToList();
                                listX.Remove(x[i]);
                                listX.Insert(j, x[i]);
                                x = listX.ToArray();
                                List <double> listY = y.ToList();
                                listY.Remove(y[i]);
                                listY.Insert(j, y[i]);
                                y = listY.ToArray();
                                break;
                            }
                        }
                        break;
                    }

                    if (x[i - 1].Equals(x[i])) //if a X-value exists twice
                    {
                        throw new ArgumentException("LinearInterpolation: it is forbidden, that a X-value appears twice");
                    }

                    if (i == x.Length - 1) //if the loop has run to its end
                    {
                        isAscending = true;
                    }
                }
            }
            this._x = x;
            this._y = y;
            _spline = LinearSpline.InterpolateInplace(x, y);
        }
示例#26
0
文件: OsuMovement.cs 项目: tjgtll/osu
        private static double calcCorrection0Or3(double d, double x, double y,
                                                 LinearSpline kInterp, LinearSpline scaleInterp, LinearSpline[,] coeffsInterps)
        {
            double correction_raw = kInterp.Interpolate(d);

            for (int i = 0; i < coeffsInterps.GetLength(0); i++)
            {
                double[] cs = new double[numCoeffs];
                for (int j = 0; j < numCoeffs; j++)
                {
                    cs[j] = coeffsInterps[i, j].Interpolate(d);
                }
                correction_raw += cs[3] * Math.Sqrt(Math.Pow((x - cs[0]), 2) +
                                                    Math.Pow((y - cs[1]), 2) +
                                                    cs[2]);
            }
            return(SpecialFunctions.Logistic(correction_raw) * scaleInterp.Interpolate(d));
        }
示例#27
0
        public void DefiniteIntegral()
        {
            IInterpolation ip = LinearSpline.Interpolate(_t, _y);

            Assert.That(ip.Integrate(-4.0, -3.0), Is.EqualTo(-0.5));
            Assert.That(ip.Integrate(-3.0, -2.0), Is.EqualTo(0.5));
            Assert.That(ip.Integrate(-2.0, -1.0), Is.EqualTo(1.5));
            Assert.That(ip.Integrate(-1.0, 0.0), Is.EqualTo(0.5));
            Assert.That(ip.Integrate(0.0, 1.0), Is.EqualTo(-0.5));
            Assert.That(ip.Integrate(1.0, 2.0), Is.EqualTo(0.5));
            Assert.That(ip.Integrate(2.0, 3.0), Is.EqualTo(1.5));
            Assert.That(ip.Integrate(3.0, 4.0), Is.EqualTo(2.5));
            Assert.That(ip.Integrate(0.0, 4.0), Is.EqualTo(4.0));
            Assert.That(ip.Integrate(-3.0, -1.0), Is.EqualTo(2.0));
            Assert.That(ip.Integrate(-3.0, 4.0), Is.EqualTo(6.5));
            Assert.That(ip.Integrate(0.5, 1.5), Is.EqualTo(0.0));
            Assert.That(ip.Integrate(-2.5, -1.0), Is.EqualTo(1.875));
        }
示例#28
0
文件: OsuMovement.cs 项目: tjgtll/osu
        private static void prepareInterp(double[] ds, double[] ks, double[] scales, double[,,] coeffs,
                                          ref LinearSpline kInterp, ref LinearSpline scaleInterp, ref LinearSpline[,] coeffsInterps)
        {
            kInterp     = LinearSpline.InterpolateSorted(ds, ks);
            scaleInterp = LinearSpline.InterpolateSorted(ds, scales);

            coeffsInterps = new LinearSpline[coeffs.GetLength(0), numCoeffs];
            for (int i = 0; i < coeffs.GetLength(0); i++)
            {
                for (int j = 0; j < numCoeffs; j++)
                {
                    double[] coeff_ij = new double[coeffs.GetLength(2)];
                    for (int k = 0; k < coeffs.GetLength(2); k++)
                    {
                        coeff_ij[k] = coeffs[i, j, k];
                    }
                    coeffsInterps[i, j] = LinearSpline.InterpolateSorted(ds, coeff_ij);
                }
            }
        }
示例#29
0
        /// <summary>
        /// Setup the interpolated waveform
        /// </summary>
        /// <param name="ckt"></param>
        public override void Setup(Circuit ckt)
        {
            if (Time == null || Time.Length < 2 || Value == null || Value.Length < 2)
            {
                throw new CircuitException("No timepoints");
            }

            // Sort the time points
            Array.Sort(Time, Value);

            // Create the linear interpolation
            interpolation = LinearSpline.Interpolate(Time, Value);

            per = Time[Time.Length - 1];
            pw  = double.PositiveInfinity;
            for (int i = 1; i < Time.Length; i++)
            {
                pw = Math.Min(pw, Time[i] - Time[i - 1]);
            }
            cindex = 0;
        }
示例#30
0
        private Fdq getCurrentForZone2(double torque, double speed, double Imax, double Umax)
        {
            VoltageLimitEllipse vle = null;
            string key = string.Format("{0},{1},{2}", Imax, Umax, speed);

            if (dict_vle.ContainsKey(key))
            {
                vle = dict_vle[key];
            }
            else
            {
                vle           = buildVoltageLimitEllipse(speed, 100, Imax, Umax);
                dict_vle[key] = vle;
            }

            var range = Enumerable.Range(0, vle.maxtorque_point);

            // find point on Voltage limit ellipse that bring given torque
            LinearSpline spline = LinearSpline.Interpolate(range.Select(i => vle.torques[i]), range.Select(i => vle.curve[i].d));
            double       id     = spline.Interpolate(torque);

            // get iq from this id
            var maxiq_point = vle.curve[vle.maxtorque_point];
            var minid_point = vle.curve[vle.minid_point];

            if (id < maxiq_point.d || minid_point.d < id)
            {
                return(default(Fdq));
            }

            LinearSpline spline2 = LinearSpline.Interpolate(vle.curve.Select(f => f.d), vle.curve.Select(f => f.q));
            double       iq      = spline2.Interpolate(id);

            return(new Fdq
            {
                d = id,
                q = iq,
            });
        }