private void Svg2Png(PlotModel model) { SvgExporter exporter = new SvgExporter { Width = 600, Height = 400 }; var svg = new SkiaSharp.Extended.Svg.SKSvg(); var imgQuality = 80; using (FileStream fs = System.IO.File.Create("temp.svg")) { exporter.Export(model, fs); } using (FileStream png = System.IO.File.Create("img.png")) { var pict = svg.Load("temp.svg"); var dimen = new SKSizeI( (int)Math.Ceiling(pict.CullRect.Width), (int)Math.Ceiling(pict.CullRect.Height) ); var matrix = SKMatrix.MakeScale(1, 1); var img = SKImage.FromPicture(pict, dimen, matrix); // convert to PNG var skdata = img.Encode(SKEncodedImageFormat.Png, imgQuality); skdata.SaveTo(png); } }
public void SaveImage(PlotModel model, string path) { var exporter = new SvgExporter(); var svgData = exporter.ExportToString(model); File.WriteAllText(path, svgData); }
static void VisualizeMulticlassClassification(string algorithmName, IEnumerable <Wine> testData, IEnumerable <WineClassification> predictedData, string savePath) { try { var plot = new PlotModel { Title = "Iris Type Prediction", IsLegendVisible = true }; var types = predictedData.Select(x => x.Predicted_result).Distinct().OrderBy(x => x); foreach (var type in types) { var scatter = new ScatterSeries() { MarkerType = MarkerType.Circle, MarkerStrokeThickness = 2, Title = $"type : {type}" }; var series = predictedData.Where(x => x.Predicted_result == type).Select(p => new ScatterPoint(p.Location[0], p.Location[1])); scatter.Points.AddRange(series); plot.Series.Add(scatter); } plot.DefaultColors = OxyPalettes.HueDistinct(plot.Series.Count).Colors; var exporter = new SvgExporter { Width = 600, Height = 400 }; using (var fs = new FileStream(savePath, FileMode.Create)) { exporter.Export(plot, fs); } Console.WriteLine($"Classification svg generated at {savePath}."); } catch { Console.WriteLine($"Unable to generate visualization for {algorithmName}"); } }
static void VisualizeClustering(IEnumerable <IrisClustering> predictedData, string savePath) { var plot = new PlotModel { Title = "Iris Cluster", IsLegendVisible = true }; var clusters = predictedData.Select(x => x.Predicted_cluster).Distinct().OrderBy(x => x); foreach (var cluster in clusters) { var scatter = new ScatterSeries() { MarkerType = MarkerType.Circle, MarkerStrokeThickness = 2, Title = $"Cluster : {cluster}" }; var series = predictedData.Where(x => x.Predicted_cluster == cluster).Select(p => new ScatterPoint(p.Location[0], p.Location[1])); scatter.Points.AddRange(series); plot.Series.Add(scatter); } plot.DefaultColors = OxyPalettes.HueDistinct(plot.Series.Count).Colors; var exporter = new SvgExporter { Width = 600, Height = 400 }; using (var fs = new FileStream(savePath, FileMode.Create)) { exporter.Export(plot, fs); } Console.WriteLine($"Clustering svg generated at {savePath}."); }
/// <summary> /// Asserts that a plot is equal to the plot stored in the "baseline" folder. /// 1. Renders the plot to file.svg /// 2. If the baseline does not exist, the current plot is copied to the baseline folder. /// 3. Checks that the svg file is equal to a baseline svg. /// </summary> /// <param name="plot">The plot.</param> /// <param name="name">The name of the baseline file.</param> public static void AreEqual(PlotModel plot, string name) { // string name = new System.Diagnostics.StackFrame(1).GetMethod().Name; string path = name + ".svg"; string baseline = @"baseline\" + path; using (var s = File.Create(path)) { SvgExporter.Export(plot, s, 800, 500, false); } if (!Directory.Exists("baseline")) { Directory.CreateDirectory("baseline"); } if (!File.Exists(baseline)) { File.Copy(path, baseline); return; } var baselineSvg = File.ReadAllText(baseline); var actualSvg = File.ReadAllText(path); Assert.IsTrue(string.Equals(baselineSvg, actualSvg), "Actual svg is not equal to baseline (" + Path.GetFullPath(baseline) + ")"); }
public async Task <SessionDetailDTO> Handle(GetSessionDetailByFileIdQuery request, CancellationToken cancellationToken) { var(fileName, fileBytes) = await _sessionService.DownloadAsset(request.FileId); if (fileName.EndsWith(".gz")) { fileBytes = fileBytes.Decompress(); } var session = JsonConvert.DeserializeObject <Session>(Encoding.UTF8.GetString(fileBytes)); var infos = session.Info.GetType().GetProperties().Where(p => p.GetCustomAttributes(false).Any(a => a is DescriptionAttribute)).ToDictionary(p => (p.GetCustomAttributes(false).First(a => a is DescriptionAttribute) as DescriptionAttribute)?.Description, p => Convert.ToString(p.GetValue(session.Info))); var sensorItems = SensorReport.GetReportFromSessionSensorData(session.Runs.Select(r => r.SensorData)).ToArray(); var frametimeStatisticsProviderOptions = new FrametimeStatisticProviderOptions() { MovingAverageWindowSize = 1000, FpsValuesRoundingDigits = 2 }; var plotSettings = new PlotSettings(); var frametimeStatisticProvider = new FrametimeStatisticProvider(frametimeStatisticsProviderOptions); var fpsGraphBuilder = new FpsGraphPlotBuilder(frametimeStatisticsProviderOptions, frametimeStatisticProvider); fpsGraphBuilder.BuildPlotmodel(session, plotSettings, 0, 1000, ERemoveOutlierMethod.None); var frametimeGraphBuilder = new FrametimePlotBuilder(frametimeStatisticsProviderOptions, frametimeStatisticProvider); frametimeGraphBuilder.BuildPlotmodel(session, plotSettings, 0, 1000, ERemoveOutlierMethod.None); var exporter = new SvgExporter { Width = 1000, Height = 400 }; using var frametimeGraphStream = new MemoryStream(); exporter.Export(frametimeGraphBuilder.PlotModel, frametimeGraphStream); using var fpsGraphStream = new MemoryStream(); exporter.Export(fpsGraphBuilder.PlotModel, fpsGraphStream); var frametimes = session.GetFrametimeTimeWindow(0, 1000, frametimeStatisticsProviderOptions, ERemoveOutlierMethod.None); var fpsTresholdsLabels = FrametimeStatisticProvider.FPSTHRESHOLDS.ToArray(); var fpsTresholdsCounts = frametimeStatisticProvider.GetFpsThresholdCounts(frametimes, false).Select(val => (double)val / frametimes.Count()).ToArray(); var fpsTresholdsCountsDictionary = Enumerable.Range(0, fpsTresholdsLabels.Count()).ToDictionary(idx => (int)fpsTresholdsLabels[idx], idx => fpsTresholdsCounts[idx]).Where(kvp => !double.IsNaN(kvp.Value)); var fpsTresholdsTimes = frametimeStatisticProvider.GetFpsThresholdTimes(frametimes, false).Select(val => val / frametimes.Sum()).ToArray(); var fpsTresholdsTimesDictionary = Enumerable.Range(0, fpsTresholdsLabels.Count()).ToDictionary(idx => (int)fpsTresholdsLabels[idx], idx => fpsTresholdsTimes[idx]).Where(kvp => !double.IsNaN(kvp.Value)); var fpsMetricDictionary = Enum.GetValues(typeof(EMetric)).Cast <EMetric>().ToDictionary(metric => metric.GetAttribute <DescriptionAttribute>().Description, metric => frametimeStatisticProvider.GetFpsMetricValue(frametimes, metric)).Where(kvp => !double.IsNaN(kvp.Value)); return(new SessionDetailDTO() { Infos = infos, SensorItems = sensorItems, FpsTresholdsCounts = fpsTresholdsCountsDictionary, FpsTresholdsTimes = fpsTresholdsTimesDictionary, FpsMetric = fpsMetricDictionary, FpsGraph = Encoding.UTF8.GetString(fpsGraphStream.ToArray()), FrametimeGraph = Encoding.UTF8.GetString(frametimeGraphStream.ToArray()) }); }
private static void SaveCustomerSegmentationPlotChart(IEnumerable <ClusteringPrediction> predictions, string plotLocation) { Common.ConsoleHelper.ConsoleWriteHeader("Plot Customer Segmentation"); var plot = new PlotModel { Title = "Customer Segmentation", IsLegendVisible = true }; var clusters = predictions.Select(p => p.SelectedClusterId).Distinct().OrderBy(x => x); foreach (var cluster in clusters) { var scatter = new ScatterSeries { MarkerType = MarkerType.Circle, MarkerStrokeThickness = 2, Title = $"Cluster: {cluster}", RenderInLegend = true }; var series = predictions .Where(p => p.SelectedClusterId == cluster) .Select(p => new ScatterPoint(p.Location[0], p.Location[1])).ToArray(); scatter.Points.AddRange(series); plot.Series.Add(scatter); } plot.DefaultColors = OxyPalettes.HueDistinct(plot.Series.Count).Colors; var exporter = new SvgExporter { Width = 600, Height = 400 }; using (var fs = new System.IO.FileStream(plotLocation, System.IO.FileMode.Create)) { exporter.Export(plot, fs); } Console.WriteLine($"Plot location: {plotLocation}"); }
public void SaveAsSVG() { string filename; try { if (ShowSaveFileDialog("svg", "SVG files|*.svg", out filename)) { //var pngExporter = new OxyPlot.Wpf.PngExporter { Width = (int)Plot.Width, Height = (int)Plot.Height, Background = OxyColors.White }; //OxyPlot.Wpf.SvgExporter.Export(Plot, filename, (int)Plot.Width, (int)Plot.Height, OxyColors.White); using (var stream = File.Create(filename)) { var exporter = new SvgExporter { Width = (int)Plot.Width, Height = (int)Plot.Height }; exporter.Export(Plot, stream); } } } catch (Exception e) { System.Windows.MessageBox.Show(e.Message, "Error"); } }
public void ExportDemoMap() { //var inputWad = @"C:\Games\Doom\IWADS\doom.wad"; var inputWad = @"C:\Games\Doom\levels\10sector.wad"; //var inputWad = @"C:\Users\aramant\Desktop\Doom\freedoom1-udmf.wad"; //var inputWad = @"C:\Users\aramant\Desktop\Doom\10sector-udmf.wad"; var baseOutputPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Doom", "SVGs"); if (!Directory.Exists(baseOutputPath)) { Directory.CreateDirectory(baseOutputPath); } var wadName = Path.GetFileNameWithoutExtension(inputWad); foreach (var(name, map) in WadLoader.Load(inputWad)) { try { SvgExporter.Export(map, Path.Combine(baseOutputPath, $"{wadName}.{name}.svg")); } catch (Exception e) { Console.WriteLine(name + ": " + e); } } }
public void Export_AllExamplesInExampleLibrary_CheckThatAllFilesExist() { const string DestinationDirectory = "SvgExporterTests_ExampleLibrary"; if (!Directory.Exists(DestinationDirectory)) { Directory.CreateDirectory(DestinationDirectory); } foreach (var example in Examples.GetList()) { void ExportModelAndCheckFileExists(PlotModel model, string fileName) { if (model == null) { return; } var path = Path.Combine(DestinationDirectory, FileNameUtilities.CreateValidFileName(fileName, ".svg")); using (var s = File.Create(path)) { SvgExporter.Export(model, s, 800, 500, true); } Assert.IsTrue(File.Exists(path)); } ExportModelAndCheckFileExists(example.PlotModel, $"{example.Category} - {example.Title}"); ExportModelAndCheckFileExists(example.TransposedPlotModel, $"{example.Category} - {example.Title} - Transposed"); } }
public static void Run() { var outputToFile = "test-oxyplot-static-export-file"; var outputExportStreamOOP = "test-oxyplot-export-stream"; var width = 1024; var height = 768; var resolutions = new[] { 72d, 96d, 182d }; var model = HeatMapExample();//BuildPlotModel(); foreach (var resolution in resolutions) { // export using the instance methods using (var stream = new MemoryStream()) { var strPath = $"{outputExportStreamOOP}{resolution}.svg"; var strFull = Path.Combine(Directory.GetCurrentDirectory(), strPath); var jpegExporter = new SvgExporter(); jpegExporter.Export(model, stream); System.IO.File.WriteAllBytes(strFull, stream.ToArray()); Process.Start(@"cmd.exe ", @"/c " + strFull); } } }
/// <summary> /// Writes the plot. /// </summary> /// <param name="plot">The plot.</param> public void WritePlot(PlotFigure plot) { this.WriteStartFigure(); switch (this.PlotElementType) { case HtmlPlotElementType.Embed: case HtmlPlotElementType.Object: // TODO: need a Func<string,Stream> to provide streams for the plot files? ////string source = string.Format( //// "{0}_Plot{1}.svg", Path.GetFileNameWithoutExtension(this.outputFile), plot.FigureNumber); ////plot.PlotModel.SaveSvg(this.GetFullFileName(source), plot.Width, plot.Height, this.textMeasurer); ////this.WriteStartElement(this.PlotElementType == HtmlPlotElementType.Embed ? "embed" : "object"); ////this.WriteAttributeString("src", source); ////this.WriteAttributeString("type", "image/svg+xml"); ////this.WriteEndElement(); break; case HtmlPlotElementType.Svg: this.WriteRaw(SvgExporter.ExportToString(plot.PlotModel, plot.Width, plot.Height, false, this.textMeasurer)); break; } this.WriteEndFigure(plot.FigureText); }
/// <inheritdoc/> void IFileWriter.Save(string path, object item, object options) { if (string.IsNullOrEmpty(path) || item == null) return; var ic = options as IImageCache; if (options == null) return; var renderer = new SkiaRenderer(true, 96.0); renderer.State.DrawShapeState.Flags = ShapeStateFlags.Printable; renderer.State.ImageCache = ic; var presenter = new ExportPresenter(); IProjectExporter exporter = new SvgExporter(renderer, presenter); if (item is XContainer) { exporter.Save(path, item as XContainer); } else if (item is XDocument) { throw new NotSupportedException("Saving documents as svg drawing is not supported."); } else if (item is XProject) { throw new NotSupportedException("Saving projects as svg drawing is not supported."); } }
public static async Task DoWork() { var provider = new ServiceCollection() .AddSingleton <IAmazonCloudWatch>(new AmazonCloudWatchClient(RegionEndpoint.EUWest1)) .AddCloudWatchGraphs() .BuildServiceProvider(); var plotBuilder = provider.GetService <IPlotBuilder>(); var plotModel = await plotBuilder.WithTime(DateTime.UtcNow.AddDays(-12), DateTime.UtcNow) .AddMetric("AWS/Logs", "IncomingBytes") .WithLabel("Average Incoming Bytes") .PlotGraph(GraphType.Line, StatisticType.Average, TimeSpan.FromMinutes(30)) .WithTitle("CloudWatch Logs Incoming Bytes") .Generate(); var svgExporter = new SvgExporter { Width = 750, Height = 300 }; using (var output = File.Open("example.svg", FileMode.Create)) { svgExporter.Export(plotModel, output); } }
public MainViewModel() { _logger.Info("MainViewModel()"); //MyModel = new PlotModel { Title = "Example 1" }; MyModel = new PlotModel(); //var seriesItem = new FunctionSeries(Math.Cos, 0, 10, 0.1, "cos(x)"); //seriesItem.Color = OxyColors.Black; //MyModel.Series.Add(seriesItem); //MyModel.Series.Add(new FunctionSeries(Math.Sin, 0, 10, 0.1, "sin(x)")); //var customSeries = new LineSeries(); //customSeries.Points.Add(new DataPoint(1, 0.5)); //customSeries.Points.Add(new DataPoint(2, 0.5)); //customSeries.Points.Add(new DataPoint(3, 0)); //MyModel.Series.Add(customSeries); //CreateLogicValueCase(); CreateCase1(); var fileName = @"c:\Users\Acer\Documents\GitHub\SymOntoClay\TestSandbox\bin\Debug\net5.0\SFunction.svg"; using (var stream = File.Create(fileName)) { var exporter = new SvgExporter { Width = 600, Height = 400 }; exporter.Export(MyModel, stream); } }
public void Export_AllExamplesInExampleLibrary_CheckThatAllFilesExist() { const string DestinationDirectory = "SvgExporterTests_ExampleLibrary"; if (!Directory.Exists(DestinationDirectory)) { Directory.CreateDirectory(DestinationDirectory); } foreach (var example in Examples.GetList()) { if (example.PlotModel == null) { continue; } var path = Path.Combine(DestinationDirectory, StringHelper.CreateValidFileName(example.Category + " - " + example.Title, ".svg")); using (var s = File.Create(path)) { SvgExporter.Export(example.PlotModel, s, 800, 500, true); } Assert.IsTrue(File.Exists(path)); } }
/// <summary> /// Creates an SVG string. /// </summary> /// <param name="model">The model.</param> /// <param name="width">The width (points).</param> /// <param name="height">The height (points).</param> /// <param name="isDocument">if set to <c>true</c>, the xml headers will be included (?xml and !DOCTYPE).</param> /// <returns>A <see cref="string" />.</returns> public static string ToSvg(this PlotModel model, double width, double height, bool isDocument) { var rc = new GraphicsRenderContext { RendersToScreen = false }; return(SvgExporter.ExportToString(model, width, height, isDocument, rc)); }
Pixbuf Load(PlotModel model, double width, double height) { MemoryStream stream = new MemoryStream(); SvgExporter.Export(model, stream, width, height, false, new PangoTextMeasurer()); stream.Seek(0, SeekOrigin.Begin); return(new Pixbuf(stream)); }
public void Export_SomeExamplesInExampleLibrary_CheckThatAllFilesExist() { var exporter = new SvgExporter { Width = 1000, Height = 750 }; var directory = Path.Combine(this.outputDirectory, "ExampleLibrary"); ExportTest.Export_FirstExampleOfEachExampleGroup_CheckThatAllFilesExist(exporter, directory, ".svg"); }
public void TestMultilineAlignment() { var exporter = new SvgExporter { Width = 1000, Height = 750 }; var model = RenderingCapabilities.DrawMultilineTextAlignmentRotation(); using var stream = File.Create(Path.Combine(this.outputDirectory, "Multiline-Alignment.svg")); exporter.Export(model, stream); }
public void export(string path, int w = 1280, int h = 720) { using (var stream = File.Create(path)) { // Export to svg, store in memory stream var exporter = new SvgExporter { Width = w, Height = h }; exporter.Export(Model, stream); } }
/// <summary> /// Exportar o modelo atual para SVG /// </summary> public void ExportSVG(string path) { using (var stream = File.Create(path)) { var exporter = new SvgExporter { Width = 1920, Height = 1080 }; exporter.Export(model, stream); } }
/// <summary> /// Exports the plot to an .svg file. The resulting .svg files seem to not render properly in Google Chrome, /// but work in Mozilla Firefox, and Microsoft Internet Explorer/Edge. /// </summary> public void ExportToSvg(string path, int width = 800, int height = 600) { using (var s = File.Create(path)) { var svgExporter = new SvgExporter { Width = width, Height = height, UseVerticalTextAlignmentWorkaround = true }; svgExporter.Export(Model, s); } }
private static MemoryStream ExportToStream(PlotModel plot, int horizontalRes, int verticalRes) { var exporter = new SvgExporter { Width = horizontalRes, Height = verticalRes, IsDocument = true }; var memStream = new MemoryStream(); exporter.Export(plot, memStream); return(memStream); }
/// <summary> /// Exports specified model into SVG format. /// </summary> /// <param name="exportFilePath"></param> /// <param name="plotModel"></param> public void ExportPlotModelToSvg(string exportFilePath, PlotModel plotModel) { using (var stream = File.Create($"{exportFilePath}.svg")) { var exporter = new SvgExporter { Width = 600, Height = 600 }; exporter.Export(plotModel, stream); } }
public void ExportToString_TestPlot_ValidSvgString() { var plotModel = new PlotModel("Test plot"); plotModel.Series.Add(new FunctionSeries(Math.Sin, 0, Math.PI * 8, 200, "Math.Sin")); var rc = new ShapesRenderContext(null); var svg = SvgExporter.ExportToString(plotModel, 800, 500, false, rc); SvgAssert.IsValidElement(svg); }
private static void SavePlotToSvg(string filePath, PlotModel plot) { // OxyPlot.Core: Works, but is SVG; PDF should also work from core. using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { var svgExporter = new SvgExporter { Width = ExportImageWidth, Height = ExportImageHeight }; svgExporter.Export(plot, stream); } }
public void ExportToString_TestPlot_ValidSvgString() { var plotModel = new PlotModel { Title = "Test plot" }; plotModel.Series.Add(new FunctionSeries(Math.Sin, 0, Math.PI * 8, 200, "Math.Sin")); var svg = SvgExporter.ExportToString(plotModel, 800, 500, false); SvgAssert.IsValidElement(svg); }
public void BackgroundColor() { var model = ShowCases.CreateNormalDistributionModel(); model.Background = OxyColors.AliceBlue; var exporter = new SvgExporter { Width = 1000, Height = 750 }; using var stream = File.Create(Path.Combine(this.outputDirectory, "Background.svg")); exporter.Export(model, stream); }
public static void Show(string wndTitlle, PlotModel model) { // export using the instance methods using (var stream = new MemoryStream()) { var strPath = $"{Guid.NewGuid().ToString()}.svg"; var strFull = Path.Combine(Directory.GetCurrentDirectory(), strPath); var jpegExporter = new SvgExporter(); jpegExporter.Export(model, stream); System.IO.File.WriteAllBytes(strFull, stream.ToArray()); Process.Start(@"cmd.exe ", @"/c " + strFull); } }
public void Export_TestPlot_ValidSvgString() { var plotModel = new PlotModel("Test plot"); const string FileName = "SvgExporterTests_Plot1.svg"; plotModel.Series.Add(new FunctionSeries(Math.Sin, 0, Math.PI * 8, 200, "Math.Sin")); using (var s = File.Create(FileName)) { var rc = new ShapesRenderContext(null); SvgExporter.Export(plotModel, s, 800, 500, true, rc); } SvgAssert.IsValidFile(FileName); }
/// <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; } }