Ejemplo n.º 1
0
        /// <summary>
        /// plot a 2D grid
        /// </summary>
        public static void Plot2DGrid(this GridCommons grd, params int[] Cells)
        {
            using (var gp = new Gnuplot()) {
                Console.WriteLine("Plotting 2D grid with gnuplot...");

                if (grd.SpatialDimension != 2)
                {
                    throw new NotSupportedException("works only for 2D grid");
                }


                int J = grd.Cells.Length;
                if (Cells == null)
                {
                    Cells = J.ForLoop(j => j);
                }

                foreach (int j in Cells)
                {
                    var Cell_j = grd.Cells[j];
                    //var Kref = grd.RefElements.Single(KK => KK.SupportedCellTypes.Contains(Cell_j.Type));

                    //var Vtx = Kref.Vertices;
                    //var _Vtx = Kref.GetSubDivTree(3).GlobalVertice;
                    //var Vtx = MultidimensionalArray.Create(_Vtx.GetLength(0), _Vtx.GetLength(1));
                    //Vtx.SetA2d(_Vtx);
                    //Vtx.Scale(1);

                    var Vtx_glob = Cell_j.TransformationParams;


                    double[] xNodes = Vtx_glob.ExtractSubArrayShallow(-1, 0).To1DArray();
                    double[] yNodes = Vtx_glob.ExtractSubArrayShallow(-1, 1).To1DArray();
                    double   xC     = xNodes.Sum() / xNodes.Length;
                    double   yC     = yNodes.Sum() / yNodes.Length;
                    for (int k = 0; k < xNodes.Length; k++)
                    {
                        double dx = xNodes[k] - xC;
                        dx       *= 0.95;
                        xNodes[k] = xC + dx;

                        double dy = yNodes[k] - yC;
                        dy       *= 0.95;
                        yNodes[k] = yC + dy;
                    }

                    double hy = yNodes.Max() - yNodes.Min();

                    gp.PlotXY(xNodes, yNodes, title: null, format: (new PlotFormat(Style: Styles.LinesPoints, lineColor: ((LineColors)j))));

                    gp.Cmd("set label \"{0}\" at {2},{3} font \"Arial,5\"", j.ToString(), Cell_j.GlobalID, xC.ToStringDot(), (yC + hy * 0.21).ToStringDot());
                    gp.Cmd("set label \"[{1}]\" at {2},{3} font \"Arial,5\"", j.ToString(), Cell_j.GlobalID, xC.ToStringDot(), (yC - hy * 0.21).ToStringDot());
                }

                gp.Execute();

                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Draws a graph with Gnuplot and saves it as a gif. Subsequently sets Picture of Form to the plot.
        /// </summary>
        private void drawGnuplotGraph()
        {
            using (Gnuplot gp = new Gnuplot()) {
                gp.SetXLabel("Iteration");
                gp.SetYLabel(log.Norm + " Norm");
                gp.Cmd("set title \"Residual Plot\"");
                gp.Cmd("set key outside under horizontal box");
                gp.Cmd("set logscale y");
                gp.Cmd("set format y \"10^{%L}\"");
                gp.Cmd("set grid xtics ytics");

                List <string> KeysToPlot = log.Values.Keys.ToList();
                KeysToPlot.Remove("#Line");
                KeysToPlot.Remove("#Time");
                KeysToPlot.Remove("#Iter");

                for (int i = 0; i < KeysToPlot.Count; i++)
                {
                    gp.PlotXY(log.Values["#Time"], log.Values[KeysToPlot[i]], KeysToPlot[i],
                              new PlotFormat(lineColor: ((LineColors)i), Style: Styles.Lines));
                }

                Image graph = gp.PlotGIF();
                pictureBox1.Image = graph;
                pictureBox1.Refresh();
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Visualizes the stored data using gnuplot.
        /// </summary>
        public void Plot()
        {
            Gnuplot gp = new Gnuplot();

            gp.SetXLabel("x");
            gp.SetYLabel("y");
            gp.Cmd("set terminal wxt noraise");
            if (LogX)
            {
                gp.Cmd("set logscale x");
                gp.Cmd("set format x \"10^{%L}\"");
            }
            if (LogY)
            {
                gp.Cmd("set logscale y");
                gp.Cmd("set format y \"10^{%L}\"");
            }
            gp.Cmd("set grid xtics ytics");

            int lineColor = 0;

            foreach (var group in dataGroups)
            {
                gp.PlotXY(group.Abscissas, group.Values, group.Name,
                          new PlotFormat(lineColor: ((LineColors)(++lineColor)), pointType: ((PointTypes)4), pointSize: 1.5, Style: Styles.LinesPoints));
            }
            gp.Execute();
        }
Ejemplo n.º 4
0
        public string Generate(Gnuplot plot)
        {
            string fileName = Path.GetRandomFileName();
            using (StreamWriter writer = new StreamWriter(Path.Combine(plot.WorkingDirectory.FullName, fileName)))
            {
                // Using a dummy plot function here.
                IPlotFunction function = PlotFunction.Create(x => 0.0);

                foreach (double t in Segment.CreatePoints(function))
                {
                    ISpacePoint c = Curve.Value(t);
                    writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} {1} {2}", c.X, c.Y, c.Z));
                }
                writer.Close();
            }

            // Format specification here:
            // http://www.gnuplot.info/docs_4.2/gnuplot.html#x1-10100034

            return string.Format("'{0}' using 1:2:3 with lines {1} {2} {3}",
                fileName,
                Properties.Axes != null ? "axes " + Properties.Axes.Generate(plot) : "",
                Properties.Label != null ? "title '" + Properties.Label.Generate(plot) + "'" : "notitle",
                Properties.Generate(this, plot));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Plots a line plot from a given residual log.
        /// The y-axis will be scaled logarithmically.
        /// </summary>
        private Image drawGnuplotGraph()
        {
            Image graph;

            using (Gnuplot gp = new Gnuplot()) {
                gp.SetXLabel("Iteration");
                gp.SetYLabel(log.Norm + " Norm");
                //gp.Cmd("set terminal wxt noraise title 'SessionGuid: " + log.SessionGuid.ToString() + "'");
                gp.Cmd("set title " + titleOfPlot);
                gp.Cmd("set key outside under horizontal box");
                gp.Cmd("set logscale y");
                gp.Cmd("set format y \"10^{%L}\"");
                gp.Cmd("set grid xtics ytics");

                List <string> KeysToPlot = log.Values.Keys.ToList();
                KeysToPlot.Remove("#Line");
                KeysToPlot.Remove("#Time");
                KeysToPlot.Remove("#Iter");

                for (int i = 0; i < KeysToPlot.Count; i++)
                {
                    gp.PlotXY(log.Values["#Time"], log.Values[KeysToPlot[i]], KeysToPlot[i],
                              new PlotFormat(lineColor: ((LineColors)i), Style: Styles.Lines));
                }

                graph = gp.PlotGIF();
            }

            return(graph);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Simple plotting interface
        /// </summary>
        /// <returns>Output of <see cref="GnuplotExtensions.PlotNow(Gnuplot)"/></returns>
        static public object Plot(IEnumerable <double> X1, IEnumerable <double> Y1, string Name1 = null, string Format1 = null,
                                  IEnumerable <double> X2 = null, IEnumerable <double> Y2 = null, string Name2 = null, string Format2 = null,
                                  IEnumerable <double> X3 = null, IEnumerable <double> Y3 = null, string Name3 = null, string Format3 = null,
                                  IEnumerable <double> X4 = null, IEnumerable <double> Y4 = null, string Name4 = null, string Format4 = null,
                                  IEnumerable <double> X5 = null, IEnumerable <double> Y5 = null, string Name5 = null, string Format5 = null,
                                  IEnumerable <double> X6 = null, IEnumerable <double> Y6 = null, string Name6 = null, string Format6 = null,
                                  IEnumerable <double> X7 = null, IEnumerable <double> Y7 = null, string Name7 = null, string Format7 = null,
                                  bool logX = false, bool logY = false)
        {
            using (var gp = new Gnuplot()) {
                IEnumerable <double>[] Xs = new[] { X1, X2, X3, X4, X5, X6, X7 };
                IEnumerable <double>[] Ys = new[] { Y1, Y2, Y3, Y4, Y5, Y6, Y7 };
                string[] Ns = new string[] { Name1, Name2, Name3, Name4, Name5, Name6, Name7 };
                string[] Fs = new string[] { Format1, Format2, Format3, Format4, Format5, Format6, Format7 };

                for (int i = 0; i < 7; i++)
                {
                    if (Ys[i] != null)
                    {
                        var f1 = new PlotFormat();
                        if (Fs[i] != null)
                        {
                            f1.FromString(Fs[i]);
                        }
                        gp.PlotXY(Xs[i], Ys[i], title: Ns[i], format: f1, logX: logX, logY: logY);
                    }
                }

                return(gp.PlotNow());
            }
        }
Ejemplo n.º 7
0
        private static void _addTicks(Dictionary <String, double> labelValues, AxisTicks axisTicks)
        {
            List <string> commands = axisTicks.AddTicks(labelValues);

            for (int i = 0; i < commands.Count; i++)
            {
                Gnuplot.WriteCommand(commands[i]);
            }
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Gnuplot plotting, automatic choice of gnuplot driver depending on
 /// the current value of <see cref="UseCairoLatex"/>.
 /// </summary>
 public static object PlotNow(this Gnuplot gp)
 {
     if (UseCairoLatex)
     {
         return(gp.PlotCairolatex());
     }
     else
     {
         return(gp.PlotGIF());
     }
 }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            Gnuplot.Start();
            var x       = Enumerable.Range(-100, 201).Select(z => z * 0.025 * Math.PI).ToArray();
            var sinX    = x.Select(Math.Sin).ToArray();
            var dataSet = new DataSet(x, sinX);

            var(id, fig) = Gnuplot.Plot <Line2D>(dataSet, "First Example: sin(x)");
            Gnuplot.Show();
            Gnuplot.Wait();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Single plot window:
        /// Converts <see cref="Plot2Ddata"/> into an alive Gnuplot object.
        /// </summary>
        public static Gnuplot ToGnuplot(this Plot2Ddata _2DData, GnuplotPageLayout layout = null)
        {
            if (layout != null)
            {
                throw new NotImplementedException("todo");
            }

            Gnuplot gp = new Gnuplot();

            _2DData.ToGnuplot(gp);
            return(gp);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Gnuplot plotting (multiplot), automatic choice of gnuplot driver depending on
 /// the current value of <see cref="UseCairoLatex"/>.
 /// </summary>
 public static object PlotNow(this Plot2Ddata[,] _2DData)
 {
     using (Gnuplot gp = _2DData.ToGnuplot()) {
         if (UseCairoLatex)
         {
             return(gp.PlotCairolatex());
         }
         else
         {
             return(gp.PlotGIF());
         }
     }
 }
Ejemplo n.º 12
0
        async Task WritePltCommands(TextWriter writer, string source, string chart_destination, ChartFormat format)
        {
            var gnuplot = new Gnuplot
            {
                Format      = format,
                Width       = 800,
                Height      = 600,
                FontScale   = 1.2,
                Destination = chart_destination
            };

            gnuplot.DataSeries.Add(new LineChartSeries
            {
                SourceFile = source,
                XColumn    = 1,
                YColumn    = 2,
                Style      = new LineChartSeriesStyle(LineChartStyle.Lines)
                {
                    Style = new LinePointStyle
                    {
                        LineColor = "#FF0000"
                    }
                }
            });

            gnuplot.DataSeries.Add(new LineChartSeries
            {
                SourceFile = source,
                XColumn    = 1,
                YColumn    = 3,
                Style      = new LineChartSeriesStyle(LineChartStyle.Lines)
                {
                    Style = new LinePointStyle
                    {
                        LineColor = "#CC0000"
                    }
                }
            });

            await gnuplot.OutputPltFileAsync(writer);
        }
Ejemplo n.º 13
0
        public string Generate(Gnuplot plot)
        {
            // Many samples here:
            // http://gnuplot.sourceforge.net/demo/contours.html

            /*// Override to align with specified x values for LinearInterpolationSurface.
            if (surface is LinearInterpolationSurface && ((LinearInterpolationSurface)surface).Projection == LinearInterpolationSurfaceProjection.XZPlane)
            {
                xs = ((LinearInterpolationSurface)surface).Values;
            }

            // Or with the specified y values.
            if (surface is LinearInterpolationSurface && ((LinearInterpolationSurface)surface).Projection == LinearInterpolationSurfaceProjection.YZPlane)
            {
                ys = ((LinearInterpolationSurface)surface).Values;
            }*/

            string fileName = Path.GetRandomFileName();
            using (StreamWriter writer = new StreamWriter(Path.Combine(plot.WorkingDirectory.FullName, fileName)))
            {
                // Using a dummy plot function here.
                IPlotFunction function = PlotFunction.Create(x => 0.0);

                foreach (double x in Segment1.CreatePoints(function))
                {
                    foreach (double y in Segment2.CreatePoints(function))
                    {
                        double z = Surface.Value(x, y);
                        writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} {1} {2}", x, y, z));
                    }
                    writer.WriteLine();
                }
                writer.Close();
            }

            return string.Format("'{0}' using 1:2:3 with lines {1} {2} {3}",
                fileName,
                Properties.Axes != null ? "axes " + Properties.Axes.Generate(plot) : "",
                Properties.Label != null ? "title '" + Properties.Label.Generate(plot) + "'" : "notitle",
                Properties.Generate(this, plot));
        }
Ejemplo n.º 14
0
        public string Generate(Gnuplot plot)
        {
            string fileName = Path.GetRandomFileName();
            using (StreamWriter writer = new StreamWriter(Path.Combine(plot.WorkingDirectory.FullName, fileName)))
            {
                foreach (ISpacePoint point in Points)
                {
                    writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} {1} {2}", point.X, point.Y, point.Z));
                }
                writer.Close();
            }

            // Format specification here:
            // http://www.gnuplot.info/docs_4.2/gnuplot.html#x1-10100034

            return string.Format("'{0}' using 1:2:3 {1} {2} {3}",
                fileName,
                Properties.Axes != null ? "axes " + Properties.Axes.Generate(plot) : "",
                Properties.Label != null ? "title '" + Properties.Label.Generate(plot) + "'" : "notitle",
                Properties.Generate(this, plot));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Plot to a gif file ('set terminal gif').
        /// </summary>
        /// <param name="gp"></param>
        /// <param name="xRes">Horizontal resolution in pixels.</param>
        /// <param name="yRes">Vertical resolution in pixels.</param>
        static public Image PlotGIF(this Gnuplot gp, int xRes = 800, int yRes = 600)
        {
            // set terminal
            gp.Terminal = string.Format("pngcairo size {0},{1}", xRes, yRes);

            // set output file
            //string OutfileName = null;
            //while (OutfileName == null || File.Exists(OutfileName)) {
            //    OutfileName = Path.GetTempFileName() + ".gif";
            //}
            string OutfileName = Path.GetTempFileName();

            gp.OutputFile = OutfileName;

            // call gnuplot
            int exCode = gp.RunAndExit(); // run & close gnuplot

            if (exCode != 0)
            {
                Console.WriteLine("Gnuplot-internal error: exit code " + exCode);
                return(null);
            }


            // return image
            var fi = (new FileInfo(OutfileName));

            if (fi.Exists && fi.Length > 0)
            {
                byte[] IOMmem = File.ReadAllBytes(OutfileName);
                File.Delete(OutfileName);
                return(Image.FromStream(new MemoryStream(IOMmem)));
                //return Image.FromFile(OutfileName); // it seems, the image object does not work anymore when the file is deleted
            }
            else
            {
                Console.WriteLine("Gnuplot output file empty or non-existent.");
                return(null);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Multiple plot windows:
        /// Converts <see cref="Plot2Ddata"/> into an alive Gnuplot object.
        /// </summary>
        public static Gnuplot ToGnuplot(this Plot2Ddata[,] _2DData, GnuplotPageLayout layout = null)
        {
            if (layout != null)
            {
                throw new NotImplementedException("todo");
            }
            if (_2DData.GetLowerBound(0) != 0)
            {
                throw new ArgumentException();
            }
            if (_2DData.GetLowerBound(1) != 0)
            {
                throw new ArgumentException();
            }
            if (_2DData.GetLength(0) <= 0)
            {
                throw new ArgumentException();
            }
            if (_2DData.GetLength(1) <= 0)
            {
                throw new ArgumentException();
            }

            Gnuplot gp = new Gnuplot();

            gp.SetMultiplot(_2DData.GetLength(0), _2DData.GetLength(1));

            for (int iRow = 0; iRow < _2DData.GetLength(0); iRow++)
            {
                for (int iCol = 0; iCol < _2DData.GetLength(1); iCol++)
                {
                    if (_2DData[iRow, iCol] != null)
                    {
                        gp.SetSubPlot(iRow, iCol);
                        _2DData[iRow, iCol].ToGnuplot(gp);
                    }
                }
            }
            return(gp);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Plot to a gif file ('set terminal gif').
        /// </summary>
        /// <param name="gp"></param>
        /// <param name="xRes">Horizontal resolution in pixels.</param>
        /// <param name="yRes">Vertical resolution in pixels.</param>
        static public Image PlotGIF(this Gnuplot gp, int xRes = 800, int yRes = 600)
        {
            // set terminal
            gp.Terminal = string.Format("pngcairo size {0},{1}", xRes, yRes);

            // set output file
            //string OutfileName = null;
            //while (OutfileName == null || File.Exists(OutfileName)) {
            //    OutfileName = Path.GetTempFileName() + ".gif";
            //}
            string OutfileName = Path.GetTempFileName();

            gp.OutputFile = OutfileName;

            // call gnuplot
            int exCode = gp.RunAndExit(); // run & close gnuplot

            if (exCode != 0)
            {
                Console.WriteLine("Gnuplot-internal error: exit code " + exCode);
                return(null);
            }


            // return image
            var fi = (new FileInfo(OutfileName));

            if (fi.Exists && fi.Length > 0)
            {
                return(Image.FromFile(OutfileName));
            }
            else
            {
                Console.WriteLine("Gnuplot output file empty or non-existent.");
                return(null);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Utility/Debug function, plots numbers at specific coordinates.
        /// </summary>
        /// <param name="X"></param>
        /// <param name="filename"></param>
        public static void PlotCoordinateLabels(this MultidimensionalArray X, string filename)
        {
            using (var gp = new Gnuplot()) {
                int L = X.NoOfRows;
                if (X.NoOfCols != 2)
                {
                    throw new NotSupportedException("works only for 2D grid");
                }

                gp.Cmd("set terminal png");
                gp.Cmd("set output \"{0}\"", filename);

                gp.SetXRange(-4, 4);
                gp.SetYRange(-4, 4);

                for (int l = 0; l < L; l++)
                {
                    gp.Cmd("set label \"{0}\" at {1},{2}", l, X[l, 0], X[l, 1]);
                }

                gp.PlotSlope(0, 0);
                gp.Execute();
            }
        }
Ejemplo n.º 19
0
 protected override void _setUp()
 {
     Gnuplot.WriteCommand("set style data boxplot");
 }
Ejemplo n.º 20
0
 public void SetPosition(Position position)
 {
     Position = position;
     Gnuplot.WriteCommand(Command);
 }
Ejemplo n.º 21
0
        private void _setRange(double min, double max, AxisRange axisRange)
        {
            var rangeCommand = axisRange.SetRange(min: min, max: max);

            Gnuplot.WriteCommand(rangeCommand);
        }
Ejemplo n.º 22
0
        private static void _setLabel(string label, int rotation, AxisLabel axisLabel)
        {
            var labelCommand = axisLabel.SetLabel(label: label, rotation: rotation);

            Gnuplot.WriteCommand(labelCommand);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Plot to a gif file ('set terminal gif').
        /// </summary>
        /// <param name="xSize">Horizontal size in centimeters, ignored if <paramref name="xSize"/> or <paramref name="ySize"/> is negative.</param>
        /// <param name="ySize">Vertical size in centimeters.</param>
        /// <param name="Options">
        /// Options for gnuplot cairolatex terminal
        /// </param>
        /// <param name="gp"></param>
        /// <returns>
        /// A memory-image of gnuplot cairolatex output.
        /// </returns>
        static public CairolatexContainer PlotCairolatex(this Gnuplot gp,
                                                         //string Options = " pdf input noheader blacktext nobackground noenhanced fontscale 0.6 ",
                                                         string Options = " pdf  ",
                                                         double xSize   = 14, double ySize = 10.5)
        {
            // return object
            var clc = new CairolatexContainer();

            // set terminal
            if (xSize >= 0 && ySize >= 0)
            {
                gp.Terminal = string.Format("cairolatex {0} size {1}cm,{2}cm", Options != null ? Options : " ", xSize.ToStringDot(), ySize.ToStringDot());
            }
            else
            {
                gp.Terminal = string.Format("cairolatex {0} size {1}cm,{2}cm", Options != null ? Options : " ");
            }

            // set output file
            string baseName = Path.GetTempFileName();

            baseName = Path.Combine(Path.GetDirectoryName(baseName), Path.GetFileNameWithoutExtension(baseName));
            string TexOutfileName = baseName + ".tex";

            gp.OutputFile = TexOutfileName;

            string GraphisOut = Path.Combine(Path.GetDirectoryName(TexOutfileName), baseName);

            // gnuplot script
            {
                string[] tmpFiles = gp.TempFilesPath.ToArray();

                clc.DataFiles     = new string[tmpFiles.Length];
                clc.DataFileNames = new string[tmpFiles.Length];

                string AllCommands = gp.GetAllCommandsString();

                for (int i = 0; i < tmpFiles.Length; i++)
                {
                    string tmpFile = tmpFiles[i];

                    string scriptName = tmpFile.Replace(Path.DirectorySeparatorChar, '/');
                    string newName    = baseName + "_data_" + i + ".csv";

                    AllCommands = AllCommands.Replace(scriptName, newName);

                    clc.DataFiles[i]     = File.ReadAllText(tmpFile);
                    clc.DataFileNames[i] = newName;
                }

                AllCommands = AllCommands.Replace(TexOutfileName, Path.GetFileName(TexOutfileName));

                AllCommands = AllCommands + System.Environment.NewLine + "exit" + System.Environment.NewLine;

                clc.GnuplotScript = AllCommands;
            }

            // call gnuplot
            {
                int exCode = gp.RunAndExit(); // run & close gnuplot
                if (exCode != 0)
                {
                    Console.WriteLine("Gnuplot-internal error: exit code " + exCode);
                    return(null);
                }
            }

            // return graphics
            {
                string TexContent = File.ReadAllText(TexOutfileName);

                string GraphisOut_ext = null;
                if (File.Exists(GraphisOut + ".eps"))
                {
                    GraphisOut_ext = ".eps";
                }
                else if (File.Exists(GraphisOut + ".pdf"))
                {
                    GraphisOut_ext = ".pdf";
                }
                else
                {
                    throw new FileNotFoundException(string.Format("Unable to find either eps or pdf file: {0}.pdf or {0}.eps.", GraphisOut));
                }

                byte[] PdfOrEps = File.ReadAllBytes(GraphisOut + GraphisOut_ext);
                TexContent           = TexContent.Replace(GraphisOut, Path.GetFileNameWithoutExtension(baseName)); // hack replacement of absolute path.
                clc.LatexCode        = TexContent;
                clc.GraphicsData     = PdfOrEps;
                clc.GraphicsFilename = Path.GetFileName(GraphisOut) + GraphisOut_ext;
            }

            return(clc);
        }
Ejemplo n.º 24
0
        private void _setTicks(IEnumerable <double> ticksValues, AxisTicks axisTicks)
        {
            var ticksCommand = axisTicks.SetTicks(ticksValues: ticksValues);

            Gnuplot.WriteCommand(ticksCommand);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Writes plot commands to a gnuplot object.
        /// </summary>
        public void ToGnuplot(Gnuplot gp)
        {
            //gp.Cmd($"set terminal enhanced font \"Helvetica, 30\" ");

            // =======
            // margins
            // =======
            {
                if (lmargin != null)
                {
                    gp.Cmd("set lmargin {0:0.####e-00}", this.lmargin.Value);
                }
                else
                {
                    gp.Cmd("unset lmargin ");
                }

                if (rmargin != null)
                {
                    gp.Cmd("set rmargin {0:0.####e-00}", this.rmargin.Value);
                }
                else
                {
                    gp.Cmd("unset rmargin ");
                }

                if (tmargin != null)
                {
                    gp.Cmd("set tmargin {0:0.####e-00}", this.tmargin.Value);
                }
                else
                {
                    gp.Cmd("unset tmargin ");
                }

                if (bmargin != null)
                {
                    gp.Cmd("set bmargin {0:0.####e-00}", this.bmargin.Value);
                }
                else
                {
                    gp.Cmd("unset bmargin ");
                }
            }

            // ============
            // log settings
            // ============
            {
                if (this.LogX)
                {
                    gp.Cmd("set logscale x " + this.LogBaseX);
                }
                else
                {
                    gp.Cmd("unset logscale x");
                }

                if (this.LogY)
                {
                    gp.Cmd("set logscale y " + this.LogBaseY);
                }
                else
                {
                    gp.Cmd("unset logscale y");
                }

                if (this.LogX2)
                {
                    gp.Cmd("set logscale x2 " + this.LogBaseX);
                }
                else
                {
                    gp.Cmd("unset logscale x2");
                }

                if (this.LogY2)
                {
                    gp.Cmd("set logscale y2 " + this.LogBaseY);
                }
                else
                {
                    gp.Cmd("unset logscale y2");
                }
            }

            // ==========
            // axis range
            // ==========

            {
                if ((this.XrangeMax != null) != (this.XrangeMin != null))
                {
                    throw new ArgumentException("X range minimum and maximum must be set either both or none.");
                }
                if ((this.YrangeMax != null) != (this.YrangeMin != null))
                {
                    throw new ArgumentException("Y range minimum and maximum must be set either both or none.");
                }

                if (this.XrangeMin != null)
                {
                    if (this.XrangeMin.Value >= this.XrangeMax.Value)
                    {
                        throw new ArgumentException("X range maximum must be grater than minimum.");
                    }

                    gp.SetXRange(this.XrangeMin.Value, this.XrangeMax.Value);
                }
                else
                {
                    gp.SetXAutorange();
                }

                if (this.YrangeMin != null)
                {
                    if (this.YrangeMin.Value >= this.YrangeMax.Value)
                    {
                        throw new ArgumentException("Y range maximum must be grater than minimum.");
                    }

                    gp.SetYRange(this.YrangeMin.Value, this.YrangeMax.Value);
                }
                else
                {
                    gp.SetYAutorange();
                }


                if ((this.X2rangeMax != null) != (this.X2rangeMin != null))
                {
                    throw new ArgumentException("X2 range minimum and maximum must be set either both or none.");
                }
                if ((this.Y2rangeMax != null) != (this.Y2rangeMin != null))
                {
                    throw new ArgumentException("Y2 range minimum and maximum must be set either both or none.");
                }

                if (this.X2rangeMin != null)
                {
                    if (this.X2rangeMin.Value >= this.X2rangeMax.Value)
                    {
                        throw new ArgumentException("X range maximum must be grater than minimum.");
                    }

                    gp.SetX2Range(this.X2rangeMin.Value, this.X2rangeMax.Value);
                }
                else
                {
                    gp.SetX2Autorange();
                }

                if (this.Y2rangeMin != null)
                {
                    if (this.Y2rangeMin.Value >= this.Y2rangeMax.Value)
                    {
                        throw new ArgumentException("Y2 range maximum must be grater than minimum.");
                    }

                    gp.SetY2Range(this.Y2rangeMin.Value, this.Y2rangeMax.Value);
                }
                else
                {
                    gp.SetY2Autorange();
                }
            }

            // ========================
            // labels, title, legend...
            // ========================
            {
                gp.SetXLabel(this.Xlabel);
                gp.SetYLabel(this.Ylabel);
                gp.SetX2Label(this.X2label);
                gp.SetY2Label(this.Y2label);

                gp.SetTitle(this.Title);


                if (this.ShowLegend)
                {
                    gp.Cmd("unset key");
                    string command = $"set key font \",{this.LegendFont}\"";

                    if ((this.LegendPosition != null) & (this.LegendAlignment != null))
                    {
                        System.Console.WriteLine("legend position and legend alignment is set. Choose only one of them! Ignoring alignment ...");
                    }

                    if (this.LegendPosition != null)
                    {
                        command += String.Format("at {1:0.####e-00},{2:0.####e-00} vertical maxrows {0} ", this.dataGroups.Length, this.LegendPosition[0], this.LegendPosition[1]);
                    }
                    else if (this.LegendAlignment != null)
                    {
                        Dictionary <string, string> alignments = new Dictionary <string, string>();
                        alignments.Add("r", "right");
                        alignments.Add("c", "center");
                        alignments.Add("l", "left");
                        alignments.Add("b", "bottom");
                        alignments.Add("t", "top");

                        switch (LegendAlignment[0])
                        {
                        case "o":
                            //alignment within plotboundary
                            command += "outside ";
                            break;

                        case "i":
                            //alignement within graphyboundary
                            command += "inside ";
                            break;

                        default:
                            throw new ArgumentException("this style is not specified: use [i/o]");
                        }

                        for (int i = 1; i <= 2; i++)
                        {
                            foreach (KeyValuePair <string, string> kvp in alignments)
                            {
                                if (LegendAlignment[i] == kvp.Key)
                                {
                                    command += kvp.Value + " ";
                                }
                            }
                        }
                    }
                    else
                    {
                        //throw new ArgumentNullException("no alignment or position chosen");
                    }
                    if (this.LegendHorizontal == true)
                    {
                        command += "horizontal ";
                    }

                    if (this.LegendSwap == true)
                    {
                        command += "Left reverse ";
                    }

                    System.Console.WriteLine(command);
                    gp.Cmd(command);
                }
                else
                {
                    gp.Cmd("set key off");
                }
            }

            // ====
            // tics
            // ====
            {
                if (this.ShowXtics)
                {
                    if (this.LogX)
                    {
                        gp.Cmd("set xtics format \"$" + this.LogBaseX + "^{%L}$\" ");
                        gp.Cmd("set xtics offset 0, 0-0.4 font \"sans, 18\" ");
                        gp.Cmd($"set xtics font \"sans, {this.LabelFont}\" ");
                    }
                    else
                    {
                        gp.Cmd("set xtics ");
                    }
                }
                else
                {
                    gp.Cmd("set xtics format \" \" "); // shows ticks/marks, but hides numbers
                }

                if (this.ShowX2tics)
                {
                    if (this.LogX2)
                    {
                        gp.Cmd("set x2tics format \"$" + this.LogBaseX + "^{%L}$\" ");
                    }
                    else
                    {
                        gp.Cmd("set x2tics ");
                    }
                }
                else
                {
                    gp.Cmd("set x2tics format \" \" "); // shows ticks/marks, but hides numbers
                }

                if (this.ShowYtics)
                {
                    if (this.LogY)
                    {
                        gp.Cmd("set ytics format \"$" + this.LogBaseY + "^{%L}$\" ");
                        gp.Cmd($"set ytics font \"sans, {this.LabelFont}\" ");
                    }
                    else
                    {
                        gp.Cmd("set ytics ");
                    }
                }
                else
                {
                    gp.Cmd("set ytics format \" \" "); // shows ticks/marks, but hides numbers
                }

                if (this.ShowY2tics)
                {
                    if (this.LogY2)
                    {
                        gp.Cmd("set y2tics format \"$" + this.LogBaseY + "^{%L}$\" ");
                    }
                    else
                    {
                        gp.Cmd("set y2tics ");
                    }
                }
                else
                {
                    //gp.Cmd("unset y2tics");
                    gp.Cmd("set y2tics format \" \" "); // shows ticks/marks, but hides numbers
                }
            }



            // =================
            // finally, plotting
            // =================
            {
                foreach (var xyData in this.dataGroups)
                {
                    gp.PlotXY(xyData.Abscissas, xyData.Values, xyData.Name, xyData.Format, useX2: xyData.UseX2, useY2: xyData.UseY2, deferred: true);
                }

                gp.WriteDeferredPlotCommands();
            }
        }
Ejemplo n.º 26
0
        private void _removeTicks(AxisTicks axisTicks)
        {
            var removeTickscommand = axisTicks.RemoveTicks();

            Gnuplot.WriteCommand(removeTickscommand);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Performs a check for
        /// - MPI
        /// - Required libraries
        /// - Optional libraries
        /// </summary>
        public static void CheckSetup()
        {
            Console.WriteLine(
                "Congratulations! Your basic BoSSS installation seems to be working");

            int numberOfBits = IntPtr.Size * 8;

            Console.WriteLine();
            Console.WriteLine(
                "You are running {0} bit BoSSS on a {1} operating system",
                numberOfBits,
                System.Environment.OSVersion.Platform);

            csMPI.Raw.Comm_Rank(csMPI.Raw._COMM.WORLD, out int rank);
            csMPI.Raw.Comm_Size(csMPI.Raw._COMM.WORLD, out int size);

            Console.Out.Flush();
            csMPI.Raw.Barrier(csMPI.Raw._COMM.WORLD);
            Console.WriteLine();
            Console.WriteLine("BoSSS has been started with {0} MPI processes", size);

            ilPSP.Environment.StdoutOnlyOnRank0 = false;
            csMPI.Raw.Barrier(csMPI.Raw._COMM.WORLD);
            Console.Out.Flush();
            Console.WriteLine(
                "Hello from rank {0}!", rank);
            ilPSP.Environment.StdoutOnlyOnRank0 = true;


            Console.WriteLine();
            Console.WriteLine("Status of REQUIRED external libraries:");
            {
                // MPI should already be loaded
                CheckDynamicLibrary("MPI", () => (DynLibLoader)csMPI.Raw);
                CheckDynamicLibrary("BLAS", () => new UnsafeDBLAS());
                CheckDynamicLibrary("LAPACK", () => new LAPACK());
            }


            Console.WriteLine();
            Console.WriteLine("Status of OPTIONAL external libraries:");
            {
                string prepend = String.Format("- gnuplot:").PadRight(23);
                try {
                    string path = Gnuplot.GetGnuplotPath();
                    string file = Path.GetFileName(path);
                    path = Path.GetDirectoryName(path);

                    ReportSuccess("gnuplot", file, path);
                } catch (Exception e) {
                    ReportError("gnuplot", isOptional: true, detailedMessage: e.Message);
                }

                CheckDynamicLibrary("METIS", () => new Metis(), isOptional: true);
                CheckDynamicLibrary("ParMETIS", () => new ParMetis(), isOptional: true);

                CheckDynamicLibrary("CGNS", () => new CgnsDriver(false), isOptional: true);
                CheckDynamicLibrary("CGNS (HDF5)", () => new CgnsDriver(true), isOptional: true);

                CheckDynamicLibrary("Tecplot", () => new Tecplot(), isOptional: true);

                CheckDynamicLibrary("MUMPS", () => new MUMPS(), isOptional: true);

                CheckDynamicLibrary("PARDISO (Intek MKL)", () => new ilPSP.LinSolvers.PARDISO.Wrapper_MKL(), isOptional: true);
                CheckDynamicLibrary("PARDISO (v4)", () => new ilPSP.LinSolvers.PARDISO.Wrapper_v4(), isOptional: true);
                CheckDynamicLibrary("PARDISO (v5)", () => new ilPSP.LinSolvers.PARDISO.Wrapper_v5(), isOptional: true);

                CheckDynamicLibrary("OpenCL", () => new ilPSP.LinSolvers.monkey.CL.cl(), isOptional: true);
                CheckDynamicLibrary("CUDA", () => new ilPSP.LinSolvers.monkey.CUDA.cu(), isOptional: true);
            }

            if (log != null)
            {
                log.Close();
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Writes plot commands to a gnuplot object.
        /// </summary>
        public void ToGnuplot(Gnuplot gp)
        {
            // =======
            // margins
            // =======
            {
                if (lmargin != null)
                {
                    gp.Cmd("set lmargin {0:0.####e-00}", this.lmargin.Value);
                }
                else
                {
                    gp.Cmd("unset lmargin ");
                }

                if (rmargin != null)
                {
                    gp.Cmd("set rmargin {0:0.####e-00}", this.rmargin.Value);
                }
                else
                {
                    gp.Cmd("unset rmargin ");
                }

                if (tmargin != null)
                {
                    gp.Cmd("set tmargin {0:0.####e-00}", this.tmargin.Value);
                }
                else
                {
                    gp.Cmd("unset tmargin ");
                }

                if (bmargin != null)
                {
                    gp.Cmd("set bmargin {0:0.####e-00}", this.bmargin.Value);
                }
                else
                {
                    gp.Cmd("unset bmargin ");
                }
            }

            // ============
            // log settings
            // ============
            {
                if (this.LogX)
                {
                    gp.Cmd("set logscale x");
                }
                else
                {
                    gp.Cmd("unset logscale x");
                }

                if (this.LogY)
                {
                    gp.Cmd("set logscale y");
                }
                else
                {
                    gp.Cmd("unset logscale y");
                }

                if (this.LogX2)
                {
                    gp.Cmd("set logscale x2");
                }
                else
                {
                    gp.Cmd("unset logscale x2");
                }

                if (this.LogY2)
                {
                    gp.Cmd("set logscale y2");
                }
                else
                {
                    gp.Cmd("unset logscale y2");
                }
            }

            // ==========
            // axis range
            // ==========

            {
                if ((this.XrangeMax != null) != (this.XrangeMin != null))
                {
                    throw new ArgumentException("X range minimum and maximum must be set either both or none.");
                }
                if ((this.YrangeMax != null) != (this.YrangeMin != null))
                {
                    throw new ArgumentException("Y range minimum and maximum must be set either both or none.");
                }

                if (this.XrangeMin != null)
                {
                    if (this.XrangeMin.Value >= this.XrangeMax.Value)
                    {
                        throw new ArgumentException("X range maximum must be grater than minimum.");
                    }

                    gp.SetXRange(this.XrangeMin.Value, this.XrangeMax.Value);
                }
                else
                {
                    gp.SetXAutorange();
                }

                if (this.YrangeMin != null)
                {
                    if (this.YrangeMin.Value >= this.YrangeMax.Value)
                    {
                        throw new ArgumentException("Y range maximum must be grater than minimum.");
                    }

                    gp.SetYRange(this.YrangeMin.Value, this.YrangeMax.Value);
                }
                else
                {
                    gp.SetYAutorange();
                }


                if ((this.X2rangeMax != null) != (this.X2rangeMin != null))
                {
                    throw new ArgumentException("X2 range minimum and maximum must be set either both or none.");
                }
                if ((this.Y2rangeMax != null) != (this.Y2rangeMin != null))
                {
                    throw new ArgumentException("Y2 range minimum and maximum must be set either both or none.");
                }

                if (this.X2rangeMin != null)
                {
                    if (this.X2rangeMin.Value >= this.X2rangeMax.Value)
                    {
                        throw new ArgumentException("X range maximum must be grater than minimum.");
                    }

                    gp.SetX2Range(this.X2rangeMin.Value, this.X2rangeMax.Value);
                }
                else
                {
                    gp.SetX2Autorange();
                }

                if (this.Y2rangeMin != null)
                {
                    if (this.Y2rangeMin.Value >= this.Y2rangeMax.Value)
                    {
                        throw new ArgumentException("Y2 range maximum must be grater than minimum.");
                    }

                    gp.SetY2Range(this.Y2rangeMin.Value, this.Y2rangeMax.Value);
                }
                else
                {
                    gp.SetY2Autorange();
                }
            }

            // ========================
            // labels, title, legend...
            // ========================
            {
                gp.SetXLabel(this.Xlabel);
                gp.SetYLabel(this.Ylabel);
                gp.SetX2Label(this.X2label);
                gp.SetY2Label(this.Y2label);

                gp.SetTitle(this.Title);


                if (this.ShowLegend)
                {
                    gp.Cmd("unset key");

                    if (this.LegendPosition != null)
                    {
                        gp.Cmd("set key at {1:0.####e-00},{2:0.####e-00} vertical maxrows {0} ", this.dataGroups.Length, this.LegendPosition[0], this.LegendPosition[1]);
                    }
                    else
                    {
                        gp.Cmd("set key outside right vertical maxrows {0} ", this.dataGroups.Length);
                    }
                }
                else
                {
                    gp.Cmd("set key off");
                }
            }

            // ====
            // tics
            // ====
            {
                if (this.ShowXtics)
                {
                    if (this.LogX)
                    {
                        gp.Cmd("set xtics format \"$10^{%T}$\" ");
                    }
                    else
                    {
                        gp.Cmd("set xtics ");
                    }
                }
                else
                {
                    gp.Cmd("set xtics format \" \" "); // shows ticks/marks, but hides numbers
                }

                if (this.ShowX2tics)
                {
                    if (this.LogX2)
                    {
                        gp.Cmd("set x2tics format \"$10^{%T}$\" ");
                    }
                    else
                    {
                        gp.Cmd("set x2tics ");
                    }
                }
                else
                {
                    gp.Cmd("set x2tics format \" \" "); // shows ticks/marks, but hides numbers
                }

                if (this.ShowYtics)
                {
                    if (this.LogY)
                    {
                        gp.Cmd("set ytics format \"$10^{%T}$\" ");
                    }
                    else
                    {
                        gp.Cmd("set ytics ");
                    }
                }
                else
                {
                    gp.Cmd("set ytics format \" \" "); // shows ticks/marks, but hides numbers
                }

                if (this.ShowY2tics)
                {
                    if (this.LogY2)
                    {
                        gp.Cmd("set y2tics format \"$10^{%T}$\" ");
                    }
                    else
                    {
                        gp.Cmd("set y2tics ");
                    }
                }
                else
                {
                    //gp.Cmd("unset y2tics");
                    gp.Cmd("set y2tics format \" \" "); // shows ticks/marks, but hides numbers
                }
            }



            // =================
            // finally, plotting
            // =================
            {
                foreach (var xyData in this.dataGroups)
                {
                    gp.PlotXY(xyData.Abscissas, xyData.Values, xyData.Name, xyData.Format, useX2: xyData.UseX2, useY2: xyData.UseY2, deferred: true);
                }

                gp.WriteDeferredPlotCommands();
            }
        }
Ejemplo n.º 29
0
    static void Main(string[] args)
    {
        Gnuplot.Start();
        var x = Enumerable.Range(-100, 201).Select(z => z * 0.025 * Math.PI).ToArray();

        var tanX       = x.Select(Math.Tan).ToArray();
        var sinX       = x.Select(Math.Sin).ToArray();
        var sincosX    = sinX.Select(Math.Cos).ToArray();
        var sincostanX = sincosX.Select(Math.Tan).ToArray();
        var expsinX    = sinX.Select((e, idx) => e * Math.Exp(-x[idx] / 4)).ToArray();

        var dataSet = new DataSet(x, tanX);

        var(lineDatasetId, lineDataset) = Gnuplot.Plot <Line2D>(ds: dataSet);
        lineDataset.SetTitle(title: "WithDataSets");
        lineDataset.SetWidth(width: 2);
        lineDataset.SetDashType(dashType: DashType.DashDotted);
        lineDataset.SetColor(color: Color.Navy);

        // Gnuplot Example 1:
        var(test0Id, test0) = Gnuplot.Plot <Scatter2D>(x, x, "Test 0", size: 0.7, marker: Marker.ColoredCircle, color: Color.SteelBlue);
        var(test1Id, test1) = Gnuplot.Plot <Line2D>(x, sinX, "Test 1", width: 2, dashType: DashType.DashDoubleDotted, color: Color.Red);
        var(test2Id, test2) = Gnuplot.Plot <Scatter2D>(x, sincosX, "Test 2", size: 1, marker: Marker.BlankTriangle, color: Color.Grey);
        var(test3Id, test3) = Gnuplot.Plot <Line2D>(x, sincostanX, "Test 3", width: 0.5, dashType: DashType.Solid, color: Color.Green);

        Gnuplot.Axis.SetXTicks(new List <double>()
        {
            -4, -2, -1, 0, 1, 2, 4
        });
        Gnuplot.Axis.SetYTicks(new List <double>()
        {
            -4, -3, -1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1, 3, 4
        });
        var xticks = new Dictionary <string, double>()
        {
            { "pi", Math.PI }, { "phi", 1.618 }, { "e", Math.E }
        };

        Gnuplot.Axis.AddTicks(labelValues: xticks, axis: 0);
        Gnuplot.Axis.SetXLabel(label: "x-axis", rotation: -20);
        Gnuplot.Axis.SetYLabel(label: "y-axis");
        Gnuplot.Legend.SetPosition(position: Position.LeftTop);
        Gnuplot.Show();
        Gnuplot.Wait();

        // Gnuplot Impulse example
        Gnuplot.CleanData();
        var(test4Id, test4) = Gnuplot.Plot <Impulse>(x, expsinX);
        test4.SetColor(Color.Brown);
        var(test5Id, test5) = Gnuplot.Plot <Scatter2D>(x, expsinX);
        test5.SetColor(Color.Black);
        test5.SetSize(1.25);
        test5.SetMarker(Marker.BlankCircle);
        Gnuplot.Show();
        Gnuplot.Wait();

        // Gnuplot Example 3D
        Gnuplot.CleanData();
        Gnuplot.SetPlotType(PlotType.Splot);
        Gnuplot.Axis.SetXRange(-8, 8);
        Gnuplot.Axis.SetYRange(-1, 1);
        Gnuplot.Axis.SetZRange(0, 2);
        Gnuplot.Axis.SetXLabel("x");
        Gnuplot.Axis.SetYLabel("y");
        Gnuplot.Axis.SetZLabel("z");
        Gnuplot.Axis.AddTicks(labelValues: xticks, axis: 0);
        var(id, fig) = Gnuplot.Plot <Line3D>(x, sinX, x.Select(e => 0.1).ToList(),
                                             title: "foo", color: Color.SteelBlue, width: 4, dashType: DashType.DashDotted);
        var(id2, fig2) = Gnuplot.Plot <Scatter3D>(x, sinX, sincostanX);
        fig2.SetColor(Color.Grey);
        fig2.SetTitle("bar");
        Gnuplot.Legend.SetPosition(Position.RightBottom);
        Gnuplot.Show();
        Gnuplot.Wait();

        // Gnuplot Example Surface with lines
        Gnuplot.CleanData();
        Gnuplot.SetPlotType(PlotType.Splot);
        Gnuplot.SetIsolineDensiy(30);
        var(id3, fig3) = Gnuplot.Plot <Surface3D>(function: "x**2-y**2");
        var(id4, fig4) = Gnuplot.Plot <Surface3D>(function: "x**2+y**2");
        var(id5, fig5) = Gnuplot.Plot <Line3D>(x: x.Select(e => 0.0).ToList(), y: x, z: x.Select(e => - (e * e)).ToList());
        var(id6, fig6) = Gnuplot.Plot <Line3D>(x: x, y: x.Select(e => 0.0).ToList(), z: x.Select(e => (e * e)).ToList());
        fig3.SetColor(Color.Purple);
        fig3.SetTitle("x**2-y**2");
        fig4.SetColor(Color.Navy);
        fig4.SetTitle("x**2+y**2");
        fig5.SetWidth(2.5);
        fig6.SetWidth(2.5);
        Gnuplot.Show();
        Gnuplot.Wait();

        // Gnuplot Example Histogram
        Gnuplot.CleanData();
        var size   = 10000;
        var values = new double[size];

        Normal.Samples(values, 0, 2);
        var(id7, fig7) = Gnuplot.Plot <Histogram>(values);
        fig7.SetColor(Color.SteelBlue);
        fig7.SetTitle("Normal distribution");
        Gnuplot.FillSolid(alpha: 0.4);
        Gnuplot.Show();
        Gnuplot.Wait();

        // Gnuplot Example Vector
        Gnuplot.CleanData();
        var px     = new List <double>();
        var py     = new List <double>();
        var xForce = new List <double>();
        var yForce = new List <double>();
        var _x     = Generate.LinearSpaced(20, -Math.PI, Math.PI).ToList();

        foreach (var xPoint in _x)
        {
            foreach (var yPoint in _x)
            {
                px.Add(xPoint);
                py.Add(yPoint);
                xForce.Add(0.3 * xPoint / Math.Sqrt(Math.Pow(xPoint, 2) + Math.Pow(yPoint, 2) + 4));
                yForce.Add(-0.3 * yPoint / Math.Sqrt(Math.Pow(xPoint, 2) + Math.Pow(yPoint, 2) + 4));
            }
        }
        var(id8, fig8) = Gnuplot.Plot <Vector>(px, py, xForce, yForce);
        Gnuplot.Show();
        Gnuplot.Wait();

        // Gnuplot Example 2:
        Gnuplot.CleanData();
        Gnuplot.Axis.SetXRange(-8, 8);
        Gnuplot.Axis.SetYRange(-1, 1);
        Gnuplot.Axis.SetXLabel("x");
        Gnuplot.Axis.SetYLabel("sin(x)");
        var(sinXId, sinXFig) = Gnuplot.Plot <Line2D>(x, sinX);
        Gnuplot.Show();
        Gnuplot.Wait();

        Gnuplot.Exit();
    }
Ejemplo n.º 30
0
        /*
         * private async void buttonOutputPlt_Click(object sender, RoutedEventArgs e)
         * {
         * // Pltファイルを出力する。
         * var dialog = new Microsoft.Win32.SaveFileDialog { Filter = "pltファイル(*.plt)|*.plt" };
         * if (dialog.ShowDialog() == true)
         * {
         *      var csv_destination = labelOutputDepthCsvDestination.Content.ToString();
         *      var chart_destination = labelOutputDepthChartDestination.Content.ToString();
         *
         *      using (var writer = new StreamWriter(dialog.FileName))
         *      {
         *              await WritePltCommands(writer, csv_destination, chart_destination, ChartFormat.Png);
         *      }
         * }
         * }
         */


        #region DepthProfile関連

        //DepthProfile _depthProfileData;

        #region *DepthProfileのチャートを表示(DisplayDepthChart)
        async void DisplayDepthChart(string source, string destination, ChartFormat format)
        {
            var gnuplot = new Gnuplot
            {
                Format      = format,
                Width       = 800,
                Height      = 600,
                FontScale   = 1.6,
                Destination = destination,
                XTitle      = "K.E. / eV",
                YTitle      = "Intensity"
            };

            gnuplot.DataSeries.Add(new LineChartSeries
            {
                SourceFile = source,
                XColumn    = 1,
                YColumn    = 2,
                Title      = "Layer 0",
                Style      = new LineChartSeriesStyle(LineChartStyle.Lines)
                {
                    Style = new LinePointStyle
                    {
                        LineColor = "#FF0000",
                        LineWidth = 3,
                    }
                }
            });
            gnuplot.DataSeries.Add(new LineChartSeries
            {
                SourceFile = source,
                XColumn    = 1,
                YColumn    = 3,
                Title      = "Layer 1",
                Style      = new LineChartSeriesStyle(LineChartStyle.Lines)
                {
                    Style = new LinePointStyle
                    {
                        LineColor = "#CC0000",
                        LineWidth = 2,
                    }
                }
            });
            gnuplot.DataSeries.Add(new LineChartSeries
            {
                SourceFile = source,
                XColumn    = 1,
                YColumn    = 4,
                Title      = "Layer 2",
                Style      = new LineChartSeriesStyle(LineChartStyle.Lines)
                {
                    Style = new LinePointStyle
                    {
                        LineColor = "#AA0000"
                    }
                }
            });


            await gnuplot.Draw();

            //imageChart.Source = new BitmapImage(new Uri(destination));
        }
Ejemplo n.º 31
0
        static void Plot2dGridGnuplot(GridCommons grd)
        {
            using (var gp = new Gnuplot()) {
                int J = grd.Cells.Length;


                double xmin = double.MaxValue, xmax = double.MinValue, ymin = double.MaxValue, ymax = double.MinValue;
                for (int j = 0; j < J; j++)
                {
                    var Cell = grd.Cells[j];
                    var Kref = grd.GetRefElement(Cell.Type);

                    int[] R;
                    if (Kref.GetType() == typeof(Triangle))
                    {
                        R = new int[] { 0, 1, 2, 0 };
                    }
                    else if (Kref.GetType() == typeof(Square))
                    {
                        R = new int[] { 0, 1, 3, 2, 0 };
                    }
                    else
                    {
                        throw new NotSupportedException();
                    }

                    int     I        = 4;
                    int     K        = 20;
                    NodeSet LocNodes = new NodeSet(Kref, I * K * (R.Length - 1), 2);
                    var     vtx      = Kref.Vertices;
                    double  alpha    = 1.0 / (K - 1);
                    for (int iFace = 0; iFace < R.Length - 1; iFace++)
                    {
                        for (int k = 0; k < K; k++)
                        {
                            double a = alpha * k;

                            for (int d = 0; d < 2; d++)
                            {
                                LocNodes[iFace * K + k, d] = vtx[R[iFace], d] * (1 - a) + vtx[R[iFace + 1], d] * a;
                            }
                        }
                    }

                    for (int i = 0; i < I; i++)
                    {
                        int ind0  = K * (R.Length - 1) * i;
                        int indE  = K * (R.Length - 1) * (i + 1) - 1;
                        int indp0 = K * (R.Length - 1) * (i - 1);
                        int indpE = K * (R.Length - 1) * i - 1;

                        var LocNodes_i = LocNodes.ExtractSubArrayShallow(new int[] { ind0, 0 }, new int[] { indE, 1 });

                        if (i > 0)
                        {
                            var LocNodes_iP = LocNodes.ExtractSubArrayShallow(new int[] { indp0, 0 }, new int[] { indpE, 1 });
                            LocNodes_i.Set(LocNodes_iP);
                            LocNodes_i.Scale(0.65);
                        }
                        else
                        {
                            LocNodes_i.Scale(0.9);
                        }
                    }


                    LocNodes.LockForever();

                    MultidimensionalArray GlobalNodes = Transform(Kref, Cell, LocNodes);

                    xmin = Math.Min(xmin, GlobalNodes.ExtractSubArrayShallow(-1, 0).Min());
                    xmax = Math.Max(xmax, GlobalNodes.ExtractSubArrayShallow(-1, 0).Max());
                    ymin = Math.Min(ymin, GlobalNodes.ExtractSubArrayShallow(-1, 1).Min());
                    ymax = Math.Max(ymax, GlobalNodes.ExtractSubArrayShallow(-1, 1).Max());

                    gp.PlotXY(GlobalNodes.GetColumn(0), GlobalNodes.GetColumn(1), title: ("tri" + j),
                              format: new PlotFormat(lineColor: ((LineColors)j)));
                }

                gp.SetXRange(xmin - 0.1, xmax + 0.1);
                gp.SetYRange(ymin - 0.1, ymax + 0.1);

                gp.Execute();


                Console.WriteLine("press any key to continue...");
                Console.ReadKey();
            }
        }