Tools.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Drawing;
  5. using System.Drawing.Imaging;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace ScottPlot
  11. {
  12. public static class Tools
  13. {
  14. public static Color GetRandomColor(Random rand = null)
  15. {
  16. if (rand is null)
  17. rand = new Random();
  18. Color randomColor = Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256));
  19. return randomColor;
  20. }
  21. public static Brush GetRandomBrush()
  22. {
  23. return new SolidBrush(GetRandomColor());
  24. }
  25. public static Color Blend(this Color colorA, Color colorB, double fractionA)
  26. {
  27. fractionA = Math.Max(fractionA, 0);
  28. fractionA = Math.Min(fractionA, 1);
  29. byte r = (byte)((colorA.R * fractionA) + colorB.R * (1 - fractionA));
  30. byte g = (byte)((colorA.G * fractionA) + colorB.G * (1 - fractionA));
  31. byte b = (byte)((colorA.B * fractionA) + colorB.B * (1 - fractionA));
  32. return Color.FromArgb(r, g, b);
  33. }
  34. [Obsolete("use ScottPlot.Plot.Version", true)]
  35. public static string GetVersionString(bool justThreeDigits = true)
  36. {
  37. Version ver = typeof(Plot).Assembly.GetName().Version;
  38. if (justThreeDigits)
  39. return $"{ver.Major}.{ver.Minor}.{ver.Build}";
  40. else
  41. return ver.ToString();
  42. }
  43. public static string GetFrameworkVersionString()
  44. {
  45. return $".NET {Environment.Version.ToString()}";
  46. }
  47. public static string BitmapHash(Bitmap bmp)
  48. {
  49. byte[] bmpBytes = BitmapToBytes(bmp);
  50. var md5 = System.Security.Cryptography.MD5.Create();
  51. StringBuilder hashString = new StringBuilder();
  52. byte[] hashBytes = md5.ComputeHash(bmpBytes);
  53. for (int i = 0; i < hashBytes.Length; i++)
  54. hashString.Append(hashBytes[i].ToString("X2"));
  55. return hashString.ToString();
  56. }
  57. public static Bitmap BitmapFromBytes(byte[] bytes, Size size, PixelFormat format = PixelFormat.Format8bppIndexed)
  58. {
  59. Bitmap bmp = new Bitmap(size.Width, size.Height, format);
  60. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
  61. BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
  62. Marshal.Copy(bytes, 0, bmpData.Scan0, bytes.Length);
  63. bmp.UnlockBits(bmpData);
  64. return bmp;
  65. }
  66. public static byte[] BitmapToBytes(Bitmap bmp)
  67. {
  68. int bytesPerPixel = Image.GetPixelFormatSize(bmp.PixelFormat) / 8;
  69. byte[] bytes = new byte[bmp.Width * bmp.Height * bytesPerPixel];
  70. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
  71. BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);
  72. //byte[] bytes = new byte[bmpData.Stride * bmp.Height * bytesPerPixel];
  73. Marshal.Copy(bmpData.Scan0, bytes, 0, bytes.Length);
  74. bmp.UnlockBits(bmpData);
  75. return bytes;
  76. }
  77. [Obsolete("use ScottPlot.Config.Fonts.GetValidFontName()", error: true)]
  78. public static string VerifyFont(string fontName)
  79. {
  80. return null;
  81. }
  82. public static string ScientificNotation(double value, int decimalPlaces = 2, bool preceedWithPlus = true)
  83. {
  84. string output;
  85. if ((Math.Abs(value) > .0001) && (Math.Abs(value) < 10000))
  86. {
  87. value = Math.Round(value, decimalPlaces);
  88. output = value.ToString();
  89. }
  90. else
  91. {
  92. int exponent = (int)Math.Log10(value);
  93. double multiplier = Math.Pow(10, exponent);
  94. double mantissa = value / multiplier;
  95. mantissa = Math.Round(mantissa, decimalPlaces);
  96. output = $"{mantissa}e{exponent}";
  97. }
  98. if (preceedWithPlus && !output.StartsWith("-"))
  99. output = "+" + output;
  100. return output;
  101. }
  102. public static void DesignerModeDemoPlot(ScottPlot.Plot plt)
  103. {
  104. int pointCount = 101;
  105. double pointSpacing = .01;
  106. double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount, pointSpacing);
  107. double[] dataSin = ScottPlot.DataGen.Sin(pointCount);
  108. double[] dataCos = ScottPlot.DataGen.Cos(pointCount);
  109. plt.AddScatter(dataXs, dataSin);
  110. plt.AddScatter(dataXs, dataCos);
  111. plt.AxisAuto(0);
  112. plt.Title("ScottPlot User Control");
  113. plt.YLabel("Sample Data");
  114. }
  115. public static double[] DateTimesToDoubles(DateTime[] dateTimeArray)
  116. {
  117. double[] positions = new double[dateTimeArray.Length];
  118. for (int i = 0; i < positions.Length; i++)
  119. positions[i] = dateTimeArray[i].ToOADate();
  120. return positions;
  121. }
  122. private static double[] DoubleArray<T>(T[] dataIn)
  123. {
  124. double[] dataOut = new double[dataIn.Length];
  125. for (int i = 0; i < dataIn.Length; i++)
  126. dataOut[i] = Convert.ToDouble(dataIn[i]);
  127. return dataOut;
  128. }
  129. public static double[] DoubleArray(byte[] dataIn)
  130. {
  131. return DoubleArray<byte>(dataIn);
  132. }
  133. public static double[] DoubleArray(int[] dataIn)
  134. {
  135. return DoubleArray<int>(dataIn);
  136. }
  137. public static double[] DoubleArray(float[] dataIn)
  138. {
  139. return DoubleArray<float>(dataIn);
  140. }
  141. public static void ApplyBaselineSubtraction(double[] data, int index1, int index2)
  142. {
  143. double baselineSum = 0;
  144. for (int i = index1; i < index2; i++)
  145. baselineSum += data[i];
  146. double baselineAverage = baselineSum / (index2 - index1);
  147. for (int i = 0; i < data.Length; i++)
  148. data[i] -= baselineAverage;
  149. }
  150. public static double[] Log10(double[] dataIn)
  151. {
  152. double[] dataOut = new double[dataIn.Length];
  153. for (int i = 0; i < dataOut.Length; i++)
  154. dataOut[i] = dataIn[i] > 0 ? Math.Log10(dataIn[i]) : 0;
  155. return dataOut;
  156. }
  157. public static (double[] xs, double[] ys) ConvertPolarCoordinates(double[] rs, double[] thetas)
  158. {
  159. double[] xs = new double[rs.Length];
  160. double[] ys = new double[rs.Length];
  161. for (int i = 0; i < rs.Length; i++)
  162. {
  163. double x = rs[i];
  164. double y = thetas[i];
  165. xs[i] = x * Math.Cos(y);
  166. ys[i] = x * Math.Sin(y);
  167. }
  168. return (xs, ys);
  169. }
  170. public static void LaunchBrowser(string url = "http://swharden.com/scottplot/")
  171. {
  172. // A cross-platform .NET-Core-safe function to launch a URL in the browser
  173. Debug.WriteLine($"Launching URL: {url}");
  174. try
  175. {
  176. Process.Start(url);
  177. }
  178. catch
  179. {
  180. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  181. Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
  182. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  183. Process.Start("xdg-open", url);
  184. else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  185. Process.Start("open", url);
  186. else
  187. throw;
  188. }
  189. }
  190. public static double[] Round(double[] data, int decimals = 2)
  191. {
  192. double[] rounded = new double[data.Length];
  193. for (int i = 0; i < data.Length; i++)
  194. rounded[i] = Math.Round(data[i], decimals);
  195. return rounded;
  196. }
  197. /// <summary>
  198. /// return a copy of the given array padded with the given value at both sidees
  199. /// </summary>
  200. public static double[] Pad(double[] values, int padCount = 1, double padWithLeft = 0, double padWithRight = 0, bool cloneEdges = false)
  201. {
  202. double[] padded = new double[values.Length + padCount * 2];
  203. Array.Copy(values, 0, padded, padCount, values.Length);
  204. if (cloneEdges)
  205. {
  206. padWithLeft = values[0];
  207. padWithRight = values[values.Length - 1];
  208. }
  209. for (int i = 0; i < padCount; i++)
  210. {
  211. padded[i] = padWithLeft;
  212. padded[padded.Length - 1 - i] = padWithRight;
  213. }
  214. return padded;
  215. }
  216. public static string GetOsName(bool details = true)
  217. {
  218. string name = "Unknown";
  219. if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  220. name = "Linux";
  221. else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  222. name = "MacOS";
  223. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  224. name = "Windows";
  225. if (details)
  226. name += $" ({System.Environment.OSVersion})";
  227. return name;
  228. }
  229. public static int SimpleHash(double[] input)
  230. {
  231. byte[] bytes = input.SelectMany(n => { return BitConverter.GetBytes(n); }).ToArray();
  232. int hash = 0;
  233. foreach (byte b in bytes)
  234. hash = (hash * 31) ^ b;
  235. return hash;
  236. }
  237. public static double[,] XYToIntensitiesGaussian(int[] xs, int[] ys, int width, int height, int sigma)
  238. {
  239. static double NormPDF(double x, double mu, double sigma) =>
  240. (1 / (sigma * Math.Sqrt(2 * Math.PI))) * Math.Exp(-0.5 * (x - mu / sigma) * (x - mu / sigma));
  241. double[,] output = new double[height, width];
  242. double[,] intermediate = new double[height, width]; // Each cell has the number of hits. This is the array before any blurring
  243. int radius = 2; // 2 Standard deviations is ~0.95, i.e. close enough
  244. for (int i = 0; i < xs.Length; i++)
  245. {
  246. if (xs[i] >= 0 && xs[i] < width && ys[i] >= 0 && ys[i] < height)
  247. {
  248. intermediate[ys[i], xs[i]] += 1;
  249. }
  250. }
  251. double[] kernel = new double[2 * radius * sigma + 1];
  252. for (int i = 0; i < kernel.Length; i++)
  253. {
  254. kernel[i] = NormPDF(i - kernel.Length / 2, 0, sigma);
  255. }
  256. for (int i = 0; i < height; i++) // Blurs up and down, i.e. a vertical kernel. Gaussian Blurs are special in that it can be decomposed this way, saving time
  257. {
  258. for (int j = 0; j < width; j++)
  259. {
  260. double sum = 0;
  261. double kernelSum = 0; // The kernelSum can be precomputed, but this gives incorrect output at the edges of the image
  262. for (int k = -radius * sigma; k <= radius * sigma; k++)
  263. {
  264. if (i + k >= 0 && i + k < height)
  265. {
  266. sum += intermediate[i + k, j] * kernel[k + kernel.Length / 2];
  267. kernelSum += kernel[k + kernel.Length / 2];
  268. }
  269. }
  270. output[i, j] = sum / kernelSum;
  271. }
  272. }
  273. for (int i = 0; i < height; i++) // Blurs left and right, i.e. a horizontal kernel
  274. {
  275. for (int j = 0; j < width; j++)
  276. {
  277. double sum = 0;
  278. double kernelSum = 0;
  279. for (int k = -radius * sigma; k <= radius * sigma; k++)
  280. {
  281. if (j + k >= 0 && j + k < width)
  282. {
  283. sum += output[i, j + k] * kernel[k + kernel.Length / 2];
  284. kernelSum += kernel[k + kernel.Length / 2];
  285. }
  286. }
  287. output[i, j] = sum / kernelSum;
  288. }
  289. }
  290. return output;
  291. }
  292. public static double[,] XYToIntensitiesDensity(int[] xs, int[] ys, int width, int height, int sampleWidth)
  293. {
  294. double[,] output = new double[height, width];
  295. (int x, int y)[] points = xs.Zip(ys, (x, y) => (x, y)).ToArray();
  296. points = points.OrderBy(p => p.x).ToArray();
  297. int[] xs_sorted = points.Select(p => p.x).ToArray();
  298. for (int i = 0; i < height - height % sampleWidth; i += sampleWidth)
  299. {
  300. for (int j = 0; j < width - width % sampleWidth; j += sampleWidth)
  301. {
  302. int count = 0;
  303. for (int k = 0; k < sampleWidth; k++)
  304. {
  305. for (int l = 0; l < sampleWidth; l++)
  306. {
  307. int index = Array.BinarySearch(xs_sorted, j + l);
  308. if (index > 0)
  309. {
  310. for (int m = index; m < xs.Length; m++)
  311. { //Multiple points w/ same x value
  312. if (points[m].x == j + l && points[m].y == i + k)
  313. {
  314. count++; // Increments number of hits in sampleWidth sized square
  315. }
  316. }
  317. }
  318. }
  319. }
  320. for (int k = 0; k < sampleWidth; k++)
  321. {
  322. for (int l = 0; l < sampleWidth; l++)
  323. {
  324. output[i + k, j + l] = count;
  325. }
  326. }
  327. }
  328. }
  329. return output;
  330. }
  331. public static double[,] XYToIntensities(IntensityMode mode, int[] xs, int[] ys, int width, int height, int sampleWidth)
  332. {
  333. return mode switch
  334. {
  335. IntensityMode.Gaussian => XYToIntensitiesGaussian(xs, ys, width, height, sampleWidth),
  336. IntensityMode.Density => XYToIntensitiesDensity(xs, ys, width, height, sampleWidth),
  337. _ => throw new NotImplementedException($"{nameof(mode)} is not a supported {nameof(IntensityMode)}"),
  338. };
  339. }
  340. public static string ToDifferentBase(double number, int radix = 16, int decimalPlaces = 3, int padInteger = 0, bool dropTrailingZeroes = true, char decimalSymbol = '.')
  341. {
  342. if (number < 0)
  343. {
  344. return "-" + ToDifferentBase(Math.Abs(number), radix, decimalPlaces, padInteger, dropTrailingZeroes, decimalSymbol);
  345. }
  346. else if (number == 0)
  347. {
  348. return "0";
  349. }
  350. char[] symbols = "0123456789ABCDEF".ToCharArray();
  351. if (radix > symbols.Length || radix <= 1)
  352. {
  353. throw new ArgumentOutOfRangeException(nameof(radix));
  354. }
  355. double epsilon = Math.Pow(radix, -decimalPlaces);
  356. if (radix > symbols.Length)
  357. {
  358. throw new ArgumentOutOfRangeException(nameof(radix));
  359. }
  360. int integerLength = (int)Math.Ceiling(Math.Log(number, radix));
  361. int decimalLength = number % 1 > epsilon ? decimalPlaces : 0;
  362. double decimalPart = number % 1;
  363. string output = "";
  364. for (int i = 0; i < integerLength; i++)
  365. {
  366. if (number == radix && padInteger == 0)
  367. {
  368. output = "10" + output;
  369. }
  370. else
  371. {
  372. output = symbols[(int)(number % radix)] + output;
  373. }
  374. number /= radix;
  375. }
  376. while (output.Length < padInteger)
  377. {
  378. output = "0" + output;
  379. }
  380. if (decimalLength != 0)
  381. {
  382. if (output == "")
  383. {
  384. output += "0";
  385. }
  386. output += decimalSymbol;
  387. output += ToDifferentBase(Math.Round(decimalPart * Math.Pow(radix, decimalPlaces)), radix, decimalPlaces, decimalPlaces, dropTrailingZeroes, decimalSymbol);
  388. if (dropTrailingZeroes)
  389. {
  390. while (output.Last() == '0')
  391. {
  392. output = output.Substring(0, output.Length - 1);
  393. }
  394. if (output.Last() == decimalSymbol)
  395. {
  396. output = output.Substring(0, output.Length - 1);
  397. }
  398. }
  399. }
  400. return output;
  401. }
  402. }
  403. }