private void RightClickMenuItemClicked(object sender, ToolStripItemClickedEventArgs e) { rightClickMenu.Hide(); switch (e.ClickedItem.Text) { case "Save Image": SaveFileDialog savefile = new SaveFileDialog(); savefile.FileName = "ScottPlot.png"; savefile.Filter = "PNG Files (*.png)|*.png;*.png"; savefile.Filter += "|JPG Files (*.jpg, *.jpeg)|*.jpg;*.jpeg"; savefile.Filter += "|BMP Files (*.bmp)|*.bmp;*.bmp"; savefile.Filter += "|TIF files (*.tif, *.tiff)|*.tif;*.tiff"; savefile.Filter += "|All files (*.*)|*.*"; if (savefile.ShowDialog() == DialogResult.OK) { plt.SaveFig(savefile.FileName); } break; case "Settings": var formSettings = new UserControls.FormSettings(plt); formSettings.ShowDialog(); Render(); break; case "Help": var formHelp = new UserControls.FormHelp(); formHelp.ShowDialog(); break; default: throw new NotImplementedException(); } }
public void SaveScottPlotTestFromWebsite() { string saveFileLocation = "C:\\Temp\\Quickstart_Quickstart_Scatter.png"; var plt = new ScottPlot.Plot(600, 400); int pointCount = 51; double[] xs = DataGen.Consecutive(pointCount); double[] sin = DataGen.Sin(pointCount); double[] cos = DataGen.Cos(pointCount); plt.AddScatter(sin, cos, label: "sin"); plt.AddScatter(xs, cos, label: "cos"); plt.Legend(); plt.Title("Scatter Plot Quickstart"); plt.YLabel("Vertical Units"); plt.XLabel("Horizontal Units"); plt.SaveFig(saveFileLocation); Assert.IsTrue(System.IO.File.Exists(saveFileLocation)); System.IO.File.Delete(saveFileLocation); }
public static void PlotOHLC(List <StockHistoryDay> stockHistory, string folderName, string fileName) { List <ScottPlot.OHLC> valSeriesList = new List <ScottPlot.OHLC>(); foreach (StockHistoryDay stockHistoryDay in stockHistory) { ScottPlot.OHLC ohlc = new ScottPlot.OHLC( stockHistoryDay.Open, stockHistoryDay.High, stockHistoryDay.Low, stockHistoryDay.Close, stockHistoryDay.Date ); valSeriesList.Add(ohlc); } ScottPlot.OHLC[] valSeries = valSeriesList.ToArray(); var plt = new ScottPlot.Plot(1000, 700); plt.Title("MSFT", fontName: "Segoe UI Light", color: Color.Black); plt.Ticks(dateTimeX: true, fontName: "Cascadia Mono"); // grids at every 7 days plt.Grid(xSpacing: 7, xSpacingDateTimeUnit: ScottPlot.Config.DateTimeUnit.Day); plt.SetCulture(shortDatePattern: "M\\/dd"); // create folder if not exists System.IO.Directory.CreateDirectory(folderName); plt.PlotOHLC(valSeries); plt.SaveFig($"./{folderName}/{fileName}.png"); }
private void RightClickMenuItemClicked(object sender, ToolStripItemClickedEventArgs e) { ToolStripItem item = e.ClickedItem; switch (item.ToString()) { case "Save Image": cmRightClickMenu.Hide(); SaveFileDialog savefile = new SaveFileDialog(); savefile.FileName = "ScottPlot.png"; savefile.Filter = "PNG Files (*.png)|*.png|All files (*.*)|*.*"; if (savefile.ShowDialog() == DialogResult.OK) { plt.SaveFig(savefile.FileName); } break; case "Auto-Axis": cmRightClickMenu.Hide(); plt.AxisAuto(); Render(); break; case "Clear": cmRightClickMenu.Hide(); plt.Clear(); Render(); break; case "About ScottPlot": cmRightClickMenu.Hide(); System.Diagnostics.Process.Start("https://github.com/swharden/ScottPlot"); break; } }
public static void PlotMonthlyChange(List <MonthlyClosedDifference> series, string propertyName, string folderName, string fileName) { // get and convert specific property of a list of objects to array of doubles PropertyInfo prop = typeof(MonthlyClosedDifference).GetProperty(propertyName); double[] valSeries = series.Select(x => Convert.ToDouble(prop.GetValue(x))).ToArray(); // months to x values and labels double[] x = DataGen.Consecutive(series.Count()); string[] labels = series.Select(x => x.Month).ToArray(); var plt = new ScottPlot.Plot(1000, 700); plt.Title(propertyName, fontName: "Segoe UI Light", color: Color.Black); plt.Ticks(dateTimeX: false, fontName: "Cascadia Mono"); plt.Grid(xSpacing: 1); // apply custom axis tick labels plt.XTicks(x, labels); // create folder if not exists System.IO.Directory.CreateDirectory(folderName); plt.PlotBar(x, valSeries, fillColor: Color.Orange); plt.SaveFig($"./{folderName}/{fileName}.png"); }
public void Test_Window_Functions() { var plt = new ScottPlot.Plot(500, 400); double[] xs = ScottPlot.DataGen.Range(-1, 1, .01, true); plt.PlotScatter(xs, FftSharp.Window.Hanning(xs.Length), label: "Hanning"); plt.PlotScatter(xs, FftSharp.Window.Hamming(xs.Length), label: "Hamming"); plt.PlotScatter(xs, FftSharp.Window.Bartlett(xs.Length), label: "Bartlett"); plt.PlotScatter(xs, FftSharp.Window.Blackman(xs.Length), label: "Blackman"); //plt.PlotScatter(xs, FftSharp.Window.BlackmanExact(xs.Length), label: "BlackmanExact"); //plt.PlotScatter(xs, FftSharp.Window.BlackmanHarris(xs.Length), label: "BlackmanHarris"); plt.PlotScatter(xs, FftSharp.Window.FlatTop(xs.Length), label: "FlatTop"); plt.PlotScatter(xs, FftSharp.Window.Cosine(xs.Length), label: "Cosine"); // customize line styles post-hoc foreach (var p in plt.GetPlottables()) { if (p is ScottPlot.PlottableScatter) { ((ScottPlot.PlottableScatter)p).markerSize = 0; ((ScottPlot.PlottableScatter)p).lineWidth = 3; var c = ((ScottPlot.PlottableScatter)p).color; ((ScottPlot.PlottableScatter)p).color = System.Drawing.Color.FromArgb(200, c.R, c.G, c.B); } } plt.Legend(location: ScottPlot.legendLocation.upperRight); plt.SaveFig("../../../../../dev/windows.png"); }
public static void SaveImageDialog(Plot plt) { SaveFileDialog savefile = new SaveFileDialog(); savefile.FileName = "ScottPlot.png"; savefile.Filter = "PNG Files (*.png)|*.png|All files (*.*)|*.*"; if (savefile.ShowDialog() == DialogResult.OK) { plt.SaveFig(savefile.FileName); } }
static public void RunJolka(List <Solver <string> > backtracks, List <Solver <string> > backtrackfws, string heuristicB = "", string heuristicBF = "", string type = "") { var plt = new ScottPlot.Plot(1280, 720); List <double> xlist = new List <double>(); List <double> yfwlist = new List <double>(); List <double> ylist = new List <double>(); foreach (var el in backtrackfws) { xlist.Add(el.solvedPuzzle.Puzzle.id); if (type == "time") { yfwlist.Add(el.solvedPuzzle.elapsed.TotalMilliseconds); } else { yfwlist.Add(el.solvedPuzzle.Puzzle.steps); } } foreach (var el in backtracks) { if (type == "time") { ylist.Add(el.solvedPuzzle.elapsed.TotalMilliseconds); } else { ylist.Add(el.solvedPuzzle.Puzzle.steps); } } double[] xs = xlist.ToArray(); ylist.Insert(2, (double)1); double[] dataB = Tools.Log10(ylist.ToArray()); double[] dataBF = Tools.Log10(yfwlist.ToArray()); plt.PlotBar(xs, dataB, label: "Backtrack w/ " + heuristicB, barWidth: .3, xOffset: -0.2, showValues: true); plt.PlotBar(xs, dataBF, label: "Backtrack with forward w/ " + heuristicBF, barWidth: .3, xOffset: 0.2, showValues: true); plt.Title(type + " over Jolka id"); plt.Ticks(useExponentialNotation: false, useMultiplierNotation: false, logScaleY: true); plt.Axis(y1: 0); plt.XTicks(new string[] { "0", "1", "2", "3", "4" }); if (type == "time") { plt.YLabel("Execution time [10 ^ y ms]"); } else { plt.YLabel("Steps [10 ^ y]"); } plt.XLabel("Jolka ID"); plt.Legend(location: legendLocation.upperRight); plt.SaveFig(heuristicB + heuristicBF + type + "JolkaBvsBF" + ".png"); }
static void Main(string[] args) { //double[] xs = { 1, 2, 3, 4, 5, 6, 7 }; //double[] ys = { 2, 2, 3, 3, 3.8, 4.2, 4 }; //ScottPlot.Statistics.LinearRegressionLine model = new ScottPlot.Statistics.LinearRegressionLine(xs, ys); //Console.WriteLine(model.slope); //Console.WriteLine(model.offset); //Console.WriteLine(model.GetValueAt(3)); //for (int i = 0; i < xs.Length; i++) //{ // Console.WriteLine(model.GetValues()[i]); // Console.WriteLine(model.GetResiduals()[i]); //} //Console.Read(); Console.WriteLine("Hello World!"); int count = 400; double step = 0.01; double[] dataR = new double[count]; double[] dataTheta = new double[count]; double[] dataX = new double[count]; double[] dataY = new double[count]; for (int i = 0; i < dataR.Length; i++) { dataR[i] = 1 + (double)i * step; dataTheta[i] = i * 2 * Math.PI * step; } var plt = new ScottPlot.Plot(600, 400); (dataX, dataY) = ScottPlot.Tools.ConvertPolarCoordinates(dataR, dataTheta); plt.PlotScatter(dataX, dataY); string filename = "qucikstart.png"; plt.SaveFig(filename); using (Process process = new Process()) { //So the photo opens automatically (you need to use xdg-open on Linux) process.StartInfo.FileName = filename; process.StartInfo.UseShellExecute = true; process.Start(); } }
static void Main(string[] args) { BendStiffener bendStiffener = new BendStiffener { max_k = 0.3f, D1 = 0.7, d1 = 0.18, d2 = 0.2, L1 = 0.1, L2 = 2.3, L3 = 0.2, EIp = 1e4, Es = 4.5e6, F = 2e4, q = 0.52 }; int N = 10000; Vector <double>[] res = bendStiffener.bvpsolver_zzz(bendStiffener.Ode_to_solve, 0.0, bendStiffener.q, 0.0, 5.0, N); double[] x = Vector <double> .Build.Dense(N, i => i * 5.0 / N).ToArray(); double[] y = new double[N]; double[] dydx = new double[N]; for (int i = 0; i < N; i++) { double[] temp = res[i].ToArray(); y[i] = temp[0]; dydx[i] = temp[1]; //Console.WriteLine(t[i]); } var plt = new ScottPlot.Plot(800, 600); //plt.PlotScatter(x, y, label: "y", markerShape: (MarkerShape)Enum.Parse(typeof(MarkerShape), "none")); plt.PlotScatter(x, dydx, label: "dydx", markerShape: (MarkerShape)Enum.Parse(typeof(MarkerShape), "none")); plt.Grid(false); plt.Legend(fontSize: 10); //plt.PlotSignal(new[,] { x, y }); plt.SaveFig("quickstart.png"); Console.WriteLine("plot finished"); // gives 164,537981852489 //Test //Console.WriteLine(y[N / 10]); // gives 164,537981852489 //Console.WriteLine(Math.Exp(-1) + 3 * Math.Exp(4) - 5.0 / 2 + 23.0 / 8); //gives 164,537329540604, which is y(1) Console.ReadKey(); }
public static void SaveImageDialog(Plot plt) { SaveFileDialog savefile = new SaveFileDialog(); savefile.FileName = "ScottPlot.png"; savefile.Filter = "PNG Files (*.png)|*.png;*.png"; savefile.Filter += "|JPG Files (*.jpg, *.jpeg)|*.jpg;*.jpeg"; savefile.Filter += "|BMP Files (*.bmp)|*.bmp;*.bmp"; savefile.Filter += "|TIF files (*.tif, *.tiff)|*.tif;*.tiff"; savefile.Filter += "|All files (*.*)|*.*"; if (savefile.ShowDialog() == DialogResult.OK) { plt.SaveFig(savefile.FileName); } }
/// <summary> /// Method for plotting data to .png /// </summary> /// <param name="dataPoints"></param> public static void Graph(double[,] dataPoints) { double[] DataError = new double[dataPoints.GetUpperBound(0) + 1]; double[] DataAccuracy = new double[dataPoints.GetUpperBound(0) + 1]; double[] dataXs = new double[dataPoints.GetUpperBound(0) + 1]; for (int i = 0; i < dataXs.Length; i++) { dataXs[i] = i; DataError[i] = dataPoints[i, 0]; DataAccuracy[i] = dataPoints[i, 1]; } /// plot the data /// var plt_acc = new ScottPlot.Plot(800, 600); var plt_loss = new ScottPlot.Plot(800, 600); plt_acc.PlotScatter(dataXs, DataAccuracy, label: "Accuracy"); plt_loss.PlotScatter(dataXs, DataError, label: "Error rate"); plt_acc.Grid(xSpacing: 20, ySpacing: .1); plt_loss.Grid(xSpacing: 5, ySpacing: .1); plt_acc.Legend(location: legendLocation.upperLeft); plt_loss.Legend(location: legendLocation.upperLeft); plt_acc.Title("Accuracy"); plt_loss.Title("Loss"); plt_acc.XLabel("Epoch"); plt_acc.YLabel("Accuracy"); plt_loss.XLabel("Epoch"); plt_loss.YLabel("Loss"); plt_acc.SaveFig("NN_acc.png"); plt_loss.SaveFig("NN_loss.png"); Process.Start(new ProcessStartInfo(@"NN_acc.png") { UseShellExecute = true }); Process.Start(new ProcessStartInfo(@"NN_loss.png") { UseShellExecute = true }); }
private string MakeGraph(string[] labels, double[] values) { double[] xs = DataGen.Consecutive(labels.Count()); var plt = new ScottPlot.Plot(1920, 1080); plt.PlotBar(xs, values); // customize the plot to make it look nicer plt.Grid(enableVertical: false, lineStyle: LineStyle.Dot); plt.XTicks(xs, labels); plt.Ticks(fontSize: 25, xTickRotation: 45); plt.Layout(yScaleWidth: 80, titleHeight: 50, xLabelHeight: 200, y2LabelWidth: 20); string path = "graph.png"; plt.SaveFig(path); return path; }
public void GenerateMultipleBoxAndWhiskers(List <List <ResultModel> > allResults, List <int> xValues, string plotTitle, string plotName = "results") { var plt = new ScottPlot.Plot(600, 400); var poulations = new ScottPlot.Statistics.Population[allResults.Count]; var p = 0; foreach (var results in allResults) { var ys = new double[results.Count]; var i = 0; foreach (var r in results) { ys[i] = r.Fitness; i++; } var pop = new ScottPlot.Statistics.Population(ys); poulations[p] = pop; p++; } var popSeries = new ScottPlot.Statistics.PopulationSeries(poulations); plt.PlotPopulations(popSeries, "scores"); // improve the style of the plot plt.Title(plotTitle); plt.YLabel("Solution energy"); var ticks = new string[xValues.Count]; var j = 0; foreach (var iterations in xValues) { ticks[j] = iterations.ToString(); j++; } plt.XTicks(ticks); plt.Legend(); plt.Grid(lineStyle: LineStyle.Dot, enableVertical: false); plt.SaveFig($"{plotName}.png"); }
public static string SaveFig(ScottPlot.Plot plot) { var stackTrace = new System.Diagnostics.StackTrace(); string callingMethodName = stackTrace.GetFrame(1) !.GetMethod() !.Name; string filename = callingMethodName + ".png"; string folder = Path.GetFullPath("RenderTest"); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } string path = Path.Combine(folder, filename); var sw = System.Diagnostics.Stopwatch.StartNew(); plot.SaveFig(path); sw.Stop(); Console.WriteLine($"Saved in {sw.Elapsed.TotalMilliseconds:N3} ms"); Console.WriteLine(path); return(path); }
static public void RunSudoku(double[] difficulty, double[] dataB, double[] dataBF, string heuristicB = "", string heuristicBF = "", string type = "") { var plt = new ScottPlot.Plot(1280, 720); int pointCount = dataB.Length; plt.PlotBar(difficulty, dataB, label: "Backtrack w/ " + heuristicB, barWidth: .3, xOffset: -0.2); plt.PlotBar(difficulty, dataBF, label: "Backtrack with forward w/ " + heuristicBF, barWidth: .3, xOffset: 0.2); plt.Title("Average " + type + " over sudoku difficulty"); plt.Axis(y1: 0); if (type == "time") { plt.YLabel("Execution time [ms]"); } else { plt.YLabel("Steps"); } plt.XLabel("Difficulty"); plt.Legend(location: legendLocation.upperRight); plt.Ticks(useExponentialNotation: false, useMultiplierNotation: false); plt.SaveFig(heuristicB + heuristicBF + type + "BvsBF" + ".png"); }
static void Main(string[] args) { int N = 10000; Vector <double> y0 = Vector <double> .Build.Dense(new[] { -7.0 / 4.0, 55.0 / 8.0 }); //Func<double, Vector<double>, Vector<double>> der = DerivativeMaker(); Vector <double>[] res = RungeKutta.FourthOrder(y0, 0, 10, N, DerivativeMaker_zzz2); double[] t = Vector <double> .Build.Dense(N, i => i * 10.0 / N).ToArray(); double[] x = new double[N]; double[] y = new double[N]; for (int i = 0; i < N; i++) { double[] temp = res[i].ToArray(); x[i] = temp[0]; y[i] = temp[1]; //Console.WriteLine(t[i]); } var plt = new ScottPlot.Plot(800, 600); plt.PlotScatter(t, x, label: "x", markerShape: (MarkerShape)Enum.Parse(typeof(MarkerShape), "none")); plt.PlotScatter(t, y, label: "y", markerShape: (MarkerShape)Enum.Parse(typeof(MarkerShape), "none")); plt.Grid(false); plt.Legend(fontSize: 10); //plt.PlotSignal(new[,] { x, y }); plt.SaveFig("quickstart.png"); //Test Console.WriteLine(y[N / 10]); // gives 164,537981852489 Console.WriteLine(Math.Exp(-1) + 3 * Math.Exp(4) - 5.0 / 2 + 23.0 / 8); //gives 164,537329540604, which is y(1) Console.ReadKey(); }
static void Main(string[] args) { Dictionary <string, double> hyp_val = new Dictionary <string, double> { { "ab", 0.6 }, { "bc", 0.3 }, { "a", 0.1 }, { "ad", 0.0 } }; MassFunction m = new MassFunction(hyp_val); m.ComputeFocalSet(); m.ComputeFrameOfDiscernment(); var bel = m.belief("ab"); var pl = m.plausibility("ab"); var q = m.commonality("ab"); // get belief function and then get mass function from belief function var bf = m.beliefFunction(); var mf = m.fromBelief(bf); // get plausibility function and then get mass function from plausibility function var pf = m.plausFunction(); var mf_pf = m.fromPlausibility(pf); // get commonality function and then get mass function from commonality function var qf = m.commFunction(); var mf_qf = m.fromCommonality(qf); //combine deterministically Dictionary <string, double> hyp_val2 = new Dictionary <string, double> { { "ab", 0.4 }, { "bc", 0.4 }, { "a", 0.2 }, { "ad", 0.0 } }; var combined = m.combinedDeterministically(hyp_val2, hyp_val, false); // conjunctive combination // combine disjunctive var disjunctive_combined = m.combinedDeterministically(hyp_val2, hyp_val, true); // combine with normalization var combined_norm = m.combine(hyp_val2, hyp_val, true, 0, false, false); var combinedSample = m.combinedDirectSampling(hyp_val2, hyp_val, 1000, false); // conjunctive combination var combinedImportanceSample = m.combinedImportanceSampling(hyp_val2, hyp_val, 1000); var samples = m.sample(1000, true, mf_pf); // test gbt var mf_from_gbt = m.gbt(pf, false, 0); var pignistic = m.pignistic(); Dictionary <string, double> mcc1 = new Dictionary <string, double> { { "ab", 0.3 }, { "bc", 0.5 }, { "abc", 0.2 } }; Dictionary <string, double> mcc2 = new Dictionary <string, double> { { "b", 0.3 }, { "bc", 0.4 }, { "abc", 0.3 } }; m.combineCautious(mcc1, mcc2, false); //compute for 1000 samples int sampleSize = 1000; //if combined_cautious bool combinedCautious = false; //Time List <double> time = new List <double>(); for (double i = 0; i < sampleSize; i++) { time.Add(i + 1); } // Now create a window for creating intrusions and causing attacks on the grid // Let say a cyber intrusion was performed on time [5,20] .... then [80,120]... then get control [200,250] //create a list of tuple List <Tuple <int, int> > cyber_intrusions_ids1 = new List <Tuple <int, int> >(); Tuple <int, int> event1 = new Tuple <int, int>(5, 20); cyber_intrusions_ids1.Add(event1); Tuple <int, int> event2 = new Tuple <int, int>(80, 120); cyber_intrusions_ids1.Add(event2); Tuple <int, int> event3 = new Tuple <int, int>(200, 250); cyber_intrusions_ids1.Add(event3); Tuple <int, int> event4 = new Tuple <int, int>(400, 470); cyber_intrusions_ids1.Add(event4); Tuple <int, int> event5 = new Tuple <int, int>(700, 790); cyber_intrusions_ids1.Add(event5); List <Tuple <int, int> > cyber_intrusions_ids2 = new List <Tuple <int, int> >(); Tuple <int, int> event6 = new Tuple <int, int>(15, 25); cyber_intrusions_ids2.Add(event6); Tuple <int, int> event7 = new Tuple <int, int>(90, 135); cyber_intrusions_ids2.Add(event7); Tuple <int, int> event8 = new Tuple <int, int>(220, 260); cyber_intrusions_ids2.Add(event8); Tuple <int, int> event9 = new Tuple <int, int>(390, 450); cyber_intrusions_ids2.Add(event9); Tuple <int, int> event10 = new Tuple <int, int>(670, 730); cyber_intrusions_ids2.Add(event10); List <Tuple <int, int> > cyber_intrusions_ids3 = new List <Tuple <int, int> >(); Tuple <int, int> event11 = new Tuple <int, int>(90, 110); cyber_intrusions_ids3.Add(event11); Tuple <int, int> event12 = new Tuple <int, int>(120, 130); cyber_intrusions_ids3.Add(event12); Tuple <int, int> event13 = new Tuple <int, int>(230, 290); cyber_intrusions_ids3.Add(event13); Tuple <int, int> event14 = new Tuple <int, int>(380, 440); cyber_intrusions_ids3.Add(event14); Tuple <int, int> event15 = new Tuple <int, int>(670, 740); cyber_intrusions_ids3.Add(event15); // perform physical attack to modify measurements from [260,270] //var sensor1_mf_list = generaterandommassfunction(samplesize); //var sensor2_mf_list = generaterandommassfunction(samplesize); //var sensor3_mf_list = generaterandommassfunction(samplesize); var sensor1_mf_list = GenerateRandomMassFunctionScenario(sampleSize, cyber_intrusions_ids1); var sensor2_mf_list = GenerateRandomMassFunctionScenario(sampleSize, cyber_intrusions_ids2); var sensor3_mf_list = GenerateRandomMassFunctionScenario(sampleSize, cyber_intrusions_ids3); List <string> ranked_Hyp_ByBelief = new List <string>(); List <double> ranked_count_ByBelief = new List <double>(); List <string> ranked_Hyp_ByPlausibility = new List <string>(); List <double> ranked_count_ByPlausibility = new List <double>(); List <string> rankedPignistic = new List <string>(); List <double> ranked_count_ByPignistic = new List <double>(); // construct mf using Generalized bayesian Theorem and store it here for every sample fused. List <Dictionary <string, double> > gbt_sample_fused = new List <Dictionary <string, double> >(); List <string> ranked_mf_gbt = new List <string>(); List <double> ranked_count_ByGBT = new List <double>(); List <double> conflictMeasure = new List <double>(); List <double> hartleyMeasure = new List <double>(); for (int i = 0; i < sampleSize; i++) { var s1_mf = sensor1_mf_list[i]; var s2_mf = sensor2_mf_list[i]; var fused = m.combinedDeterministically(s1_mf, s2_mf, false); //if (combinedCautious && (s1_mf.Count != 1) && (s2_mf.Count != 1)) fused = m.combineCautious(s1_mf, s2_mf); if (combinedCautious) { fused = m.combineCautious(s1_mf, s2_mf, false); } var s3_mf = sensor3_mf_list[i]; var fused3 = m.combinedDeterministically(fused, s3_mf, false); //if (combinedCautious && (fused.Count != 1) && (s3_mf.Count != 1)) fused3 = m.combineCautious(fused, s3_mf); if (combinedCautious) { fused3 = m.combineCautious(fused, s3_mf, false); } //conflict measure MassFunction t1 = new MassFunction(fused); MassFunction t2 = new MassFunction(s3_mf); var conflict = m.conflict(t1, t2, 0); conflictMeasure.Add(conflict); //hartley measure var hartley = m.hartley_measure(fused3); hartleyMeasure.Add(hartley); MassFunction newM = new MassFunction(fused3); newM.ComputeFocalSet(); newM.ComputeFrameOfDiscernment(); var bel_func = newM.beliefFunction(); var plaus_func = newM.plausFunction(); // test gbt var gbt_mf = newM.gbt(plaus_func, false, 0); gbt_sample_fused.Add(gbt_mf); // decision basis var max_hyp_bel = bel_func.OrderByDescending(x => x.Value).First().Key; ranked_Hyp_ByBelief.Add(max_hyp_bel); ranked_count_ByBelief.Add(Convert.ToDouble(max_hyp_bel.Length)); var max_hyp_plaus = plaus_func.OrderByDescending(x => x.Value).First().Key; ranked_Hyp_ByPlausibility.Add(max_hyp_plaus); ranked_count_ByPlausibility.Add(Convert.ToDouble(max_hyp_plaus.Length)); var pignisticFunction = newM.pignistic(); if (pignisticFunction != null && pignisticFunction.Count != 0) { var max_pignistic = pignisticFunction.OrderByDescending(x => x.Value).First().Key; rankedPignistic.Add(max_pignistic); ranked_count_ByPignistic.Add(Convert.ToDouble(max_pignistic.Length)); } else { rankedPignistic.Add(max_hyp_plaus); ranked_count_ByPignistic.Add(Convert.ToDouble(max_hyp_plaus.Length)); } var max_mf_gbt = gbt_mf.OrderByDescending(x => x.Value).First().Key; ranked_mf_gbt.Add(max_mf_gbt); ranked_count_ByGBT.Add(Convert.ToDouble(max_mf_gbt.Length)); } //plot conflict measure var plt_conflict = new ScottPlot.Plot(800, 400); plt_conflict.PlotScatter(time.ToArray(), conflictMeasure.ToArray()); plt_conflict.SaveFig("conflict_measure.png"); //plot hartley measure var plt_hartley = new ScottPlot.Plot(800, 400); plt_hartley.PlotScatter(time.ToArray(), hartleyMeasure.ToArray()); plt_hartley.SaveFig("hartley_measure.png"); //plot the decision rules based on the count of strings that were ranked highest in the evidences var plt_rank_belief = new ScottPlot.Plot(800, 400); plt_rank_belief.PlotScatter(time.ToArray(), ranked_count_ByBelief.ToArray()); plt_rank_belief.SaveFig("rank_belief_count.png"); var plt_rank_plausibility = new ScottPlot.Plot(800, 400); plt_rank_plausibility.PlotScatter(time.ToArray(), ranked_count_ByPlausibility.ToArray()); plt_rank_plausibility.SaveFig("rank_plausibility_count.png"); var plt_rank_pignistic = new ScottPlot.Plot(800, 400); plt_rank_pignistic.PlotScatter(time.ToArray(), ranked_count_ByPignistic.ToArray()); plt_rank_pignistic.SaveFig("rank_pignistic_count.png"); var plt_rank_gbt = new ScottPlot.Plot(800, 400); plt_rank_gbt.PlotScatter(time.ToArray(), ranked_count_ByGBT.ToArray()); plt_rank_gbt.SaveFig("rank_gbt_count.png"); // Now create a window for creating intrusions and causing attacks on the grid // Let say a cyber intrusion was performed on time [5,20] .... then [80,120]... then get control [200,250] //create a list of tuple List <Tuple <int, int> > physical_intrusions = new List <Tuple <int, int> >(); Tuple <int, int> pevent1 = new Tuple <int, int>(20, 25); physical_intrusions.Add(pevent1); Tuple <int, int> pevent2 = new Tuple <int, int>(118, 125); physical_intrusions.Add(pevent2); Tuple <int, int> pevent3 = new Tuple <int, int>(230, 240); physical_intrusions.Add(pevent3); Tuple <int, int> pevent4 = new Tuple <int, int>(465, 490); physical_intrusions.Add(pevent4); Tuple <int, int> pevent5 = new Tuple <int, int>(860, 910); physical_intrusions.Add(pevent5); // generate physical data: voltage for a 3 bus system int nbus = 3; Random rand = new Random(); List <List <double> > voltages = new List <List <double> >(); for (int i = 0; i < nbus; i++) { List <double> volt_bus = new List <double>(); for (int j = 0; j < sampleSize; j++) { double start = 0.8; double end = 1.2; if (!IsInRange(j, physical_intrusions)) { end = 1.05; start = 0.95; } var v = (rand.NextDouble() * Math.Abs(end - start)) + start; volt_bus.Add(v); } voltages.Add(volt_bus); } //plot voltages using scottplot bool smoothen = true; if (smoothen) { voltages[0] = MovingAverage(10, voltages[0]); voltages[1] = MovingAverage(10, voltages[1]); voltages[2] = MovingAverage(10, voltages[2]); } var v1 = voltages[0].ToArray(); var v2 = voltages[1].ToArray(); var v3 = voltages[2].ToArray(); var plt1 = new ScottPlot.Plot(800, 400); var plt2 = new ScottPlot.Plot(800, 400); var plt3 = new ScottPlot.Plot(800, 400); plt1.PlotScatter(time.ToArray(), v1); plt1.SaveFig("v1.png"); plt2.PlotScatter(time.ToArray(), v2); plt2.SaveFig("v2.png"); plt3.PlotScatter(time.ToArray(), v3); plt3.SaveFig("v3.png"); // compute mass function for the physical values double t_low_lower_limit = 0.93; double t_high_lower_limit = 0.97; double t_low_higher_limit = 1.03; double t_high_higher_limit = 1.07; List <Dictionary <string, double> > phyList = new List <Dictionary <string, double> >(); String[] phyKeys = new string[3] { "x", "y", "z" }; for (int i = 0; i < sampleSize; i++) { Dictionary <string, double> mf_per_sample = new Dictionary <string, double>(); for (int j = 0; j < nbus; j++) { if (voltages[j][i] >= t_high_lower_limit && voltages[j][i] <= t_low_higher_limit) { mf_per_sample[phyKeys[j]] = 0.0; } else if (voltages[j][i] <= t_high_lower_limit && voltages[j][i] >= t_low_lower_limit) { mf_per_sample[phyKeys[j]] = 1.0 + Convert.ToDouble(Convert.ToDouble(t_low_lower_limit - voltages[j][i]) / Convert.ToDouble(t_high_lower_limit - t_low_lower_limit)); } else if (voltages[j][i] <= t_high_higher_limit && voltages[j][i] >= t_low_higher_limit) { mf_per_sample[phyKeys[j]] = 1.0 + Convert.ToDouble(Convert.ToDouble(voltages[j][i] - t_high_higher_limit) / Convert.ToDouble(t_high_higher_limit - t_low_higher_limit)); } else { mf_per_sample[phyKeys[j]] = 1.0; } } if (IsAllBPANull(mf_per_sample)) { phyList.Add(new Dictionary <string, double> { { "", 1.0 } }); } else { phyList.Add(normalize(mf_per_sample)); } } List <string> cp_ranked_Hyp_ByBelief = new List <string>(); List <double> cp_ranked_count_ByBelief = new List <double>(); List <string> cp_ranked_Hyp_ByPlausibility = new List <string>(); List <double> cp_ranked_count_ByPlausibility = new List <double>(); List <string> cp_rankedPignistic = new List <string>(); List <double> cp_ranked_count_ByPignistic = new List <double>(); // construct mf using Generalized bayesian Theorem and store it here for every sample fused. List <Dictionary <string, double> > cp_gbt_sample_fused = new List <Dictionary <string, double> >(); List <string> cp_ranked_mf_gbt = new List <string>(); List <double> cp_ranked_count_ByGBT = new List <double>(); List <double> cpConflictMeasure = new List <double>(); List <double> cpHartleyMeasure = new List <double>(); bool combinedCautiousCP = false; //test fusing cyber sensor with the physical sensor for (int i = 0; i < sampleSize; i++) { var s1_mf = sensor1_mf_list[i]; var p1_mf = phyList[i]; var fused = m.combinedDeterministically(s1_mf, p1_mf, true); if (combinedCautiousCP) { fused = m.combineCautious(s1_mf, p1_mf, true); } //conflict measure MassFunction t1 = new MassFunction(s1_mf); MassFunction t2 = new MassFunction(p1_mf); var conflict = m.conflict(t1, t2, 0); cpConflictMeasure.Add(conflict); //hartley measure var hartley = m.hartley_measure(fused); cpHartleyMeasure.Add(hartley); MassFunction newM = new MassFunction(fused); newM.ComputeFocalSet(); newM.ComputeFrameOfDiscernment(); var bel_func = newM.beliefFunction(); var plaus_func = newM.plausFunction(); //// test gbt //var gbt_mf = newM.gbt(plaus_func, false, 0); //cp_gbt_sample_fused.Add(gbt_mf); // decision var max_hyp_bel = bel_func.OrderByDescending(x => x.Value).First().Key; cp_ranked_Hyp_ByBelief.Add(max_hyp_bel); cp_ranked_count_ByBelief.Add(Convert.ToDouble(max_hyp_bel.Length)); var max_hyp_plaus = plaus_func.OrderByDescending(x => x.Value).First().Key; cp_ranked_Hyp_ByPlausibility.Add(max_hyp_plaus); cp_ranked_count_ByPlausibility.Add(Convert.ToDouble(max_hyp_plaus.Length)); var pignisticFunction = newM.pignistic(); if (pignisticFunction != null && pignisticFunction.Count != 0) { var max_pignistic = pignisticFunction.OrderByDescending(x => x.Value).First().Key; rankedPignistic.Add(max_pignistic); cp_ranked_count_ByPignistic.Add(Convert.ToDouble(max_pignistic.Length)); } else { rankedPignistic.Add(max_hyp_plaus); cp_ranked_count_ByPignistic.Add(Convert.ToDouble(max_hyp_plaus.Length)); } //var max_mf_gbt = gbt_mf.OrderByDescending(x => x.Value).First().Key; //ranked_mf_gbt.Add(max_mf_gbt); //cp_ranked_count_ByGBT.Add(Convert.ToDouble(max_mf_gbt.Length)); } //plot conflict measure var cp_plt_conflict = new ScottPlot.Plot(800, 400); cp_plt_conflict.PlotScatter(time.ToArray(), cpConflictMeasure.ToArray()); cp_plt_conflict.SaveFig("cp_conflict_measure.png"); //plot hartley measure var cp_plt_hartley = new ScottPlot.Plot(800, 400); cp_plt_hartley.PlotScatter(time.ToArray(), cpHartleyMeasure.ToArray()); cp_plt_hartley.SaveFig("cp_hartley_measure.png"); //plot the decision rules based on the count of strings that were ranked highest in the evidences var cp_plt_rank_belief = new ScottPlot.Plot(800, 400); cp_plt_rank_belief.PlotScatter(time.ToArray(), cp_ranked_count_ByBelief.ToArray()); cp_plt_rank_belief.SaveFig("cp_rank_belief_count.png"); var cp_plt_rank_plausibility = new ScottPlot.Plot(800, 400); cp_plt_rank_plausibility.PlotScatter(time.ToArray(), cp_ranked_count_ByPlausibility.ToArray()); cp_plt_rank_plausibility.SaveFig("cp_rank_plausibility_count.png"); var cp_plt_rank_pignistic = new ScottPlot.Plot(800, 400); cp_plt_rank_pignistic.PlotScatter(time.ToArray(), cp_ranked_count_ByPignistic.ToArray()); cp_plt_rank_pignistic.SaveFig("cp_rank_pignistic_count.png"); //var cp_plt_rank_gbt = new ScottPlot.Plot(800, 400); //cp_plt_rank_gbt.PlotScatter(time.ToArray(), cp_ranked_count_ByGBT.ToArray()); //cp_plt_rank_gbt.SaveFig("cp_rank_gbt_count.png"); Dictionary <string, double> testpf = new Dictionary <string, double> { { "b", 0.5 }, { "c", 0.8 } }; var m_gbt = m.gbt(testpf, true, 20000); Dictionary <string, double> hyp = new Dictionary <string, double> { { "ab", 0.3 }, { "bc", 0.5 }, { "abc", 0.2 } }; MassFunction m2 = new MassFunction(hyp); m2.ComputeFocalSet(); m2.ComputeFrameOfDiscernment(); m2.weight_function(); var conf = m.conflict(m, m2, 1000); }
static void Main(string[] args) { //Read data var USDataReader = new USYieldDataXMLReader(); USDataReader.filepath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\", "Data\\USDYieldCurveDailyData2020.xml")); var Data = USDataReader.GetFullTimeSeriesData(); var yields = Data["2020-02-11"]; var tau = new double[12] { (double)1 / 12, (double)2 / 12, (double)3 / 12, (double)6 / 12, 1, 2, 3, 5, 7, 10, 20, 30 }; //// Test--------------------------------------- Static NS 3 factors model------------------------------------------------// //var NS3factorCalibration = new StaticNS3FactorModelCalibration(); //NS3factorCalibration.yields = yields; //NS3factorCalibration.maturities = tau; //var optimziedpara = NS3factorCalibration.Calibration(); //var modeloutput = NS3factorCalibration.CalculateModelOutput(tau, optimziedpara); //Console.WriteLine("NS 3 Factor Model Is Calibrated."); ////Plot //var plt = new ScottPlot.Plot(600, 400); //plt.PlotSignalXY(tau, yields, color: Color.Red, label: "Market Data"); //plt.PlotSignalXY(tau, modeloutput, color: Color.Blue, label: "Model Output"); //plt.Legend(); //plt.XLabel("Time to maturity"); //plt.YLabel("Annualized yields (%)"); //var savepath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\", "Pictures\\NS3FactorModelEmpiricalResult.png")); //plt.SaveFig(savepath); //Process.Start(savepath); //// Test--------------------------------------- Static NS 4 factors model------------------------------------------------// //var NS4factorCalibration = new StaticNS4FactorModelCalibration(); //NS4factorCalibration.yields = yields; //NS4factorCalibration.maturities = tau; //var optimziedpara2 = NS4factorCalibration.Calibration(); //var modeloutput2 = NS4factorCalibration.CalculateModelOutput(tau, optimziedpara2); //Console.WriteLine("NS 4 Factor Model Is Calibrated."); ////Plot //var plt2 = new ScottPlot.Plot(600, 400); //plt2.PlotSignalXY(tau, yields, color: Color.Red, label: "Market Data"); //plt2.PlotSignalXY(tau, modeloutput2, color: Color.Blue, label: "Model Output"); //plt2.Legend(); //plt2.XLabel("Time to maturity"); //plt2.YLabel("Annualized yields (%)"); //var savepath2 = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\", "Pictures\\NS4FactorModelEmpiricalResult.png")); //plt2.SaveFig(savepath2); //Process.Start(savepath2); //// Test--------------------------------------- Static Vasicek Two factors model------------------------------------------------// //var V2FactorCal = new StaticVasicekTwoFactorModelCalibration(); //V2FactorCal.yields = yields; //V2FactorCal.maturities = tau; //var V2FactorOptPara = V2FactorCal.Calibration(); //var V2Factor = new StaticVasicekTwoFactorModel(); //V2Factor.maturities = tau; //var modeloutputV2 = V2FactorCal.CalcualteModelOutput(V2FactorOptPara); //Console.WriteLine("Vasicek 2 Factor Model Is Calibrated."); ////Plot //var pltv2 = new ScottPlot.Plot(600, 400); //pltv2.PlotSignalXY(tau, yields, color: Color.Red, label: "Market Data"); //pltv2.PlotSignalXY(tau, modeloutputV2, color: Color.Blue, label: "Model Output"); //pltv2.Legend(); //pltv2.XLabel("Time to maturity"); //pltv2.YLabel("Annualized yields (%)"); //var savepathV2 = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\", "Pictures\\VasicekTwoFactorModelEmpiricalResult.png")); //pltv2.SaveFig(savepathV2); //Process.Start(savepathV2); // Test--------------------------------------- Static Longstaff Schwartz Two factors model------------------------------------------------// var LS2FactorCal = new StaticTwoFactorLongstaffSchwartzModelCalibration(); LS2FactorCal.yields = yields; LS2FactorCal.maturities = tau; var LS2FactorOptPara = LS2FactorCal.Calibration(); var LS2Factor = new StaticTwoFactorLongstaffSchwartzModel(); LS2Factor.maturities = tau; var modeloutputLS2 = LS2FactorCal.CalcualteModelOutput(LS2FactorOptPara); Console.WriteLine("Longstaff Schwartz 2 Factor Model Is Calibrated."); //Plot var pltls2 = new ScottPlot.Plot(600, 400); pltls2.PlotSignalXY(tau, yields, color: Color.Red, label: "Market Data"); pltls2.PlotSignalXY(tau, modeloutputLS2, color: Color.Blue, label: "Model Output"); pltls2.Legend(); pltls2.XLabel("Time to maturity"); pltls2.YLabel("Annualized yields (%)"); var savepathls2 = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\", "Pictures\\LongstaffSchwartzTwoFactorModelEmpiricalResult.png")); pltls2.SaveFig(savepathls2); Process.Start(savepathls2); ////Test dynamic NS3 factor model //var DynaimcNS3factor = new DynamicNS3FactorModelCalibration(); //DynaimcNS3factor.yields = Data; //DynaimcNS3factor.maturities = tau; //var optimziedpara=DynaimcNS3factor.Optimize(); //(var tvbeta1, var tvbeta2, var tvbeta3) = DynaimcNS3factor.GetDynamicBetas(optimziedpara); ////Plot //// Beta1 //var pltbeta1 = new ScottPlot.Plot(600, 400); //pltbeta1.PlotSignal(tvbeta1, color: Color.Red, label: "Time-varying Beta1"); //pltbeta1.Legend(); //pltbeta1.XLabel("History Time"); //pltbeta1.YLabel("Beta1"); //var savepathbeta1 = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\", "Pictures\\DynamicNS3FactorModelBeta1.png")); //pltbeta1.SaveFig(savepathbeta1); //Process.Start(savepathbeta1); //// Beta2 //var pltbeta2 = new ScottPlot.Plot(600, 400); //pltbeta2.PlotSignal(tvbeta2, color: Color.Red, label: "Time-varying Beta2"); //pltbeta2.Legend(); //pltbeta2.XLabel("History Time"); //pltbeta2.YLabel("Beta2"); //var savepathbeta2 = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\", "Pictures\\DynamicNS3FactorModelBeta2.png")); //pltbeta2.SaveFig(savepathbeta2); //Process.Start(savepathbeta2); //// Beta3 //var pltbeta3 = new ScottPlot.Plot(600, 400); //pltbeta3.PlotSignal(tvbeta3, color: Color.Red, label: "Time-varying Beta3"); //pltbeta3.Legend(); //pltbeta3.XLabel("History Time"); //pltbeta3.YLabel("Beta3"); //var savepathbeta3 = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\", "Pictures\\DynamicNS3FactorModelBeta3.png")); //pltbeta3.SaveFig(savepathbeta3); //Process.Start(savepathbeta3); ////Test dynamic NS4 factor model //var DynaimcNS4factor = new DynamicNS4FactorModelCalibration(); //DynaimcNS4factor.yields = Data; //DynaimcNS4factor.maturities = tau; //var optimziedpara = DynaimcNS4factor.Optimize(); //(var tvbeta1, var tvbeta2, var tvbeta3, var tvbeta4) = DynaimcNS4factor.GetDynamicBetas(optimziedpara); ////Plot //// Beta1 //var pltbeta1 = new ScottPlot.Plot(600, 400); //pltbeta1.PlotSignal(tvbeta1, color: Color.Red, label: "Time-varying Beta1"); //pltbeta1.Legend(); //pltbeta1.XLabel("History Time"); //pltbeta1.YLabel("Beta1"); //var savepathbeta1 = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\", "Pictures\\DynamicNS3FactorModelBeta1.png")); //pltbeta1.SaveFig(savepathbeta1); //Process.Start(savepathbeta1); //// Beta2 //var pltbeta2 = new ScottPlot.Plot(600, 400); //pltbeta2.PlotSignal(tvbeta2, color: Color.Red, label: "Time-varying Beta2"); //pltbeta2.Legend(); //pltbeta2.XLabel("History Time"); //pltbeta2.YLabel("Beta2"); //var savepathbeta2 = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\", "Pictures\\DynamicNS3FactorModelBeta2.png")); //pltbeta2.SaveFig(savepathbeta2); //Process.Start(savepathbeta2); //// Beta3 //var pltbeta3 = new ScottPlot.Plot(600, 400); //pltbeta3.PlotSignal(tvbeta3, color: Color.Red, label: "Time-varying Beta3"); //pltbeta3.Legend(); //pltbeta3.XLabel("History Time"); //pltbeta3.YLabel("Beta3"); //var savepathbeta3 = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\", "Pictures\\DynamicNS3FactorModelBeta3.png")); //pltbeta3.SaveFig(savepathbeta3); //Process.Start(savepathbeta3); //// Beta3 //var pltbeta4 = new ScottPlot.Plot(600, 400); //pltbeta4.PlotSignal(tvbeta4, color: Color.Red, label: "Time-varying Beta4"); //pltbeta4.Legend(); //pltbeta4.XLabel("History Time"); //pltbeta4.YLabel("Beta4"); //var savepathbeta4 = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\", "Pictures\\DynamicNS3FactorModelBeta4.png")); //pltbeta4.SaveFig(savepathbeta4); //Process.Start(savepathbeta4); Console.WriteLine("Press any key to exit"); Console.ReadKey(); }
private void btnSubmitHilos_Click(object sender, EventArgs e) { txtResFact.Clear(); lblResponse.Text = ""; BigInteger numero = 0; int iteraciones = 0; try { numero = int.Parse(numeroFact.Text); iteraciones = int.Parse(numItera.Text); } catch (Exception) { numero = 0; iteraciones = 0; } if (numero > 0 && iteraciones > 0) { txtResFact.Visible = false; Dictionary <double[], string> response = new Dictionary <double[], string>(); lblError.Visible = false; string formated = string.Format("{0}", numero); //OBTENER Numero Hilos, Tiempo en ms , y el string con info completa response = Principal.ObtenerFactoriales(numero, iteraciones); //PARA GRAFICA var plt = new ScottPlot.Plot(600, 400); double[] tiempos = new double[response.Count]; double[] hilos = new double[response.Count]; int i = 0; foreach (double[] val in response.Keys) { hilos[i] = val[0]; tiempos[i] = val[1]; i++; } plt.PlotScatter(hilos, tiempos); plt.Legend(); plt.Title("Hilos vs Tiempo de Obtener Factorial"); plt.YLabel("Tiempo(ms)"); plt.XLabel("Hilos"); string nombreImagen = string.Format("../../{0}_{1}_Grafica.png", numero, iteraciones); try { plt.SaveFig(nombreImagen); lblConfirmed.Text = "Se ha guardado la gráfica en png"; } catch (Exception) { lblConfirmed.Text = "No se ha podido guardar la información"; } lblConfirmed.Visible = true; //IMPRIMIR EN FORMS foreach (string val in response.Values) { lblResponse.Text += string.Format($"{val} \n"); Console.WriteLine(val); } } else { lblError.Visible = true; } }
public static string chart(string pair) { List <string> pena = new List <string>(); System.Net.WebClient wc1 = new System.Net.WebClient(); int sum_chart = 150; double last_price = 0; String link_Response = wc1.DownloadString("https://www.binance.com/api/v1/klines?symbol=" + pair + "&interval=15m&limit=" + sum_chart); MatchCollection matchList = System.Text.RegularExpressions.Regex.Matches(link_Response, @"(\d+.\d+)|\d+\d+|\d"); pena = matchList.Cast <Match>().Select(match => match.Value).ToList(); System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); int count = 0; int count_draw = 0; //Оишбка в апи hbc в конце несколкьо нулей 0 0 0 0 0 //введен костыль-переменная ScottPlot.OHLC[] ohlcs = new ScottPlot.OHLC[sum_chart]; var plt = new ScottPlot.Plot(800, 400); for (int i = 0; i < sum_chart; i++) { double Open = Convert.ToDouble(pena[count_draw + 1]); double High = Convert.ToDouble(pena[count_draw + 2]); double Low = Convert.ToDouble(pena[count_draw + 3]); double Close = Convert.ToDouble(pena[count_draw + 4]); double Opentime = ((Convert.ToDouble(pena[count_draw])) / 1000) + (3600 * 3); ohlcs[count] = new ScottPlot.OHLC(Open, High, Low, Close, ConvertFromUnixTimestamp(Opentime), 1); count_draw = count_draw + 12; count++; last_price = Close; } plt.Title("15 Minute Chart"); plt.YLabel("Stock Price (" + pair + ")"); plt.Ticks(dateTimeX: true, dateTimeFormatStringX: "HH:mm:ss", numericFormatStringY: "n"); plt.PlotCandlestick(ohlcs); plt.Style(tick: Color.White, label: Color.White, title: Color.White, dataBg: Color.FromArgb(255, 36, 43, 60), grid: Color.FromArgb(255, 36, 43, 60), figBg: Color.FromArgb(255, 36, 43, 60)); DateTime date1 = new DateTime(); date1 = DateTime.Now; string name = "PlotTypes" + pair + "№" + date1.Ticks + ".png"; string name_file = name; string label_name = Convert.ToString(last_price); plt.PlotHLine(y: last_price, color: Color.Green, lineWidth: 0.5, label: label_name); plt.Legend(backColor: Color.FromArgb(255, 36, 43, 60), location: legendLocation.upperCenter); plt.SaveFig(name_file); return(name_file); }