/// <summary> /// Экпорт диаграммы в один из типов /// </summary> /// <param name="type">Тип для экспорта</param> public void ExportDiagram(ExportType type) { SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.Filter = type + " файлы (*." + type + ")|*." + type; bool? result = saveDialog.ShowDialog(); if (result == true) switch (type) { case ExportType.pdf: PdfExporter pdfExporter = new PdfExporter(); pdfExporter.Export(DiagramNetwork, saveDialog.FileName); break; case ExportType.svg: SvgExporter svgExporter = new SvgExporter(); svgExporter.Export(DiagramNetwork, saveDialog.FileName); break; } }
// TODO: Draw to pdf file public void XLDrawMSMatchToPdf(Ms2ScanWithSpecificMass MsScanForDraw, PsmCross psmParentsForDraw, int order, string OutputFolder) { var x = MsScanForDraw.TheScan.MassSpectrum.XArray; var y = MsScanForDraw.TheScan.MassSpectrum.YArray; string scanNum = psmParentsForDraw.ScanNumber.ToString(); string sequence1 = psmParentsForDraw.FullSequence + "-" + psmParentsForDraw.XlPos.ToString(); string sequence2 = psmParentsForDraw.BetaPsmCross.FullSequence + "-" + psmParentsForDraw.BetaPsmCross.XlPos.ToString(); var matchedIonDic1 = psmParentsForDraw.MatchedIonInfo; var matchedIonDic2 = psmParentsForDraw.BetaPsmCross.MatchedIonInfo; PlotModel model = new PlotModel { Title = "Spectrum anotation of Scan " + scanNum + " for Crosslinked Peptide", DefaultFontSize = 15 }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "m/z", Minimum = 0, Maximum = x.Max() * 1.02, AbsoluteMinimum = 0 }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "Intensity(counts)", Minimum = 0, Maximum = y.Max() * 1.2, AbsoluteMinimum = 0 }); var textAnnoSeq1 = new TextAnnotation() { }; //textAnnoSeq1.TextRotation=90; textAnnoSeq1.FontSize = 12; textAnnoSeq1.TextColor = OxyColors.Red; textAnnoSeq1.StrokeThickness = 0; textAnnoSeq1.TextPosition = new DataPoint(x.Max() / 2, y.Max() * 1.15); textAnnoSeq1.Text = sequence1; var textAnnoSeq2 = new TextAnnotation() { }; //textAnnoSeq2.TextRotation=90; textAnnoSeq2.FontSize = 12; textAnnoSeq2.TextColor = OxyColors.Blue; textAnnoSeq2.StrokeThickness = 0; textAnnoSeq2.TextPosition = new DataPoint(x.Max() / 2, y.Max() * 1.1); textAnnoSeq2.Text = sequence2; model.Annotations.Add(textAnnoSeq1); model.Annotations.Add(textAnnoSeq2); LineSeries[] s0 = new LineSeries[x.Length]; LineSeries[] s1 = new LineSeries[x.Length]; LineSeries[] s2 = new LineSeries[x.Length]; //Draw the ms/ms scan peaks for (int i = 0; i < x.Length; i++) { s0[i] = new LineSeries(); s0[i].Color = OxyColors.DimGray; s0[i].StrokeThickness = STROKE_THICKNESS_UNANNOTATED; s0[i].Points.Add(new DataPoint(x[i], 0)); s0[i].Points.Add(new DataPoint(x[i], y[i])); model.Series.Add(s0[i]); } //Draw the ms/ms scan matched peaks for (int i = 0; i < matchedIonDic1.MatchedIonMz.Length; i++) { OxyColor ionColor = OxyColors.Red; if (matchedIonDic1.MatchedIonMz[i] > 0) { s1[i] = new LineSeries(); s1[i].Color = ionColor; s1[i].StrokeThickness = STROKE_THICKNESS_ANNOTATED; s1[i].Points.Add(new DataPoint(matchedIonDic1.MatchedIonMz[i] + 1.007277, 0)); s1[i].Points.Add(new DataPoint(matchedIonDic1.MatchedIonMz[i] + 1.007277, matchedIonDic1.MatchedIonIntensity[i])); var textAnno1 = new TextAnnotation(); //textAnno1.TextRotation=90; textAnno1.FontSize = 12; textAnno1.TextColor = ionColor; textAnno1.StrokeThickness = 0; textAnno1.TextPosition = s1[i].Points[1]; textAnno1.Text = matchedIonDic1.MatchedIonMz[i].ToString("f3"); var textAnno2 = new TextAnnotation(); //textAnno2.TextRotation=90; textAnno2.FontSize = 12; textAnno2.TextColor = ionColor; textAnno2.StrokeThickness = 0; textAnno2.TextPosition = new DataPoint(s1[i].Points[1].X, s1[i].Points[1].Y + y.Max() * 0.02); textAnno2.Text = matchedIonDic1.MatchedIonName[i]; model.Annotations.Add(textAnno1); model.Annotations.Add(textAnno2); model.Series.Add(s1[i]); } } for (int i = 0; i < matchedIonDic2.MatchedIonMz.Length; i++) { OxyColor ionColor = OxyColors.Blue; if (matchedIonDic2.MatchedIonMz[i] > 0) { s2[i] = new LineSeries(); s2[i].Color = ionColor; s2[i].StrokeThickness = STROKE_THICKNESS_ANNOTATED; s2[i].Points.Add(new DataPoint(matchedIonDic2.MatchedIonMz[i] + 1.007277, 0)); s2[i].Points.Add(new DataPoint(matchedIonDic2.MatchedIonMz[i] + 1.007277, matchedIonDic2.MatchedIonIntensity[i])); var textAnno1 = new TextAnnotation(); //textAnno1.TextRotation=90; textAnno1.FontSize = 12; textAnno1.TextColor = ionColor; textAnno1.StrokeThickness = 0; textAnno1.TextPosition = s2[i].Points[1]; textAnno1.Text = matchedIonDic2.MatchedIonMz[i].ToString("f3"); var textAnno2 = new TextAnnotation(); //textAnno2.TextRotation=90; textAnno2.FontSize = 12; textAnno2.TextColor = ionColor; textAnno2.StrokeThickness = 0; textAnno2.TextPosition = new DataPoint(s2[i].Points[1].X, s2[i].Points[1].Y + y.Max() * 0.02); textAnno2.Text = matchedIonDic2.MatchedIonName[i]; model.Annotations.Add(textAnno1); model.Annotations.Add(textAnno2); model.Series.Add(s2[i]); } } using (var stream = File.Create(OutputFolder + "\\" + order.ToString() + "_Scan" + scanNum + ".pdf")) { PdfExporter pdf = new PdfExporter { Width = 500, Height = 210 }; pdf.Export(model, stream); } }
/// <summary> /// Plots average fitness graph to pdf in defalut directory /// </summary> /// <param name="Data"> List of lists of every creatures' fitness in given generation</param> public void AverageFitnessPerGeneration(List <List <float> > Data) { #region Functions /// Licz średnią double CalculateAverage(List <float> generation) { float sum = 0f; foreach (float fitness in generation) { sum += fitness; } return((double)(sum / generation.Count)); } ///funkcja tworząca szereg funkcyjny funkcji avg(x) FunctionSeries functionSeries(List <List <float> > list) { int Length = list.Count; FunctionSeries function = new FunctionSeries(); for (int x = 0; x < Length; x++) { for (int y = 0; y < Length; y++) { DataPoint point = new DataPoint(x, CalculateAverage(list[x])); function.Points.Add(point); } } return(function); } #endregion /// Tworzenie Osi wykresu LinearAxis linearAxisX = new LinearAxis { Title = "Generation Number", Position = AxisPosition.Bottom, Minimum = 0, Maximum = 300, MajorGridlineStyle = LineStyle.Dot, MajorGridlineColor = OxyColor.FromRgb(128, 128, 128) }; LinearAxis linearAxisY = new LinearAxis { Title = "Average Fitness", Position = AxisPosition.Left, MajorGridlineStyle = LineStyle.Dot, MajorGridlineColor = OxyColor.FromRgb(128, 128, 128) }; PlotModel PM = new PlotModel(); PM.Axes.Add(linearAxisX); PM.Axes.Add(linearAxisY); PM.Series.Add(functionSeries(Data)); /// Przykład z dokumentacji OxyPlot na Tworzenie pdf /// TODO: Dynamiczna nazwa PDFu, inne formatowanie? using (var stream = File.Create("LatestAvgFit.pdf")) { var pdfExporter2 = new PdfExporter { Width = 600, Height = 400 }; pdfExporter2.Export(PM, stream); } }
/*Задача 17. Пуассоновские потоки частиц из двух источников сначала соединяются в один поток, * в котором частицы нумеруются в порядке поступления.Затем этот поток разделяется на два таким образом, * что первый поток состоит из четных частиц, а второй из нечетных. * Построить функцию распределения и функцию плотности распределения длительности * интервала времени между двумя частицами первого потока на основании 1000 выборочных значений уже разделенного потока.*/ static void Main(string[] args) { //общий поток, ключ -- номер Dictionary <int, double> stream = new Dictionary <int, double>(); //лямбда -- значение double val = 0.1; for (int i = 1; i <= 1000; i++) { stream.Add(i, val); val += 0.000001; } //два потока для чётных и не //деление по номеру Dictionary <int, double> firstStream = new Dictionary <int, double>(); Dictionary <int, double> secondStream = new Dictionary <int, double>(); foreach (var particle in stream) { if (particle.Key % 2 == 0) { firstStream.Add(particle.Key, particle.Value); } else { secondStream.Add(particle.Key, particle.Value); } } //сами значения //цикл с 1 до 500 -- время //флаг для определения потока: чёт или не //вычисление значений для графиков int time = 1; IList <DataPoint> dataDensity = new List <DataPoint>(); IList <DataPoint> dataDistribution = new List <DataPoint>(); bool flagUseFirstStream = false; while (time <= 500) { if (flagUseFirstStream) { double point = firstStream[time] * Math.Pow(2.7, -(firstStream[time] * time)); dataDensity.Add(new DataPoint(time, point)); point = 1 - Math.Exp(-firstStream[time] * time); dataDistribution.Add(new DataPoint(time, point)); } else { double point = secondStream[time] * Math.Pow(2.7, -(secondStream[time] * time)); dataDensity.Add(new DataPoint(time, point)); point = 1 - Math.Exp(-secondStream[time] * time); dataDistribution.Add(new DataPoint(time, point)); } flagUseFirstStream = !flagUseFirstStream; time++; } var model = new PlotModel { Title = "Graph", DefaultFont = "Arial" }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left }); var areaSeries = new AreaSeries(); areaSeries.Points.AddRange(dataDensity); model.Series.Add(areaSeries); //график // х -- время // у -- лямбда от времени //плотность var exporter = new PdfExporter { Width = 400, Height = 400 }; using (var streamGraph = File.Create("density.pdf")) { exporter.Export(model, streamGraph); } var modelDistribution = new PlotModel { Title = "Graph", DefaultFont = "Arial" }; modelDistribution.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom }); modelDistribution.Axes.Add(new LinearAxis { Position = AxisPosition.Left }); var areaSeriesDistribution = new AreaSeries(); areaSeriesDistribution.Points.AddRange(dataDistribution); modelDistribution.Series.Add(areaSeriesDistribution); //распр var exporterDistribution = new PdfExporter { Width = 400, Height = 400 }; using (var streamGraph = File.Create("distribution.pdf")) { exporterDistribution.Export(modelDistribution, streamGraph); } }
public static void Plot(string inputFilename) { var sizeData = new List <double>(); var timeData = new List <double>(); var errorData = new List <double>(); using (var reader = new StreamReader(inputFilename)) { reader.ReadLine(); while (!reader.EndOfStream) { var row = reader.ReadLine(); var cells = row.Split(','); sizeData.Add(Convert.ToDouble(cells[1])); timeData.Add(Convert.ToDouble(cells[2])); errorData.Add(Convert.ToDouble(cells[3])); } } for (var i = 0; i < 2; i++) { var title = i == 0 ? "Time" : "Error"; var data = i == 0 ? timeData : errorData; var model = new PlotModel { Title = $"{inputFilename.Replace('_', ' ').Replace(".csv", "")} {title.ToLower()} plot" }; model.Axes.Add(new LinearAxis { Title = "Size", Position = AxisPosition.Bottom, Minimum = 0, Maximum = sizeData.Last() + 1 }); model.Axes.Add(new LinearAxis { Title = title, Position = AxisPosition.Left, Minimum = 0, Maximum = data.Max() + data.Max() / 10 }); var lineSeries = new LineSeries(); for (var j = 0; j < sizeData.Count; j++) { lineSeries.Points.Add(new DataPoint(sizeData[j], data[j])); } model.Series.Add(lineSeries); using (var stream = File.Create($"{inputFilename}_{title}Plot.pdf")) { var pdfExporter = new PdfExporter { Width = 600, Height = 400 }; pdfExporter.Export(model, stream); } } }
// [ref] ${OxyPlot_HOME}/NET45/Examples/ExampleBrowser/ExampleBrowser.exe. static void runMarketTypes() { var plotModel = new PlotModel(); plotModel.Title = "Marker types"; var linearAxis1 = new LinearAxis(); linearAxis1.Position = AxisPosition.Bottom; plotModel.Axes.Add(linearAxis1); var linearAxis2 = new LinearAxis(); plotModel.Axes.Add(linearAxis2); var lineSeries1 = new LineSeries(); lineSeries1.MarkerStroke = OxyColors.Black; lineSeries1.MarkerType = MarkerType.Circle; lineSeries1.Title = "Circle"; lineSeries1.Points.Add(new DataPoint(11.8621869598805, 1.4144100893356)); lineSeries1.Points.Add(new DataPoint(18.1636718735861, 3.34725344383496)); lineSeries1.Points.Add(new DataPoint(26.1161091961507, 5.10126935043431)); lineSeries1.Points.Add(new DataPoint(29.99451482482, 6.99704349646207)); lineSeries1.Points.Add(new DataPoint(41.9055463103138, 8.21414295500803)); lineSeries1.Points.Add(new DataPoint(48.6674896314123, 9.55912132400978)); lineSeries1.Points.Add(new DataPoint(56.0143694207139, 10.8773872386093)); lineSeries1.Points.Add(new DataPoint(67.4011132397694, 12.2735980540857)); lineSeries1.Points.Add(new DataPoint(74.2207925069243, 13.5990719658318)); lineSeries1.Points.Add(new DataPoint(78.4307891402537, 14.9570749639334)); plotModel.Series.Add(lineSeries1); var lineSeries2 = new LineSeries(); lineSeries2.MarkerStroke = OxyColors.Black; lineSeries2.MarkerType = MarkerType.Cross; lineSeries2.Title = "Cross"; lineSeries2.Points.Add(new DataPoint(10.2551460425626, 1.12034707615168)); lineSeries2.Points.Add(new DataPoint(17.2749783542356, 2.66979351810636)); lineSeries2.Points.Add(new DataPoint(21.436097549012, 4.12809186853845)); lineSeries2.Points.Add(new DataPoint(30.78668166268, 5.20108992848596)); lineSeries2.Points.Add(new DataPoint(33.2050538869598, 6.637421580794)); lineSeries2.Points.Add(new DataPoint(45.0304378052384, 7.66540479830718)); lineSeries2.Points.Add(new DataPoint(56.7345610422709, 9.54063240976102)); lineSeries2.Points.Add(new DataPoint(66.1928816270981, 10.7854569441571)); lineSeries2.Points.Add(new DataPoint(74.2900140398601, 12.665478166037)); lineSeries2.Points.Add(new DataPoint(79.0780252865879, 13.7934278663217)); plotModel.Series.Add(lineSeries2); var lineSeries3 = new LineSeries(); lineSeries3.MarkerStroke = OxyColors.Black; lineSeries3.MarkerType = MarkerType.Diamond; lineSeries3.Title = "Diamond"; lineSeries3.Points.Add(new DataPoint(8.23705901030314, 1.04818704773122)); lineSeries3.Points.Add(new DataPoint(15.3159614062477, 2.61679908755086)); lineSeries3.Points.Add(new DataPoint(26.0893045543178, 3.88729132986036)); lineSeries3.Points.Add(new DataPoint(30.3871664714008, 5.60047892089955)); lineSeries3.Points.Add(new DataPoint(42.2880761336014, 6.83121995620021)); lineSeries3.Points.Add(new DataPoint(45.5782417531955, 8.70534298555243)); lineSeries3.Points.Add(new DataPoint(53.6039859063942, 9.76094881480604)); lineSeries3.Points.Add(new DataPoint(63.170427156226, 11.6268204346424)); lineSeries3.Points.Add(new DataPoint(74.2946957379089, 13.5075224840583)); lineSeries3.Points.Add(new DataPoint(83.4620100881262, 14.6444678658827)); plotModel.Series.Add(lineSeries3); var lineSeries4 = new LineSeries(); lineSeries4.MarkerStroke = OxyColors.Black; lineSeries4.MarkerType = MarkerType.Plus; lineSeries4.Title = "Plus"; lineSeries4.Points.Add(new DataPoint(2.18957495232559, 1.11484250291942)); lineSeries4.Points.Add(new DataPoint(12.7289441883233, 2.66961399916076)); lineSeries4.Points.Add(new DataPoint(17.0745548555043, 4.11782511375743)); lineSeries4.Points.Add(new DataPoint(22.8202153084894, 5.77728548123375)); lineSeries4.Points.Add(new DataPoint(30.5445538696575, 7.4711353287432)); lineSeries4.Points.Add(new DataPoint(40.409529611659, 9.07308203357881)); lineSeries4.Points.Add(new DataPoint(42.8762574823928, 10.166131996627)); lineSeries4.Points.Add(new DataPoint(52.219228453105, 11.9434595531521)); lineSeries4.Points.Add(new DataPoint(60.3437968186772, 13.8768307444997)); lineSeries4.Points.Add(new DataPoint(69.0649180901539, 15.8224504216679)); plotModel.Series.Add(lineSeries4); var lineSeries5 = new LineSeries(); lineSeries5.MarkerStroke = OxyColors.Black; lineSeries5.MarkerType = MarkerType.Square; lineSeries5.Title = "Square"; lineSeries5.Points.Add(new DataPoint(4.28512158723787, 1.0218708203276)); lineSeries5.Points.Add(new DataPoint(7.11419252451239, 2.83296700745493)); lineSeries5.Points.Add(new DataPoint(12.1873434279986, 3.94138236993057)); lineSeries5.Points.Add(new DataPoint(18.4414314499318, 5.85618886438021)); lineSeries5.Points.Add(new DataPoint(21.6272663146384, 7.73614930302657)); lineSeries5.Points.Add(new DataPoint(26.9512430769164, 9.46516049488688)); lineSeries5.Points.Add(new DataPoint(30.584140945498, 10.6070162377353)); lineSeries5.Points.Add(new DataPoint(33.6740629960196, 12.1158796358462)); lineSeries5.Points.Add(new DataPoint(37.6165642373341, 14.0689983791993)); lineSeries5.Points.Add(new DataPoint(42.9570739683495, 15.4981215794096)); plotModel.Series.Add(lineSeries5); var lineSeries6 = new LineSeries(); lineSeries6.MarkerStroke = OxyColors.Black; lineSeries6.MarkerType = MarkerType.Star; lineSeries6.Title = "Star"; lineSeries6.Points.Add(new DataPoint(10.9592619701099, 1.57032582423199)); lineSeries6.Points.Add(new DataPoint(14.3667993193338, 2.86656694294259)); lineSeries6.Points.Add(new DataPoint(20.8092339303387, 4.3936368000664)); lineSeries6.Points.Add(new DataPoint(31.0837363531272, 5.90316125233805)); lineSeries6.Points.Add(new DataPoint(36.2968236749511, 7.88247782079618)); lineSeries6.Points.Add(new DataPoint(40.8309715077425, 9.86153348761682)); lineSeries6.Points.Add(new DataPoint(44.9168707304247, 11.6326452454704)); lineSeries6.Points.Add(new DataPoint(56.0012029614305, 13.6297319203754)); lineSeries6.Points.Add(new DataPoint(58.3205570533502, 14.6725726568478)); lineSeries6.Points.Add(new DataPoint(62.7951211122773, 15.7987183610903)); plotModel.Series.Add(lineSeries6); var lineSeries7 = new LineSeries(); lineSeries7.MarkerStroke = OxyColors.Black; lineSeries7.MarkerType = MarkerType.Triangle; lineSeries7.Title = "Triangle"; lineSeries7.Points.Add(new DataPoint(2.2280231240336, 1.45975955084886)); lineSeries7.Points.Add(new DataPoint(9.6367919340901, 3.15223296831932)); lineSeries7.Points.Add(new DataPoint(15.2513136469067, 4.20971935065916)); lineSeries7.Points.Add(new DataPoint(21.6378828266812, 6.11453639488413)); lineSeries7.Points.Add(new DataPoint(33.4784604066417, 7.33997009384445)); lineSeries7.Points.Add(new DataPoint(41.3092347305777, 8.99930818704856)); lineSeries7.Points.Add(new DataPoint(49.3024369130388, 10.2422971139859)); lineSeries7.Points.Add(new DataPoint(51.7993717146103, 11.9004834484777)); lineSeries7.Points.Add(new DataPoint(62.6105425686625, 13.6871494234945)); lineSeries7.Points.Add(new DataPoint(68.2790698289308, 15.4673946567194)); plotModel.Series.Add(lineSeries7); // #if false String output_filename = "../data/visualization/oxyplot/lineseries_marker_type.png"; using (var stream = File.Create(output_filename)) { System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke( System.Windows.Threading.DispatcherPriority.Normal, new Action( delegate { OxyPlot.Wpf.PngExporter.Export(plotModel, stream, 600, 400, OxyColors.White); // run-time error. } ) ); } #elif true String output_filename = "../data/visualization/oxyplot/lineseries_marker_type.pdf"; using (var stream = File.Create(output_filename)) { PdfExporter.Export(plotModel, stream, 600, 400); } #elif true // Copy to clipboard. using (var stream = new MemoryStream()) { OxyPlot.Wpf.PngExporter.Export(plotModel, stream, 600, 400, OxyColors.White); // run-time error. } #endif }
private void exportButton_Click(object sender, EventArgs e) { if (exportHeightValue.BackColor == Color.Red) { const string message = "Please choose an integer value for the export height."; const string caption = "Error"; var result = MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (exportWidthValue.BackColor == Color.Red) { const string message = "Please choose an integer value for the export width."; const string caption = "Error"; var result = MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (exportAsComboBox.Text == "SVG") { SaveFileDialog saveParameters = new SaveFileDialog(); saveParameters.Filter = ".svg files|*.svg"; saveParameters.Title = "Export figure as .svg"; if (saveParameters.ShowDialog() == DialogResult.Cancel) { return; } using (var stream = File.Create(saveParameters.FileName)) { var exporter = new SvgExporter { Width = Convert.ToInt32(exportWidthValue.Text.ToString()), Height = Convert.ToInt32(exportHeightValue.Text.ToString()) }; exporter.Export(plotViewMassSpectrum.Model, stream); } } else if (exportAsComboBox.Text == "PDF") { SaveFileDialog saveParameters = new SaveFileDialog(); saveParameters.Filter = ".pdf files|*.pdf"; saveParameters.Title = "Export figure as .pdf"; if (saveParameters.ShowDialog() == DialogResult.Cancel) { return; } using (var stream = File.Create(saveParameters.FileName)) { var exporter = new PdfExporter { Width = Convert.ToInt32(exportWidthValue.Text.ToString()), Height = Convert.ToInt32(exportHeightValue.Text.ToString()) }; exporter.Export(plotViewMassSpectrum.Model, stream); } } else if (exportAsComboBox.Text == "PNG") { SaveFileDialog saveParameters = new SaveFileDialog(); saveParameters.Filter = "PNG files|*.png"; saveParameters.Title = "Export figure as .png"; if (saveParameters.ShowDialog() == DialogResult.Cancel) { return; } using (var stream = File.Create(saveParameters.FileName)) { var exporter = new OxyPlot.WindowsForms.PngExporter { Width = Convert.ToInt32(exportWidthValue.Text.ToString()), Height = Convert.ToInt32(exportHeightValue.Text.ToString()) }; exporter.Export(plotViewMassSpectrum.Model, stream); } } }
///<summary> /// Create and run a Fleet MSO that attempts to find the optimum fleet composition to raid this defense ///</summary> static Defense Solve() { Random rand = new Random(0); DefenseSwarm[] defenseSwarms = new DefenseSwarm[NumSwarms]; for (int i = 0; i < NumSwarms; i++) { defenseSwarms[i] = new DefenseSwarm(); } Defense gBestDefense = new Defense(); double gBestError = double.MaxValue; for (int i = 0; i < NumSwarms; ++i) { if (defenseSwarms[i].lBestError < gBestError) { gBestError = defenseSwarms[i].lBestError; gBestDefense.CopyDefense(defenseSwarms[i].lBestDefense); } } var gBestList = new List <(int, double)> { (-1, gBestError) }; int epoch = 0; while (epoch < MaxEpochsOuter) { ++epoch; if (epoch < MaxEpochsOuter) { Console.WriteLine("Outer Epoch " + epoch + ", gBestError " + gBestError.ToString("F1")); } for (int i = 0; i < NumSwarms; ++i) // each swarm { // Shuffle(sequence, rand); // move particles in random sequence for (int j = 0; j < NumParticles; ++j) // each particle { //Death double p1 = rand.NextDouble(); if (defenseSwarms[i].defenseParticles[j].consecutiveNonImproves * p1 > 20) { defenseSwarms[i].defenseParticles[j] = new DefenseParticle(); // new random position if (defenseSwarms[i].defenseParticles[j].error < defenseSwarms[i].lBestError) // new swarm best by luck? { defenseSwarms[i].lBestError = defenseSwarms[i].defenseParticles[j].error; defenseSwarms[i].lBestDefense.CopyDefense(defenseSwarms[i].defenseParticles[j].defense); if (defenseSwarms[i].defenseParticles[j].error < gBestError) // if a new swarm best, maybe also a new global best? { //must repeat defense evaluation to avoid outlier skewing results double result1 = defenseSwarms[i].defenseParticles[j].error; double result2 = defenseSwarms[i].defenseParticles[j].EvaluateDefense(); double result3 = defenseSwarms[i].defenseParticles[j].EvaluateDefense(); double maxResult = new[] { result1, result2, result3 }.Max(); if (maxResult < gBestError) { gBestError = maxResult; gBestDefense.CopyDefense(defenseSwarms[i].defenseParticles[j].defense); } } } } //Immigration double p2 = rand.NextDouble(); if (p2 < ProbImmigrate) { int otherSwarm = rand.Next(0, NumSwarms); int otherParticle = rand.Next(0, NumParticles); DefenseParticle tmp = defenseSwarms[i].defenseParticles[j]; defenseSwarms[i].defenseParticles[j] = defenseSwarms[otherSwarm].defenseParticles[otherParticle]; defenseSwarms[otherSwarm].defenseParticles[otherParticle] = tmp; if (defenseSwarms[i].defenseParticles[j].pBestError < defenseSwarms[otherSwarm].lBestError) // new (other) swarm best? { defenseSwarms[otherSwarm].lBestError = defenseSwarms[i].defenseParticles[j].pBestError; defenseSwarms[otherSwarm].lBestDefense.CopyDefense(defenseSwarms[i].defenseParticles[j].defense); } if (defenseSwarms[otherSwarm].defenseParticles[otherParticle].pBestError < defenseSwarms[i].lBestError) // new (curr) swarm best? { defenseSwarms[i].lBestError = defenseSwarms[otherSwarm].defenseParticles[otherParticle].pBestError; defenseSwarms[i].lBestDefense.CopyDefense(defenseSwarms[otherSwarm].defenseParticles[otherParticle].defense); } // not possible for a new global best } for (int k = 0; k < DefenseDims; ++k) // update velocity. each x position component { double r1 = rand.NextDouble(); double r2 = rand.NextDouble(); double r3 = rand.NextDouble(); defenseSwarms[i].defenseParticles[j].velocity[k] = ( (Inertia * defenseSwarms[i].defenseParticles[j].velocity[k]) + (GravityLocal * r1 * (defenseSwarms[i].defenseParticles[j].pBestDefense.DefenseCounts[k] - defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k]) ) + (GravitySwarm * r2 * (defenseSwarms[i].lBestDefense.DefenseCounts[k] - defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k]) ) + (GravityGlobal * r3 * (gBestDefense.DefenseCounts[k] - defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k]) ) ); //constrain velocities //if (defenseSwarms[i].defenseParticles[j].velocity[k] < minX) // defenseSwarms[i].defenseParticles[j].velocity[k] = minX; //else if (defenseSwarms[i].defenseParticles[j].velocity[k] > maxX) // defenseSwarms[i].defenseParticles[j].velocity[k] = maxX; } for (int k = 0; k < DefenseDims; ++k) // update position { defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k] += (int)defenseSwarms[i].defenseParticles[j].velocity[k]; // constrain all xi if (defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k] < 0 || defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k] > DefenseUnitsMaximums[k]) { defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k] = (int)(rand.NextDouble() * DefenseUnitsMaximums[k]); } } // update error defenseSwarms[i].defenseParticles[j].EvaluateDefense(); // check if new best error for this particle if (defenseSwarms[i].defenseParticles[j].error < defenseSwarms[i].defenseParticles[j].pBestError) { defenseSwarms[i].defenseParticles[j].pBestError = defenseSwarms[i].defenseParticles[j].error; defenseSwarms[i].defenseParticles[j].pBestDefense.CopyDefense(defenseSwarms[i].defenseParticles[j].defense); if (defenseSwarms[i].defenseParticles[j].error < defenseSwarms[i].lBestError) // new swarm best? { defenseSwarms[i].lBestError = defenseSwarms[i].defenseParticles[j].error; defenseSwarms[i].lBestDefense.CopyDefense(defenseSwarms[i].defenseParticles[j].defense); if (defenseSwarms[i].defenseParticles[j].error < gBestError) // new global best? { //must repeat defense evaluation to avoid outlier skewing results double result1 = defenseSwarms[i].defenseParticles[j].error; double result2 = defenseSwarms[i].defenseParticles[j].EvaluateDefense(); double result3 = defenseSwarms[i].defenseParticles[j].EvaluateDefense(); double maxResult = new[] { result1, result2, result3 }.Max(); if (maxResult < gBestError) { gBestError = maxResult; gBestDefense.CopyDefense(defenseSwarms[i].defenseParticles[j].defense); gBestList.Add((epoch, gBestError)); } } } } } // each particle } // each swarm } // while string defenseStr = String.Join(", ", gBestDefense.DefenseCounts); Console.WriteLine("\n****Best defense found: " + defenseStr + " ****"); var pm = new PlotModel { Title = "DefenseMSO", PlotAreaBorderThickness = new OxyThickness(0) }; var categoryAxis = new OxyPlot.Axes.CategoryAxis { AxislineStyle = LineStyle.Solid, TickStyle = TickStyle.None }; var value = new List <DataPoint>(); for (int i = 0; i < gBestList.Count; i++) { value.Add(new DataPoint(gBestList[i].Item1, gBestList[i].Item2)); } pm.Axes.Add ( new OxyPlot.Axes.LinearAxis { Position = AxisPosition.Left, Minimum = -Math.Abs(gBestList[0].Item2), Maximum = 1.05 * Math.Abs(gBestList[gBestList.Count - 1].Item2), MajorStep = Math.Abs(gBestList[0].Item2 / 10), MinorStep = Math.Abs(gBestList[0].Item2 / 50), AxislineStyle = LineStyle.Solid, TickStyle = TickStyle.Crossing, StringFormat = "0,0" } ); pm.Axes.Add ( new OxyPlot.Axes.LinearAxis { Position = AxisPosition.Bottom, Minimum = -1, Maximum = MaxEpochsOuter, MajorStep = Program.MaxEpochsInner / 5, MinorStep = Program.MaxEpochsInner / 20, AxislineStyle = LineStyle.Solid, TickStyle = TickStyle.Outside } ); pm.Series.Add ( new OxyPlot.Series.ScatterSeries { ItemsSource = value, MarkerType = MarkerType.Circle, MarkerSize = 3.0, MarkerFill = OxyColors.White, MarkerStroke = OxyColors.Black, DataFieldX = "X", DataFieldY = "Y" } ); Stream stream = File.Create("C:\\Users\\admin\\source\\repos\\SpeedSimML\\SpeedSimML\\defenseplot.pdf"); var pdf = new PdfExporter(); PdfExporter.Export(pm, stream, 400.0, 400); return(gBestDefense); }
/// <summary> /// "helper" funtion to generate CDF,PDF and histogram for a list. /// </summary> public void CDFPDF(List <double> source, string filename) { Operations functions = new Operations(); int count = 0; PlotModel graf = new PlotModel { Title = "Histogram " + filename }; PlotModel graf_cdf = new PlotModel { Title = "CDF " + filename }; PlotModel graf_pdf = new PlotModel { Title = "PDF " + filename }; List <double> workData = new List <double>(); foreach (var petal in source) { workData.Add(petal); } workData.Sort(); double[] values = workData.ToArray(); var bucketeer = new Dictionary <double, double>(); var groups = workData.GroupBy(i => i); List <string> kek = new List <string>(); var overlayData = new LineSeries(); var PDF = new LineSeries(); int z = 0; foreach (var iris in groups) { bucketeer.Add(iris.Key, iris.Count()); kek.Add(iris.Key.ToString()); count = count + iris.Count(); z++; overlayData.Points.Add(new DataPoint(z, count / 1.5)); PDF.Points.Add(new DataPoint(z, functions.PDF(functions.CDF(iris.Key, functions.Average(workData), functions.StandartDeviation(workData))))); } ColumnSeries ColSer = new ColumnSeries(); CategoryAxis Axis = new CategoryAxis(); foreach (var pair in bucketeer.OrderBy(x => x.Key)) { ColSer.Items.Add(new ColumnItem(pair.Value)); } Axis.ItemsSource = kek; CategoryAxis Axis2 = new CategoryAxis(); Axis2.ItemsSource = kek; CategoryAxis Axis3 = new CategoryAxis(); Axis3.ItemsSource = kek; graf.Series.Add(ColSer); graf.Axes.Add(Axis); graf_cdf.Series.Add(overlayData); graf_cdf.Axes.Add(Axis2); graf_pdf.Series.Add(PDF); graf_pdf.Axes.Add(Axis3); using (var stream = File.Create(filename + "_histogram.pdf")) { var pdfExporter = new PdfExporter { Width = 1000, Height = 400 }; pdfExporter.Export(graf, stream); Console.WriteLine("Graph " + filename + "_histogram.pdf" + " generated!"); } using (var stream = File.Create(filename + "_CDF.pdf")) { var pdfExporter = new PdfExporter { Width = 1000, Height = 400 }; pdfExporter.Export(graf_cdf, stream); Console.WriteLine("Graph " + filename + "_CDF.pdf" + " generated!"); } using (var stream = File.Create(filename + "_PDF.pdf")) { var pdfExporter = new PdfExporter { Width = 1000, Height = 400 }; pdfExporter.Export(graf_pdf, stream); Console.WriteLine("Graph " + filename + "_PDF.pdf" + " generated!"); } }
public void ExportPerformanceReportsAsPNG_PDF(List <IEnumerable <SecretSharingBenchmarkReport> > results, List <string> titles, string PlotTitle, bool drawMinusPrimeTime, bool drawElapsedTime, Func <SecretSharingBenchmarkReport, long> selector, string selectorTitle, Func <IEnumerable <long>, double> functionToDraw, string functionTitle, string ExportPNGFileName) { InitializeComponent(); InitPlotView(); var myModel = new PlotModel { Title = string.Format("{0}", PlotTitle) }; myModel.LegendPosition = LegendPosition.TopLeft; int i = 0; if (results == null || results.Count == 0) { return; } double minMs = double.MaxValue; double maxMs = double.MinValue; List <SecretSharingBenchmarkReport> temp = new List <SecretSharingBenchmarkReport>(); var a = results.Select(po => po.ToList()).Aggregate((current, next) => { temp.AddRange(current); temp.AddRange(next); return(temp); }); long minN; long maxN; if (temp.Count > 0) { minN = temp.Min(selector); maxN = temp.Max(selector); } else { minN = results[0].Min(selector); maxN = results[0].Max(selector); } foreach (var reports in results) { double sumPrimeGenTime, rmsPrimeTime = 0.0; LineSeries lineNoPrimeSeries = null; var lineSeries = new LineSeries(titles[i]); lineSeries.MarkerType = MarkerType.Circle; lineSeries.Smooth = true; #if calcPrimeTime if (drawMinusPrimeTime) { sumPrimeGenTime = reports.Select(po => Math.Pow(po.primeGenerationTime, 2.0)).Aggregate((current, next) => current + next); rmsPrimeTime = Math.Sqrt(1.0 / (double)reports.Count() * (sumPrimeGenTime)); lineNoPrimeSeries = new LineSeries(titles[i] + "primeGen:" + rmsPrimeTime.ToString()); } #endif foreach (var report in reports) { // if we have all elapsd ticks we can view the graph as the f(x) that we wish otherwise only totalElapsed is available var ElapsdToDraw = report.ElapsedTicks == null? report.TotalElapsedMilliseconds: functionToDraw(report.ElapsedTicks); if (drawElapsedTime) { maxMs = Math.Max(maxMs, ElapsdToDraw); minMs = Math.Min(minMs, ElapsdToDraw); lineSeries.Points.Add(new DataPoint(selector(report), ElapsdToDraw)); } #if calcPrimeTime if (drawMinusPrimeTime) { //if (report.TotalElapsedMilliseconds - rmsPrimeTime <= 0) throw new Exception("rms is bigger than total elapsed time"); if (report.TotalElapsedMilliseconds - rmsPrimeTime /*report.primeGenerationTime*/ < minMs) { minMs = report.TotalElapsedMilliseconds - rmsPrimeTime /*report.primeGenerationTime*/; } if (report.TotalElapsedMilliseconds - rmsPrimeTime /*report.primeGenerationTime*/ > maxMs) { maxMs = report.TotalElapsedMilliseconds - rmsPrimeTime /* report.primeGenerationTime*/; } lineNoPrimeSeries.Points.Add(new DataPoint(report.n, report.TotalElapsedMilliseconds - rmsPrimeTime /*report.primeGenerationTime*/)); } #endif } if (lineSeries.Points.Count > 0) { myModel.Series.Add(lineSeries); } if (lineNoPrimeSeries != null && lineNoPrimeSeries.Points.Count > 0) { myModel.Series.Add(lineNoPrimeSeries); } i++; } // myModel.Series.Add(new FunctionSeries(nloglogn, 0, 10, 0.1, "N log2(N)")); myModel.Axes.Add(new OxyPlot.Axes.LinearAxis(OxyPlot.Axes.AxisPosition.Bottom, minN, maxN, selectorTitle)); myModel.Axes.Add(new OxyPlot.Axes.LinearAxis(OxyPlot.Axes.AxisPosition.Left, minMs - 3 < 0 ? 0 : minMs - 3, maxMs, functionTitle)); this.plot1.Model = myModel; //if (ExportPdfFileName != null) //{ using (var stream = File.Create(ExportPNGFileName + ".pdf")) { PdfExporter.Export(myModel, stream, 600, 400); } OxyPlot.WindowsForms.PngExporter.Export(myModel, ExportPNGFileName + ".png", 600, 400, Brushes.White); //} }