public override object[] GetRowData(long row) { List <object> rowData = new List <object>(); for (int i = 0; i < mdata.ColumnCount; i++) { rowData.Add(NumUtils.RoundSignificantDigits(mdata.Values.Get((int)row, i), 6)); } for (int i = 0; i < mdata.CategoryColumnCount; i++) { rowData.Add(StringUtils.Concat(";", mdata.GetCategoryColumnEntryAt(i, (int)row) ?? new string[0])); } for (int i = 0; i < mdata.NumericColumnCount; i++) { rowData.Add(NumUtils.RoundSignificantDigits(mdata.NumericColumns[i][row], 6)); } for (int i = 0; i < mdata.StringColumnCount; i++) { rowData.Add(mdata.StringColumns[i][row]); } for (int i = 0; i < mdata.MultiNumericColumnCount; i++) { rowData.Add(StringUtils.Concat(";", mdata.MultiNumericColumns[i][row] ?? new double[0])); } return(rowData.ToArray()); }
/* * You might expect that pressing one of the edges of the SteamVR controller touchpad could * be detected with a call to device.GetPress( EVRButtonId.k_EButton_DPad_* ), but currently this always returns false. * Not sure whether this is SteamVR's design intent, not yet implemented, or a bug. * The expected behaviour can be achieved by detecting overall Touchpad press, with Touch-Axis comparison to an edge threshold. */ public static NVRButtons?GetDPadPress(NVRHand hand) { if (hand.Inputs[NVRButtons.Touchpad].PressDown) { var touchpad_axis = hand.Inputs[NVRButtons.Touchpad].Axis; var angle = Mathf.Rad2Deg * Mathf.Atan2(touchpad_axis.y, touchpad_axis.x); if (NumUtils.DistanceInModulo(angle, 0, 360) < 45) { return(NVRButtons.DPad_Right); } if (NumUtils.DistanceInModulo(angle, 90, 360) < 45) { return(NVRButtons.DPad_Up); } if (NumUtils.DistanceInModulo(angle, 180, 360) < 45) { return(NVRButtons.DPad_Left); } if (NumUtils.DistanceInModulo(angle, 270, 360) < 45) { return(NVRButtons.DPad_Down); } Debug.LogError("Error: DPAD Press Math is wrong. Angle did not register with any specified direction."); } return(null); }
public static double[] CalcSignificanceB(BaseVector ratios, BaseVector intens, TestSide side) { double[] result = new double[ratios.Length]; for (int i = 0; i < result.Length; i++) { result[i] = 1; } List <double> lRatio = new List <double>(); List <double> lIntensity = new List <double>(); List <int> indices = new List <int>(); for (int i = 0; i < ratios.Length; i++) { if (!double.IsNaN(ratios[i]) && !double.IsInfinity(ratios[i]) && !double.IsNaN(intens[i]) && !double.IsInfinity(intens[i])) { lRatio.Add(ratios[i]); lIntensity.Add(intens[i]); indices.Add(i); } } double[] ratioSignificanceB = NumUtils.MovingBoxPlot(lRatio.ToArray(), lIntensity.ToArray(), -1, side); for (int i = 0; i < indices.Count; i++) { result[indices[i]] = ratioSignificanceB[i]; } return(result); }
public static double[][] GetIsotopeDistribution(int n, double[] masses, double[] composition) { int len = masses.Length; int[][] partitions = NumUtils.GetPartitions(n, len); double[] ms = new double[partitions.Length]; double[] weights = new double[partitions.Length]; for (int i = 0; i < partitions.Length; i++) { weights[i] = 1; int[] partition = partitions[i]; for (int j = 0; j < len; j++) { ms[i] += partition[j] * masses[j]; for (int k = 0; k < partition[j]; k++) { weights[i] *= composition[j]; } } weights[i] *= Factorial.Multinomial(n, partition); } int[] o = ArrayUtils.Order(ms); ms = ArrayUtils.SubArray(ms, o); weights = ArrayUtils.SubArray(weights, o); double[][] x = FilterWeights(ms, weights, 1e-6); ms = x[0]; weights = x[1]; x = FilterMasses(ms, weights, 0.2); ms = x[0]; weights = x[1]; return(new[] { ms, weights }); }
public static Dictionary <string, List <string> > GetPeptideCompositions(double maxMass) { Dictionary <string, List <string> > result = new Dictionary <string, List <string> >(); double mg = glycine.MonoIsotopicMass; int maxN = (int)((maxMass - Molecule.massWater) / mg); string aas = StandardSingleLetterAas; double[] masses = AaMonoMasses; NumUtils.GetPartitions(maxN, 21, i1 => { double m1 = Molecule.massWater; for (int i = 0; i < i1.Length; i++) { if (i < 20) { m1 += i1[i] * masses[aas[i]]; } } return(m1 <= maxMass); }, i2 => { string seq = GetSequence(i2, aas); Molecule m = GetPeptideMolecule(seq); string formula = m.GetEmpiricalFormula(); if (!result.ContainsKey(formula)) { result.Add(formula, new List <string>()); } result[formula].Add(seq); }); return(result); }
private string GetTicLabel(double ticval, int decade, double max) { if (IsLogarithmic) { return("10" + ToSuperscript((int)Math.Round(ticval / Math.Log(10.0)))); } return(NumUtils.RoundSignificantDigits2(ticval / Math.Pow(10.0, decade), 7, max / Math.Pow(10.0, decade))); }
public WeatherReport(double lat, double lon, DateTime date) { HiTempperature = NumUtils.getRandom(0, 36); LowTemperature = NumUtils.getRandom(((HiTempperature - 15) < 0 ? 0: HiTempperature - 15), HiTempperature); WindSpeed = NumUtils.getRandom(0, 80); Condition = EnumUtils.GetRandomEnum <WeatherCondition>(); Date = date; }
public void Encode(ImageBase imageBase, Stream stream) { if (imageBase == null || stream == null) { throw new ArgumentNullException(); } Image2 image = (Image2)imageBase; if (Quantizer == null) { Quantizer = new OctreeQuantizer { Threshold = Threshold }; } // Do not use IDisposable pattern here as we want to preserve the stream. EndianBinaryWriter writer = new EndianBinaryWriter(EndianBitConverter.Little, stream); // Ensure that quality can be set but has a fallback. int quality = Quality > 0 ? Quality : imageBase.Quality; Quality = quality > 0 ? NumUtils.Clamp(quality, 1, 256) : 256; // Get the number of bits. bitDepth = GetBitsNeededForColorDepth(Quality); // Quantize the image returning a palette. QuantizedImage quantized = Quantizer.Quantize(image, Quality); // Write the header. WriteHeader(writer); // Write the LSD. We'll use local color tables for now. WriteLogicalScreenDescriptor(image, writer, quantized.TransparentIndex); // Write the first frame. WriteGraphicalControlExtension(imageBase, writer, quantized.TransparentIndex); WriteImageDescriptor(image, writer); WriteColorTable(quantized, writer); WriteImageData(quantized, writer); // Write additional frames. if (image.Frames.Any()) { WriteApplicationExtension(writer, image.RepeatCount, image.Frames.Count); foreach (ImageFrame frame in image.Frames) { QuantizedImage quantizedFrame = Quantizer.Quantize(frame, Quality); WriteGraphicalControlExtension(frame, writer, quantizedFrame.TransparentIndex); WriteImageDescriptor(frame, writer); WriteColorTable(quantizedFrame, writer); WriteImageData(quantizedFrame, writer); } } // TODO: Write Comments extension etc writer.Write(GifConstants.endIntroducer); }
public override QuantizedImage Quantize(ImageBase image, int maxColors) { colors = NumUtils.Clamp(maxColors, 1, 255); if (octree == null) { octree = new Octree(GetBitsNeededForColorDepth(maxColors)); } return(base.Quantize(image, maxColors)); }
public static double GetLogFisherP(int q00, int q01, int q10, int q11) { int rowSum0 = q00 + q01; int rowSum1 = q10 + q11; int colSum0 = q00 + q10; int colSum1 = q01 + q11; int total = rowSum0 + rowSum1; return(NumUtils.Factln(rowSum0) + NumUtils.Factln(rowSum1) + NumUtils.Factln(colSum0) + NumUtils.Factln(colSum1) - NumUtils.Factln(q00) - NumUtils.Factln(q01) - NumUtils.Factln(q10) - NumUtils.Factln(q11) - NumUtils.Factln(total)); }
private static double EstimateDensity(double x, double y, double[,] data, double[,] hinv) { double result = 0; for (int i = 0; i < data.GetLength(0); i++) { double[] w = { x - data[i, 0], y - data[i, 1] }; double[] b = NumUtils.MatrixTimesVector(hinv, w); result += StandardGaussian(b); } result *= NumUtils.Determinant2X2(hinv) / data.Length; return(result); }
private static double EstimateDensity(double x, double[] data, double hinv) { double result = 0; for (int i = 0; i < data.GetLength(0); i++) { double w = x - data[i]; double[] b = new[] { hinv *w }; result += NumUtils.StandardGaussian(b); } result *= hinv / data.Length; return(result); }
public void Encode(ImageBase image, Stream stream) { if (image == null || stream == null) { throw new ArgumentNullException(); } stream.Write(new byte[] { 0x89, // Set the high bit. 0x50, // P 0x4E, // N 0x47, // G 0x0D, // Line ending CRLF 0x0A, // Line ending CRLF 0x1A, // EOF 0x0A // LF }, 0, 8); int quality = Quality > 0 ? Quality : image.Quality; Quality = quality > 0 ? NumUtils.Clamp(quality, 1, int.MaxValue) : int.MaxValue; bitDepth = Quality <= 256 ? (byte)NumUtils.Clamp(GifEncoderCore.GetBitsNeededForColorDepth(Quality), 1, 8) : (byte)8; if (bitDepth == 3) { bitDepth = 4; } else if (bitDepth >= 5 || bitDepth <= 7) { bitDepth = 8; } PngHeader header = new PngHeader { Width = image.Width, Height = image.Height, ColorType = (byte)(Quality <= 256 ? 3 : 6), BitDepth = bitDepth, FilterMethod = 0, // None CompressionMethod = 0, InterlaceMethod = 0 }; WriteHeaderChunk(stream, header); QuantizedImage quantized = WritePaletteChunk(stream, header, image); WritePhysicalChunk(stream, image); WriteGammaChunk(stream); using (IPixelAccessor pixels = image.Lock()){ WriteDataChunks(stream, pixels, quantized); } WriteEndChunk(stream); stream.Flush(); }
public static float[,] GetValuesOnGrid(IList <float> xvals, double minx, double xStep, int xCount, IList <float> yvals, double miny, double yStep, int yCount) { float[,] vals = new float[xCount, yCount]; if (xvals == null || yvals == null) { return(vals); } int n = xvals.Count; double[,] cov = NumUtils.CalcCovariance(new[] { xvals, yvals }); double fact = Math.Pow(n, 1.0 / 6.0); double[,] hinv = NumUtils.ApplyFunction(cov, w => fact / Math.Sqrt(w)); hinv[0, 0] *= xStep; hinv[1, 0] *= xStep; hinv[0, 1] *= yStep; hinv[1, 1] *= yStep; int dx = (int)(1.0 / hinv[0, 0] * 5); int dy = (int)(1.0 / hinv[1, 1] * 5); for (int i = 0; i < xvals.Count; i++) { double xval = xvals[i]; if (double.IsNaN(xval)) { continue; } int xind = (int)Math.Floor((xval - minx) / xStep); double yval = yvals[i]; if (double.IsNaN(yval)) { continue; } int yind = (int)Math.Floor((yval - miny) / yStep); for (int ii = Math.Max(xind - dx, 0); ii <= Math.Min(xind + dx, xCount - 1); ii++) { for (int jj = Math.Max(yind - dy, 0); jj <= Math.Min(yind + dy, yCount - 1); jj++) { double[] w = { ii - xind, jj - yind }; double[] b = NumUtils.MatrixTimesVector(hinv, w); vals[ii, jj] += (float)NumUtils.StandardGaussian(b); } } } return(vals); }
public QuantizedImage Quantize(ImageBase image, int maxColors) { if (image == null) { throw new ArgumentNullException(); } int colorCount = NumUtils.Clamp(maxColors, 1, 256); Clear(); using (IPixelAccessor imagePixels = image.Lock()){ Build3DHistogram(imagePixels); Get3DMoments(); Box[] cube; BuildCube(out cube, ref colorCount); return(GenerateResult(imagePixels, colorCount, cube)); } }
/// <summary> /// Kruskal Wallis test is the extention of the Wilcoxon U test to more than two group /// Another words it is designed to test the equakity of medians of multiple sample /// </summary> /// <param name="data">Value of the first dimension is number of groups, second - size of the group</param> /// <param name="stat">H-statistic of the test</param> /// <returns></returns> public static double TestImpl(double[][] data, out double stat) { int i, j, counter = 0; int[] arrN = new int[data.Length]; List <double> x = new List <double>(); for (i = 0; i < data.Length; i++) { arrN[i] = data[i].Length; for (j = 0; j < arrN[i]; j++) { x.Add(data[i][j]); } } int n = arrN.Sum(); List <double> dataRank = ArrayUtils.Rank(x, true).ToList(); List <int> numDuplicates = new List <int>(); double[] dataRankSorted = dataRank.OrderBy(a => a).ToArray(); for (i = 0; i < n; i++) { counter++; if ((i == n - 1) || (dataRankSorted[i] != dataRankSorted[i + 1])) { if (counter > 1) { numDuplicates.Add(counter); } counter = 0; } } j = 0; double[] s = new double[data.Length]; for (i = 0; i < data.Length; i++) { s[i] = Math.Pow(dataRank.Skip(j).Take(arrN[i]).Select(d => d + 1).Sum(), 2) / arrN[i]; j += arrN[i]; } stat = (12 * s.Sum() / (n * (n + 1)) - 3 * (n + 1)) / (1 - numDuplicates.Select(d => d * (d * d - 1)).Sum() / (Math.Pow(n, 3) - n)); int df = data.Length - 1; return(1 - NumUtils.Gammq(stat * 0.5, df * 0.5)); }
public static double Betai(double a, double b, double x) { double bt; if (x < 0.0 || x > 1.0) { throw new Exception("Bad x in routine betai"); } if (x == 0.0 || x == 1.0) { bt = 0.0; } else { bt = Math.Exp(NumUtils.Gammln(a + b) - NumUtils.Gammln(a) - NumUtils.Gammln(b) + a * Math.Log(x) + b * Math.Log(1.0 - x)); } if (x < (a + 1.0) / (a + b + 2.0)) { return(bt * Betacf(a, b, x) / a); } return(1.0 - bt * Betacf(b, a, 1.0 - x) / b); }
public override ClassificationModel Train(BaseVector[] x, int[][] y, int ngroups, Parameters param, int nthreads, Action <double> reportProgress) { int n = x.Length; int p = x[0].Length; int[] groupCounts = new int[ngroups]; int totalCount = 0; double[,] groupMeans = new double[ngroups, p]; double[] totalMean = new double[p]; for (int i = 0; i < n; i++) { int groupIndex = y[i][0]; groupCounts[groupIndex]++; totalCount++; for (int j = 0; j < p; j++) { groupMeans[groupIndex, j] += x[i][j]; totalMean[j] += x[i][j]; } } for (int i = 0; i < ngroups; i++) { for (int j = 0; j < p; j++) { groupMeans[i, j] /= groupCounts[i]; } } for (int j = 0; j < p; j++) { totalMean[j] /= totalCount; } double[,] b = new double[p, p]; for (int i = 0; i < p; i++) { for (int j = 0; j < p; j++) { for (int k = 0; k < ngroups; k++) { b[i, j] += groupCounts[k] * (groupMeans[k, i] - totalMean[i]) * (groupMeans[k, j] - totalMean[j]); } } } double[,] w = new double[p, p]; for (int k = 0; k < n; k++) { int groupIndex = y[k][0]; for (int i = 0; i < p; i++) { for (int j = 0; j < p; j++) { w[i, j] += (x[k][i] - groupMeans[groupIndex, i]) * (x[k][j] - groupMeans[groupIndex, j]); } } } double[,] x1; double[] e = NumUtils.GeneralizedEigenproblem(b, w, out x1); int[] order = ArrayUtils.Order(e); int[] indices = new int[ngroups - 1]; for (int i = 0; i < ngroups - 1; i++) { indices[i] = order[order.Length - 1 - i]; } e = ArrayUtils.SubArray(e, indices); double[,] projection = ExtractColumns(x1, indices); double[][] projectedGroupMeans = MatrixTimesMatrix(groupMeans, projection); return(new FisherLdaClassificationModel(projection, projectedGroupMeans, ngroups)); }
public static Vector4F Clamp(Vector4F x, Vector4F min, Vector4F max) { return(new Vector4F(NumUtils.Clamp(x.X, min.X, max.X), NumUtils.Clamp(x.Y, min.Y, max.Y), NumUtils.Clamp(x.Z, min.Z, max.Z), NumUtils.Clamp(x.W, min.W, max.W))); }
public static Vector3F Clamp(Vector3F x, Vector3F min, Vector3F max) { return(new Vector3F(NumUtils.Clamp(x.x, min.x, max.x), NumUtils.Clamp(x.y, min.y, max.y), NumUtils.Clamp(x.z, min.z, max.z))); }
/// <summary> /// This method generates a pseudo random number drawn from a normal distribution /// with zero mean and unit variance. /// </summary> /// <returns> The Gaussian random number.</returns> public double NextGaussian() { return(NumUtils.Gasdev(ref iset, ref gset, this)); }
/// <summary> /// This method generates a pseudo random number drawn from a normal distribution /// with the given mean and standard deviation. /// </summary> /// <returns> The Gaussian random number.</returns> public double NextGaussian(double mean, double stddev) { double x = NumUtils.Gasdev(ref iset, ref gset, this); return(x * stddev + mean); }
private static byte ToByte(int value) { return((byte)NumUtils.Clamp(value, 0, 255)); }
public void ProcessData(IMatrixData mdata, Parameters param, ref IMatrixData[] supplTables, ref IDocumentData[] documents, ProcessInfo processInfo) { int[] colIndx = param.GetParam <int[]>("x").Value; int[] colIndy = param.GetParam <int[]>("y").Value; if (colIndx.Length == 0) { processInfo.ErrString = "Please select some columns"; return; } if (colIndx.Length != colIndy.Length) { processInfo.ErrString = "Please select the same number of columns in the boxes for the first and second columns."; return; } int typeInd = param.GetParam <int>("Distribution type").Value; int points = param.GetParam <int>("Number of points").Value; for (int k = 0; k < colIndx.Length; k++) { float[] xvals = GetColumn(mdata, colIndx[k]); float[] yvals = GetColumn(mdata, colIndy[k]); float[] xvals1; float[] yvals1; NumUtils.GetValidPairs(xvals, yvals, out xvals1, out yvals1); double xmin; double xmax; double ymin; double ymax; DensityEstimation.CalcRanges(xvals1, yvals1, out xmin, out xmax, out ymin, out ymax); float[,] values = DensityEstimation.GetValuesOnGrid(xvals1, xmin, (xmax - xmin) / points, points, yvals1, ymin, (ymax - ymin) / points, points); if (typeInd == 1) { MakeConditional1(values); } if (typeInd == 2) { MakeConditional2(values); } if (typeInd == 3) { MakeConditional3(values); } DensityEstimation.DivideByMaximum(values); double[] xmat = new double[points]; for (int i = 0; i < points; i++) { xmat[i] = xmin + i * (xmax - xmin) / points; } double[] ymat = new double[points]; for (int i = 0; i < points; i++) { ymat[i] = ymin + i * (ymax - ymin) / points; } float[,] percvalues = CalcExcludedPercentage(values); double[] dvals = new double[xvals.Length]; double[] pvals = new double[xvals.Length]; for (int i = 0; i < dvals.Length; i++) { double xx = xvals[i]; double yy = yvals[i]; if (!double.IsNaN(xx) && !double.IsNaN(yy)) { int xind = ArrayUtils.ClosestIndex(xmat, xx); int yind = ArrayUtils.ClosestIndex(ymat, yy); dvals[i] = values[xind, yind]; pvals[i] = percvalues[xind, yind]; } else { dvals[i] = double.NaN; pvals[i] = double.NaN; } } string xname = GetColumnName(mdata, colIndx[k]); string yname = GetColumnName(mdata, colIndy[k]); mdata.AddNumericColumn("Density_" + xname + "_" + yname, "Density of data points in the plane spanned by the columns " + xname + " and " + yname + ".", dvals); mdata.AddNumericColumn("Excluded fraction_" + xname + "_" + yname, "Percentage of points with a point density smaller than at this point in the plane spanned by the columns " + xname + " and " + yname + ".", pvals); } }
public void ProcessData(IMatrixData mdata, Parameters param, ref IMatrixData[] supplTables, ref IDocumentData[] documents, ProcessInfo processInfo) { int[] rcols = param.GetParam <int[]>("Ratio columns").Value; int[] icols = param.GetParam <int[]>("Intensity columns").Value; if (rcols.Length == 0) { processInfo.ErrString = "Please specify some ratio columns."; return; } if (rcols.Length != icols.Length) { processInfo.ErrString = "The number of ratio and intensity columns have to be equal."; return; } int truncIndex = param.GetParam <int>("Use for truncation").Value; TestTruncation truncation = truncIndex == 0 ? TestTruncation.Pvalue : (truncIndex == 1 ? TestTruncation.BenjaminiHochberg : TestTruncation.PermutationBased); double threshold = param.GetParam <double>("Threshold value").Value; int sideInd = param.GetParam <int>("Side").Value; TestSide side; switch (sideInd) { case 0: side = TestSide.Both; break; case 1: side = TestSide.Left; break; case 2: side = TestSide.Right; break; default: throw new Exception("Never get here."); } for (int i = 0; i < rcols.Length; i++) { BaseVector r = mdata.Values.GetColumn(rcols[i]); BaseVector intens = icols[i] < mdata.ColumnCount ? mdata.Values.GetColumn(icols[i]) : new DoubleArrayVector(mdata.NumericColumns[icols[i] - mdata.ColumnCount]); double[] pvals = NumUtils.CalcSignificanceB(r.ToArray(), intens.ToArray(), side); string[][] fdr; switch (truncation) { case TestTruncation.Pvalue: fdr = PerseusPluginUtils.CalcPvalueSignificance(pvals, threshold); break; case TestTruncation.BenjaminiHochberg: fdr = PerseusPluginUtils.CalcBenjaminiHochbergFdr(pvals, threshold, out double[] _); break; default: throw new Exception("Never get here."); } mdata.AddNumericColumn(mdata.ColumnNames[rcols[i]] + " Significance B", "", pvals); mdata.AddCategoryColumn(mdata.ColumnNames[rcols[i]] + " B significant", "", fdr); } }
public static void Mrqmin(double[] x, double[] y, double[] sig, int ndata, double[] a, double[] amin, double[] amax, double[,] covar, double[,] alpha, out double chisq, Func <double, double[], double[], int, double> func, ref double alamda, ref double ochisq, ref double[,] oneda, ref int mfit, ref double[] atry, ref double[] beta, ref double[] da, int nthreads) { if (amin == null) { amin = new double[a.Length]; for (int i = 0; i < amin.Length; i++) { amin[i] = double.MinValue; } } if (amax == null) { amax = new double[a.Length]; for (int i = 0; i < amax.Length; i++) { amax[i] = double.MaxValue; } } int ma = a.Length; if (alamda < 0.0) { atry = new double[ma]; beta = new double[ma]; da = new double[ma]; mfit = ma; oneda = new double[mfit, 1]; alamda = 0.001; if (nthreads > 1) { MrqcofMulti(x, y, sig, ndata, a, alpha, beta, out chisq, func, nthreads); } else { Mrqcof(x, y, sig, ndata, a, alpha, beta, out chisq, func); } ochisq = chisq; for (int j = 0; j < ma; j++) { atry[j] = a[j]; } } for (int j = 0; j < ma; j++) { for (int k = 0; k < ma; k++) { covar[j, k] = alpha[j, k]; } covar[j, j] = alpha[j, j] * (1.0 + (alamda)); oneda[j, 0] = beta[j]; } NumUtils.Gaussj(covar, mfit, oneda, 1); for (int j = 0; j < mfit; j++) { da[j] = oneda[j, 0]; } if (alamda == 0.0) { NumUtils.Covsrt(covar); chisq = ochisq; return; } for (int j = 0; j < ma; j++) { double ax = a[j] + da[j]; if (ax >= amin[j] && ax <= amax[j]) { atry[j] = ax; } } if (nthreads > 1) { MrqcofMulti(x, y, sig, ndata, atry, covar, da, out chisq, func, nthreads); } else { Mrqcof(x, y, sig, ndata, atry, covar, da, out chisq, func); } if (chisq < ochisq) { alamda *= 0.1; ochisq = chisq; for (int j = 0; j < ma; j++) { for (int k = 0; k < ma; k++) { alpha[j, k] = covar[j, k]; } beta[j] = da[j]; a[j] = atry[j]; } } else { alamda *= 10.0; chisq = ochisq; } }
private static void Invert(double[,] falseData, double[,] trueData, out double[] xRes, out double[] yRes, out double[,] zRes, out double[,] forwardOut, out double[,] reverseOut, int nthreads, int ndata, double[,] covIn, bool debug) { double xmin = double.MaxValue; double xmax = double.MinValue; double ymin = double.MaxValue; double ymax = double.MinValue; for (int i = 0; i < falseData.GetLength(0); i++) { double xx = falseData[i, 0]; double yy = falseData[i, 1]; if (xx < xmin) { xmin = xx; } if (xx > xmax) { xmax = xx; } if (yy < ymin) { ymin = yy; } if (yy > ymax) { ymax = yy; } } for (int i = 0; i < trueData.GetLength(0); i++) { double xx = trueData[i, 0]; double yy = trueData[i, 1]; if (xx < xmin) { xmin = xx; } if (xx > xmax) { xmax = xx; } if (yy < ymin) { ymin = yy; } if (yy > ymax) { ymax = yy; } } double dx = xmax - xmin; xmin -= 0.1 * dx; xmax += 0.1 * dx; double dy = ymax - ymin; ymin -= 0.1 * dy; ymax += 0.1 * dy; double[] falseX; double[] falseY; double[,] falseZ; double[,] cov = covIn ?? NumUtils.CalcCovariance(trueData); double fact = Math.Pow(ndata, 1.0 / 6.0); double[,] hinv = null; try { hinv = NumUtils.ApplyFunction(cov, w => fact / Math.Sqrt(w)); } catch { } if (hinv == null || !IsValidMatrix(hinv)) { xRes = null; yRes = null; zRes = null; forwardOut = null; reverseOut = null; return; } try { EstimateBivariateDensity(falseData, out falseX, out falseY, out falseZ, xmin, xmax, ymin, ymax, hinv, nthreads); } catch (Exception) { xRes = null; yRes = null; zRes = null; forwardOut = null; reverseOut = null; return; } double[] trueX; double[] trueY; double[,] trueZ; try { EstimateBivariateDensity(trueData, out trueX, out trueY, out trueZ, xmin, xmax, ymin, ymax, hinv, nthreads); } catch (Exception) { xRes = null; yRes = null; zRes = null; forwardOut = null; reverseOut = null; return; } double[] x = UnifySupport(falseX, trueX); double[] y = UnifySupport(falseY, trueY); falseZ = Interpolate(x, y, falseX, falseY, falseZ); trueZ = Interpolate(x, y, trueX, trueY, trueZ); double[,] inverse = new double[x.Length, y.Length]; for (int i = 0; i < x.Length; i++) { for (int j = 0; j < y.Length; j++) { inverse[i, j] = falseZ[i, j] <= 0 ? double.Epsilon : Math.Max((falseZ[i, j] * 0.5) / trueZ[i, j], double.Epsilon); } } for (int j = 0; j < y.Length; j++) { double maxVal = double.MinValue; int maxInd = -1; for (int i = 0; i < x.Length; i++) { if (inverse[i, j] > maxVal) { maxVal = inverse[i, j]; maxInd = i; } } for (int i = 0; i < maxInd; i++) { inverse[i, j] = maxVal; } } xRes = x; yRes = y; zRes = inverse; if (debug) { forwardOut = trueZ; reverseOut = falseZ; } else { forwardOut = null; reverseOut = null; } }
public override QuantizedImage Quantize(ImageBase image, int maxColors) { Array.Resize(ref colors, NumUtils.Clamp(maxColors, 1, 256)); return(base.Quantize(image, maxColors)); }
internal override double NumEvaluateDouble(double x) { return(NumUtils.Erff(x)); }