private CubicSpline CreateCurve(double[] x, double[] y) { //CubicSpline curve = CubicSpline.InterpolateNatural(x, y); // var curve = CubicSpline.InterpolateNaturalInplace(x, y); CubicSpline curve = CubicSpline.InterpolateNaturalSorted(x, y); return(curve); }
/******************************************************************************************** * Constructors ********************************************************************************************/ public NumericalRunningCoupling() : base(RunningCouplingType.NonPerturbative_ITP) { ExtractValues("..\\..\\AlphaS_qQCD.txt", out double[] momenta, out double[] alphas); alphas = NormalizeToLOperturbative(momenta, alphas); AlphaInterpolator = CubicSpline.InterpolateNaturalSorted(momenta, alphas); }
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 TestCubicSplineInterpolation() { double[] x = new double[13]; double[] y = new double[13]; Console.WriteLine($"X Y"); for (int i = 0; i <= 12; i++) { x[i] = i * Math.PI / 12; y[i] = Math.Sin(x[i]); Console.WriteLine($"{x[i]} {y[i]}"); } var spline = CubicSpline.InterpolateNaturalSorted(x, y); double testX = 1.5 * Math.PI / 12; double testY = spline.Interpolate(testX); Console.WriteLine($"Interpolated:"); Console.WriteLine($"{testX} {testY}"); }
public static TiltData CubicSplineNatural(TiltData raw, float spacing, int n) { var xmin = raw.Distances.Min(); var npt = n; var newdistances = new float[npt]; var newtilt = new float[npt]; var interpolator = CubicSpline.InterpolateNaturalSorted(Array.ConvertAll(raw.Distances, Convert.ToDouble), Array.ConvertAll(raw.Values, Convert.ToDouble)); for (var i = 0; i < npt; i++) { newdistances[i] = xmin + (i * spacing); newtilt[i] = Convert.ToSingle(interpolator.Interpolate(Convert.ToDouble(newdistances[i]))); } return(new TiltData(raw.Title, npt, spacing, raw.X, raw.Y, raw.Bearing, newdistances, newtilt)); }
/// <summary> /// Gets the charge state (determined by AutoCorrelation algorithm) for a peak in some data. /// </summary> /// <param name="peak">is the peak whose charge we want to detect.</param> /// <param name="peakData">is the PeakData object containing raw data, peaks, etc which are used in the process.</param> /// <param name="debug"></param> /// <returns>Returns the charge of the feature.</returns> public static int GetChargeState(ThrashV1Peak peak, PeakData peakData, bool debug) { var minus = 0.1; var plus = 1.1; // right direction to look var startIndex = PeakIndex.GetNearest(peakData.MzList, peak.Mz - peak.FWHM - minus, peak.DataIndex); var stopIndex = PeakIndex.GetNearest(peakData.MzList, peak.Mz + peak.FWHM + plus, peak.DataIndex); var numPts = stopIndex - startIndex; var numL = numPts; if (numPts < 5) { return(-1); } if (numPts < 256) { numL = 10 * numPts; } // TODO: PattersonChargeStateCalculator does a lot of funny stuff around here. // variable to help us perform spline interpolation. // count is stopIndex - startIndex + 1 because we need to include the values at stopIndex as well // NOTE: This output is different from what the DeconEngineV2 code outputs; there are notes in that code // wondering if there was a bug in the previous implementation imported from VB, of starting at startIndex + 1. // That code performed interpolation on the range from startIndex + 1 to stopIndex, inclusive, and minMz set to PeakData.MzList[startIndex + 1]. // This code can produce output that more closely matches the DeconEngineV2 output by using // "startIndex, stopIndex - startIndex + 2" as the parameters to "GetRange()", and setting minMz to PeakData.MzList[startIndex + 1]. // Since using startIndex and stopIndex directly produces output that mostly differs on fit score by a small amount, // we are changing this code to use them. var interpolator = CubicSpline.InterpolateNaturalSorted( peakData.MzList.GetRange(startIndex, stopIndex - startIndex + 1).ToArray(), peakData.IntensityList.GetRange(startIndex, stopIndex - startIndex + 1).ToArray()); var minMz = peakData.MzList[startIndex]; var maxMz = peakData.MzList[stopIndex]; // List to store the interpolated intensities of the region on which we performed the cubic spline interpolation. var iv = new List <double>(numL); for (var i = 0; i < numL; i++) { var xVal = minMz + (maxMz - minMz) * i / numL; var fVal = interpolator.Interpolate(xVal); iv.Add(fVal); } if (debug) { Console.Error.WriteLine("mz,intensity"); for (var i = 0; i < numL; i++) { var xVal = minMz + (maxMz - minMz) * i / numL; Console.Error.WriteLine(xVal + "," + iv[i]); } } // List to store the auto correlation values at the points in the region. var autoCorrelationScores = ACss(iv.ToArray()); if (debug) { Console.Error.WriteLine("AutoCorrelation values"); for (var i = 0; i < autoCorrelationScores.Count; i++) { var score = autoCorrelationScores[i]; Console.Error.WriteLine((maxMz - minMz) * i / numL + "," + score); } } var minN = 0; while (minN < numL - 1 && autoCorrelationScores[minN] > autoCorrelationScores[minN + 1]) { minN++; } var success = HighestChargeStatePeak(minMz, maxMz, minN, autoCorrelationScores, MaxCharge, out var bestAcScore, out _); if (!success) { return(-1); // Didn't find anything } // List to temporarily store charge list. These charges are calculated at peak values of auto correlation. // Now go back through the CS peaks and make a list of all CS that are at least 10% of the highest var charges = GenerateChargeStates(minMz, maxMz, minN, autoCorrelationScores, MaxCharge, bestAcScore); // Get the final CS value to be returned var returnChargeStateVal = -1; // TODO: PattersonChargeStateCalculator really doesn't match the following code. var fwhm = peak.FWHM; // Store a copy of the FWHM to avoid modifying the actual value if (fwhm > 0.1) { fwhm = 0.1; } for (var i = 0; i < charges.Count; i++) { // no point retesting previous charge. var tempChargeState = charges[i]; var skip = false; for (var j = 0; j < i; j++) { if (charges[j] == tempChargeState) { skip = true; break; } } if (skip) { continue; } if (tempChargeState > 0) { var peakA = peak.Mz + 1.0 / tempChargeState; var found = peakData.GetPeakFromAllOriginalIntensity(peakA - fwhm, peakA + fwhm, out var isoPeak); if (found) { returnChargeStateVal = tempChargeState; if (isoPeak.Mz * tempChargeState < 3000) { break; } // if the mass is greater than 3000, lets make sure that multiple isotopes exist. peakA = peak.Mz - 1.03 / tempChargeState; found = peakData.GetPeakFromAllOriginalIntensity(peakA - fwhm, peakA + fwhm, out isoPeak); if (found) { return(tempChargeState); } } else { peakA = peak.Mz - 1.0 / tempChargeState; found = peakData.GetPeakFromAllOriginalIntensity(peakA - fwhm, peakA + fwhm, out isoPeak); if (found && isoPeak.Mz * tempChargeState < 3000) { return(tempChargeState); } } } } return(returnChargeStateVal); }
public CubicInterpolation(double[] xPoints, double[] yPoints) { _interpolator = CubicSpline.InterpolateNaturalSorted(xPoints, yPoints); }
public List <Tuple <DateTime, VolumeIndicator> > GetRangeOfVolumeIndicator(DateTime Start, DateTime End) { List <Tuple <DateTime, VolumeIndicator> > oVolumeIndicatorData = new List <Tuple <DateTime, VolumeIndicator> >(); try { DateTime StartWithOffset = Start; if ((int)(End - Start).TotalDays < 20) { StartWithOffset = Start.AddDays(-(20 - (int)(End - Start).TotalDays)); } var HistData = GetDataForRange(StartWithOffset, End); if (HistData.Count() == 0) { return(oVolumeIndicatorData); } double[] VolumeList = HistData.Select(x => Convert.ToDouble(x.Volume)).ToArray(); double StdForVolume = VolumeList.StandardDeviation(); double StdForPrice = HistData.Select(x => Convert.ToDouble(x.Close)).ToArray().StandardDeviation(); CubicSpline oCSTotalData = CubicSpline.InterpolateNaturalSorted( VolumeList.Select((s, i2) => new { i2, s }) .Select(t => Convert.ToDouble(t.i2)).ToArray(), VolumeList); var ListOfDiff = VolumeList.Select((s, i2) => new { i2, s }) .ToList().Select(f => oCSTotalData.Differentiate(Convert.ToDouble(f.i2))).ToArray(); int i = 0; foreach (var hqd in HistData) { VolumeIndicator oVi = new VolumeIndicator(); bool bHighVolume = (ListOfDiff[i] > 0 && VolumeList[i] > StdForVolume); bool bLowVolume = (ListOfDiff[i] <= 0 && VolumeList[i] < StdForVolume); bool bHighRange = (Convert.ToDouble(hqd.Close - hqd.Open) > StdForPrice); bool bLowRange = (-Convert.ToDouble(hqd.Open - hqd.Close) > StdForPrice); bool bUpBars = (hqd.Close > hqd.Open); bool bNeutralBars = (hqd.Close.Equals(hqd.Open)); if (bHighVolume && bHighRange && bUpBars && !bNeutralBars) { oVi.VolumeIndicatorType = VolumeIndicatorType.VolumeClimaxUp; } else if (bHighVolume && bHighRange && !bUpBars && !bNeutralBars) { oVi.VolumeIndicatorType = VolumeIndicatorType.VolumeClimaxDown; } else if (bHighVolume && bHighRange && bNeutralBars) { oVi.VolumeIndicatorType = VolumeIndicatorType.VolumeClimaxPlusHighVolumeChurn; } else if (bHighVolume && !bHighRange) { oVi.VolumeIndicatorType = VolumeIndicatorType.HighVolumeChurn; } else if (!bHighVolume && bLowVolume) { oVi.VolumeIndicatorType = VolumeIndicatorType.LowVolume; } else { oVi.VolumeIndicatorType = VolumeIndicatorType.Unknown; } oVi.Strength = 100; oVolumeIndicatorData.Add(new Tuple <DateTime, VolumeIndicator>(hqd.Date, oVi)); i++; } }catch (Exception ex) { ImperaturGlobal.GetLog().Error(string.Format("Error in GetRangeOfVolumeIndicator"), ex); } return(oVolumeIndicatorData); }
/// <summary> /// configures the data points to run this model. Provide three arrays, which must be of identical length, containing /// recorded daytime temps, nighttime temps, and dates of those temps, which must all be of the same length and in /// sorted order. If only one of the temperature series has a valid value at a particular point then the other array at /// that position should be set to NoDataValue. /// </summary> /// <param name="Max_Temps">Array of LST Day temperatures, one per MODIS file in the period e.g. one every 8 days</param> /// <param name="Min_Temps">Array of LST Night temperatures, one per MODIS file in the period e.g. one every 8 days. /// Must be for the same dates as LST_Day input.</param> /// <param name="TemperatureDatePoints">Array of DateTime objects representing the dates of the input temperatures.</param> /// <returns></returns> public bool SetData(float[] Max_Temps, float[] Min_Temps, DateTime[] TemperatureDatePoints, float NoDataValue, bool convertMaxTempsFromLST, bool convertMinTempsFromLST) { // check inputs are of correct length if (Max_Temps.Length != Min_Temps.Length || Max_Temps.Length != TemperatureDatePoints.Length) { return(false); } int nPoints = TemperatureDatePoints.Length; // check dates are sorted for (int i = 1; i < nPoints; i++) { if (TemperatureDatePoints[i - 1] > TemperatureDatePoints[i]) { return(false); } } // Store the original input dates m_InputTemperatureDates = TemperatureDatePoints; var startDay = m_InputTemperatureDates.First(); // For each of max and min temps, we will create a spline between time/value pairs but only for points where the // temperature was valid (the spline doesn't know about nodata). So first generate separate list of valid time stamps // for max and min. List <double> validminTemps, validmaxTemps, validminDatePoints, validmaxDatePoints; // we will create the lists at their max possible size (i.e. same as input, all values are valid) and trim later, // rather than grow as needed, this is an attempt to fix a garbage collector crash that was occurring here in an // old version of mono validminTemps = new List <double>(nPoints); validmaxTemps = new List <double>(nPoints); validmaxDatePoints = new List <double>(nPoints); validminDatePoints = new List <double>(nPoints); double minTemp, maxTemp; for (int i = 0; i < nPoints; i++) { if (Min_Temps[i] != NoDataValue) { ConvertTemperature(Max_Temps[i], Min_Temps[i], TemperatureDatePoints[i].DayOfYear, out maxTemp, out minTemp); // min temp calculation only depends on the night temp if (convertMinTempsFromLST) { validminTemps.Add(minTemp); } else { // for development only, allow to run the model against unconverted LST values rather than converted air temp validminTemps.Add(Min_Temps[i]); } // create a copy of the input image date as seconds since the first one, as the interpolator needs doubles not dates var dSeconds = (TemperatureDatePoints[i] - startDay).TotalSeconds; validminDatePoints.Add(dSeconds); // max temp calculation depends on both the day and night temp if (Max_Temps[i] != NoDataValue) { if (convertMaxTempsFromLST) { validmaxTemps.Add(maxTemp); } else { validmaxTemps.Add(Max_Temps[i]); } validmaxDatePoints.Add(dSeconds); } } } if (validmaxTemps.Count / TemperatureDatePoints.Length < modelParams.ValidDataProportion && validminTemps.Count / TemperatureDatePoints.Length < modelParams.ValidDataProportion) { return(false); } // generate the spline interpolator objects to get daily temps from the 8-daily (or whatever) inputs // note we will use these splines for all days, rather than the original data on the days where they exist, // because splines don't have to pass through the data points and we don't want discontinuities // We are only storing (and splining from) the converted min/max air temps rather than the LST temps _MaxTempSpline = CubicSpline.InterpolateNaturalSorted(validmaxDatePoints.ToArray(), validmaxTemps.ToArray()); _MinTempSpline = CubicSpline.InterpolateNaturalSorted(validminDatePoints.ToArray(), validminTemps.ToArray()); // set the initial "previous" sunset temp to be the first day's max temp m_PreviousSunsetTemp = validmaxTemps.First(); // set the flag for whether the temperatures are _ever_ suitable for sporogenesis if (validmaxTemps.Max() > modelParams.MinTempThreshold && validmaxTemps.Min() < modelParams.MosquitoDeathTemperature) { // NB the Weiss code checked on the 1-daily splined temperature values for this; here we // are checking on the converted 8-daily (or whatever interval is provided) input values. // A spline can go outside the range of the input data, so this doesn't necessarily give // the same result in every case, but i think it's reasonable to not base our decisions on such cases. _PotentiallySuitableTemperature = true; } _CanRun = true; return(true); }