private void PlotSurfaceBtn_Click(object sender, RoutedEventArgs e)
        {
            var B     = ILMath.tosingle(sigma);
            var scene = new PlotCube(twoDMode: false)
            {
                // add a surface
                new Surface(B)
                {
                    // make thin transparent wireframes
                    Wireframe = { Color = Color.FromArgb(50, Color.LightGray) },
                    // choose a different colormap
                    Colormap = Colormaps.Jet,
                }
            };

            scene.Axes.XAxis.Max = (float)arguments[0].Maximum;
            scene.Axes.XAxis.Min = (float)arguments[0].Minimum;
            scene.Axes.YAxis.Max = (float)arguments[1].Maximum;
            scene.Axes.YAxis.Min = (float)arguments[1].Minimum;
            scene.First <PlotCube>().Rotation = Matrix4.Rotation(new Vector3(1f, 0.23f, 1), 0.7f);

            PlotSurface form = new PlotSurface(scene);

            form.Refresh();
            form.ShowDialog();
        }
Example #2
0
        private void Plot2D(int selectedFuncId)
        {
            var range = 7000;

            float[][]       points = _benchmark.GeneratePoints(range);
            ILArray <float> A      = ILMath.zeros <float>(3, points.GetLength(0));

            for (int i = 0; i < points.GetLength(0); i++)
            {
                A[0, i] = points[i][0];
                A[1, i] = CallFunction(selectedFuncId, points[i]);
            }


            _scene = new ILScene();
            _scene.Add(new ILPlotCube(twoDMode: true)
            {
                new ILPoints
                {
                    Positions = ILMath.tosingle(A)
                }
            });

            ilPanel1.Scene = _scene;
            ilPanel1.Refresh();

            return;
        }
        private static void InitPanel(ILPanel panel, NeuralNetwork ann)
        {
            panel.Scene.Remove(panel.Scene.First <ILPlotCube>());
            int xmin = (int)ann.Instance.Samples[0].Variables[0];
            int xmax = (int)ann.Instance.Samples[ann.Instance.NumSamples - 1].Variables[0];
            int ymin = (int)ann.Instance.Samples[0].Variables[1];
            int ymax = (int)ann.Instance.Samples[ann.Instance.NumSamples - 1].Variables[0];

            ILArray <double> positions = ILMath.zeros <double>(3, ann.Instance.NumSamples);

            int index = 0;

            foreach (var sample in ann.Instance.Samples)
            {
                positions[0, index] = sample.Variables[0];
                positions[1, index] = sample.Variables[1];
                positions[2, index] = sample.Value;
                index++;
            }

            ILPlotCube cube = new ILPlotCube(twoDMode: false)
            {
                // rotate plot cube
                Rotation = Matrix4.Rotation(new Vector3(-1, 1, .1f), 0.4f),
                // perspective projection
                Projection = Projection.Perspective,
                Children   =
                {
                    new ILSurface((x,   y) => 0,
                                  xmin, xmax,                                                       50,
                                  ymin, ymax,                                                       50,
                                  (x,   y) => x * y,
                                  colormap: Colormaps.Autumn)
                    {
                        UseLighting = true
                    },
                    new ILSurface((x,   y) => (float)Convert(ann.Instance.OriginalFunction.ValueAt,x,  y),
                                  xmin, xmax,                                                       50,
                                  ymin, ymax,                                                       50,
                                  (x,   y) => x * y,
                                  colormap: Colormaps.Hsv)
                    {
                        UseLighting = true
                    },
                    // add line plot, provide data as rows
                    new ILPoints {
                        Positions = ILMath.tosingle(positions),
                        Color     = Color.Red
                    }
                }
            };

            panel.Scene.Add(cube);
            panel.Scene.First <ILPlotCube>().Rotation = Matrix4.Rotation(Vector3.UnitX, .8f) * Matrix4.Rotation(Vector3.UnitZ, .6f);
            panel.Refresh();
        }
Example #4
0
        /// <summary>
        /// Plot function with generation of individuals.
        /// </summary>
        /// <param name="selectedFuncId"></param>
        /// <param name="population"></param>
        private void PlotGeneration(int selectedFuncId, Individuals population)
        {
            ILArray <float> A   = ILMath.zeros <float>(3, population.Population.Count - 1);
            ILArray <float> B   = ILMath.zeros <float>(3, 0);
            var             dim = _benchmark.GetById(selectedFuncId).Dimension;

            var best = population.GetBest();

            int c = 0;

            foreach (var i in population.Population)
            {
                if (i == best)
                {
                    continue;
                }
                A[0, c] = i.Dimension[0];
                A[1, c] = i.Dimension[1];
                A[2, c] = i.Z;

                c += 1;
            }

            // Best individual
            B[0, 0] = best.Dimension[0];
            B[1, 0] = best.Dimension[1];
            B[2, 0] = best.Z;


            _scene = new ILScene()
            {
                new ILPlotCube(twoDMode: false)
                {
                    new ILSurface((x, y) => CallFunction(selectedFuncId, new float[] { x, y }),
                                  xmin: (float)genMin.Value, xmax: (float)genMax.Value, xlen: LENGTH,
                                  ymin: (float)genMin.Value, ymax: (float)genMax.Value, ylen: LENGTH,
                                  colormap: Colormaps.Hsv)
                    {
                        new ILColorbar()
                    },
                    new ILPoints {
                        Positions = ILMath.tosingle(B), Color = Color.Blue
                    },
                    new ILPoints {
                        Positions = ILMath.tosingle(A), Color = Color.DarkSlateGray
                    }
                }
            };

            ilPanel1.Scene = _scene;
            ilPanel1.Refresh();

            return;
        }
Example #5
0
        /// <summary>
        /// [internal] constructor - do not use this! Use ILPanel.Graphs.Add...() instead!
        /// </summary>
        /// <param name="panel">panel hosting the scene</param>
        /// <param name="XData">x data array</param>
        /// <param name="YData">y data array</param>
        /// <param name="clippingContainer">hosting panels clipping data</param>
        public ILPlot2DGraph(ILPanel panel, ILBaseArray XData, ILBaseArray YData,
                             ILClippingData clippingContainer)
            : base(panel, clippingContainer)
        {
            if (!XData.IsVector)
            {
                throw new ILArgumentException("Plot2D: supplied data must be a real vector!");
            }
            if (!YData.IsVector)
            {
                throw new ILArgumentException("Plot2D: XData and YData must be real vectors!");
            }
            if (YData.Length != XData.Length)
            {
                throw new ILArgumentException("Plot2D: XData and YData must have the same length!");
            }
            int             pos = 0;
            ILArray <float> dataX, dataY;
            C4bV3f          vert = new C4bV3f();

            if (XData is ILArray <float> )
            {
                dataX = (ILArray <float>)XData;
            }
            else
            {
                dataX = ILMath.tosingle(XData);
            }
            if (YData is ILArray <float> )
            {
                dataY = (ILArray <float>)YData;
            }
            else
            {
                dataY = ILMath.tosingle(YData);
            }
            m_vertices            = new C4bV3f[dataX.Length + 1];
            m_vertexCount         = m_vertices.Length;
            m_startID             = m_vertexCount - 1;
            m_updateCount         = 0;
            m_properties          = new ILLineProperties();
            m_properties.Color    = Color.DarkBlue;
            m_properties.Changed += new EventHandler(m_properties_Changed);
            foreach (float val in dataX.Values)
            {
                vert.Position     = new ILPoint3Df(val, dataY.GetValue(pos), 0);
                vert.Color        = m_properties.Color;
                m_vertices[pos++] = vert;
            }
            m_marker          = new ILMarker(panel);
            m_marker.Changed += new EventHandler(m_marker_Changed);
            m_graphType       = GraphType.Plot2D;
            updateClipping();
        }
        /// <summary>
        /// Add new graph(s) of arbitrary type, provide both axis data
        /// </summary>
        /// <param name="xData">x coordinates </param>
        /// <param name="graphType">type of graph to be added</param>
        /// <param name="yData">y coordinates</param>
        /// <returns>List with newly created graph(s)</returns>
        /// <remarks>The return value will be a list of all graphs created (and added),
        /// since more than one graph may have been specified. This depends on the
        /// shape of the data provided.
        /// <para>Currently only Plot2D graphs are supported as GraphType! </para></remarks>
        /// <exception cref="ILNumerics.Exceptions.ILArgumentException">if the data provided are nor
        /// numeric or the size for one of the arrays <typeparamref name="xData"/> or <typeparamref name="yData"/>
        /// do not match. </exception>
        public List <ILGraph> Add(ILBaseArray xData, ILBaseArray yData, GraphType graphType)
        {
            if (!yData.IsNumeric || !xData.IsNumeric)
            {
                throw new ILArgumentException("Add graph: data arrays must be numeric!");
            }
            List <ILGraph>  ret = new List <ILGraph>();
            ILGraph         newGraph;
            ILArray <float> tmpDataY, tmpDataX;

            lock (this) {
                #region add each graph type seperately
                switch (graphType)
                {
                case GraphType.Plot2D:
                    if (!yData.Dimensions.IsSameSize(xData.Dimensions))
                    {
                        throw new ILArgumentException("Add graph: for X/Y plots, the size of X and Y must be equal!");
                    }
                    if (yData.IsVector || yData.IsScalar)
                    {
                        newGraph = m_graphFact.CreateGraph(yData, graphType, xData);
                        Add(newGraph);
                        newGraph.Changed += new ILGraphChangedEvent(GraphChanged);
                        m_clippingData.Update(newGraph.Limits);
                        ret.Add(newGraph);
                    }
                    else if (yData.IsMatrix)
                    {
                        // plot columns
                        m_clippingData.EventingSuspend();
                        tmpDataY = ILMath.tosingle(yData);
                        tmpDataX = ILMath.tosingle(xData);
                        for (int c = 0; c < tmpDataY.Dimensions[1]; c++)
                        {
                            newGraph = m_graphFact.CreateGraph(tmpDataY[null, c], graphType, tmpDataX[null, c]);
                            Add(newGraph);
                            newGraph.Changed += new ILGraphChangedEvent(GraphChanged);
                            ret.Add(newGraph);
                            m_clippingData.Update(newGraph.Limits);
                        }
                        m_clippingData.EventingResume();
                    }
                    // trigger change event
                    OnChange(ret[0], GraphCollectionChangeReason.Added, null);
                    break;

                default:
                    throw new ILDrawingException("graph type is not supported in that mode yet!");
                }
                #endregion
            }
            return(ret);
        }
        public override ILCell GenerateTestArrays()
        {
            ILCell ret   = new ILCell();
            int    count = 0;
            // empty
            ILArray <float> tmp;

            ret[count++] = ILMath.tosingle(ILArray <float> .empty(0, 0));
            ret[count++] = ILMath.tosingle(ILArray <float> .empty(1, 0));
            ret[count++] = ILMath.tosingle(ILArray <float> .empty(0, 1, 0));
            // scalar
            ret[count++] = (ILArray <float>) 1.0f;
            ret[count++] = (ILArray <float>) float.NaN;
            ret[count++] = (ILArray <float>) float.PositiveInfinity;
            ret[count++] = (ILArray <float>) float.NegativeInfinity;
            ret[count++] = (ILArray <float>) 0.0f;
            ret[count++] = (ILArray <float>)(-30.0f);
            // vector
            ret[count++] = ILMath.tosingle(ILMath.zeros(1, 10));
            ret[count++] = ILMath.tosingle(ILMath.ones(1, 10));
            ret[count++] = ILMath.tosingle(ILMath.zeros(10, 1));
            ret[count++] = ILMath.tosingle(ILMath.ones(10, 1));
            ret[count++] = ILMath.tosingle(ILMath.vector(0.0, 10.0));
            ret[count++] = ILMath.tosingle(ILMath.vector(-5.0, 4.0));

            tmp          = ILMath.tosingle(ILMath.vector(-5.0, 4.0));
            tmp[0]       = float.NegativeInfinity;
            tmp["end"]   = float.PositiveInfinity;
            tmp[3]       = float.NaN;
            ret[count++] = tmp;
            // matrix
            ret[count++] = ILMath.tosingle(ILMath.zeros(3, 2));
            ret[count++] = ILMath.tosingle(ILMath.rand(2, 4));
            ret[count++] = ILMath.tosingle(ILMath.ones(2, 3) * float.NaN);
            ret[count++] = ILMath.tosingle(ILMath.ones(3, 2) / 0.0); // inf
            tmp          = ILMath.tosingle(ILMath.ones(3, 2));
            tmp[0]       = float.NaN;
            ret[count++] = tmp;
            tmp[1]       = float.PositiveInfinity;
            ret[count++] = tmp;
            tmp[3]       = float.NegativeInfinity;
            ret[count++] = tmp;
            // 3d array
            ret[count++] = ILMath.tosingle(ILMath.zeros(4, 3, 2));
            ret[count++] = ILMath.tosingle(ILMath.ones(4, 3, 2));
            ret[count++] = ILMath.tosingle(0.0 / ILMath.zeros(4, 3, 2));
            ret[count++] = ILMath.tosingle(ILMath.ones(4, 3, 2) * float.NaN);
            ret[count++] = ILMath.tosingle(ILMath.ones(4, 3, 2) * float.NegativeInfinity);
            ret[count++] = ILMath.tosingle(ILMath.rand(4, 3, 2));
            // 4d array
            ret[count++] = ILMath.tosingle(ILMath.rand(30, 2, 3, 20));

            return(ret);
        }
        public void Update(ILInArray <double> A)
        {
            using (ILScope.Enter(A))
            {
                var plot = ilPanel1.Scene.First <ILLinePlot>(tag: "mylineplot");
                if (plot != null)
                {
                    plot.Update(ILMath.tosingle(A));

                    plot.Configure();

                    ilPanel1.Refresh();
                }
            }
        }
Example #9
0
        protected void createQuads(ILBaseArray data)
        {
            if (data == null || data.Length == 0)
            {
                Clear();
                m_quads = new ILQuad[0];
            }
            else
            {
                Clear();
                m_quads = new ILQuad[data.Length];
                ILColorEnumerator colors = new ILColorEnumerator();
                ILArray <float>   fData  = null;
                if (data is ILArray <float> )
                {
                    fData = (ILArray <float>)data;
                }
                else
                {
                    fData = ILMath.tosingle(data);
                }
                for (int i = 0; i < m_quads.Length; i++)
                {
                    m_quads[i] = new ILQuad(m_panel);
                    m_quads[i].Border.Visible = true;
                    m_quads[i].FillColor      = colors.NextColor();
                    ILPoint3Df pos = new ILPoint3Df();
                    pos.X = i - m_barWidth / 2;
                    pos.Y = 0;
                    pos.Z = -0.5f;
                    m_quads[i].Vertices[0].Position = pos;
                    pos.X += m_barWidth;
                    m_quads[i].Vertices[1].Position = pos;
                    pos.Y += fData.GetValue(i);
                    m_quads[i].Vertices[2].Position = pos;
                    pos.X -= m_barWidth;
                    m_quads[i].Vertices[3].Position = pos;
                    // label the bar
                    m_quads[i].Label.Text   = i.ToString();
                    m_quads[i].Label.Anchor = new PointF(.5f, -1);

                    // bars will be transparent, oldest fading to OpacityOldest
                    m_quads[i].Opacity = (byte)(m_oldestOpacity + i * (255 - m_oldestOpacity) / m_quads.Length);
                    // add the bar to the scene graph node (base)
                    Add(m_quads[i]);
                }
            }
        }
        /// <summary>
        /// update composite shape
        /// </summary>
        /// <param name="X">x coordinates, vector of length <see cref="ILNumerics.Drawing.Shapes.ILShape.VertexCount"/></param>
        /// <param name="Y">y coordinates, vector of length <see cref="ILNumerics.Drawing.Shapes.ILShape.VertexCount"/></param>
        /// <param name="Z">z coordinates, vector of length <see cref="ILNumerics.Drawing.Shapes.ILShape.VertexCount"/></param>
        /// <remarks>All vertices of the shape are updated with the data specified in X,Y and Z. Neither the mapping of shapes
        /// nor the colors or any other data of vertices are changed. The shape is invalidated than. </remarks>
        public void Update(ILBaseArray X, ILBaseArray Y, ILBaseArray Z)
        {
            if (!X.IsVector || !Y.IsVector || !Z.IsVector || X.Length != Y.Length || Y.Length != Z.Length)
            {
                throw new ILArgumentException("numeric vectors of same length expected for: X, Y and Z");
            }
            ILArray <float> fX = ILMath.tosingle(X);
            ILArray <float> fY = ILMath.tosingle(Y);
            ILArray <float> fZ = ILMath.tosingle(Z);

            for (int i = 0; i < m_vertices.Length; i++)
            {
                m_vertices[i].XPosition = fX.GetValue(i);
                m_vertices[i].YPosition = fY.GetValue(i);
                m_vertices[i].ZPosition = fZ.GetValue(i);
            }
            Invalidate();
        }
Example #11
0
 /// <summary>
 /// Update the colorbar of the surface graph
 /// </summary>
 private void ColorBarUpdate()
 {
     _panel.Controls.Remove(_cb);
     _cm             = new ILColormap(_colormapType);
     _cm.Data        = ILMath.tosingle(_displayData);
     _panel.Colormap = _cm;
     _cb             = new ILColorBar(_cm);
     _cb.Orientation = isHorizontal?TextOrientation.Horizontal:TextOrientation.Vertical;
     _cb.Precision   = _colorbarDigits;
     _cb.BorderStyle = _borderStyleOfColorbar;
     _cb.Visible     = _colorbarVisible;
     _cb.BackColor   = _backColor;
     _cb.Width       = _widthOfColorbar;
     _cb.Height      = _heightOfColorbar;
     _cb.Location    = _position;
     _panel.Controls.Add(_cb);
     AutoScaleColorRange();
 }
Example #12
0
        /// <summary>
        /// Example update function used for dynamic updates to the plot
        /// </summary>
        /// <param name="A">New data, matching the requirements of your plot</param>
        public void Update(InArray<double> A) {
            using (Scope.Enter(A)) {

                // fetch a reference to the plot
                var plot = ilPanel1.Scene.First<LinePlot>(tag: "mylineplot");
                if (plot != null) {
                    // make sure, to convert elements to float
                    plot.Update(ILMath.tosingle(A));
                    //
                    // ... do more manipulations here ...

                    // finished with updates? -> Call Configure() on the changes 
                    plot.Configure();

                    // cause immediate redraw of the scene
                    ilPanel1.Refresh();
                }

            }
        }
Example #13
0
        /// <summary>
        /// [internal] constructor - do not use this! Use ILPanel.Graphs.Add...() instead!
        /// </summary>
        /// <param name="panel">panel hosting the scene</param>
        /// <param name="sourceArray">data array</param>
        /// <param name="clippingContainer">hosting panels clipping data</param>
        public ILPlot2DGraph(ILPanel panel, ILBaseArray sourceArray,
                             ILClippingData clippingContainer)
            : base(panel, clippingContainer)
        {
            if (object.Equals(sourceArray, null) || !sourceArray.IsVector || !sourceArray.IsNumeric)
            {
                throw new ILArgumentException("Plot2D: supplied data must be numeric (real valued) vector!");
            }
            int             pos = 0;
            ILArray <float> data;
            C4bV3f          vert = new C4bV3f();

            if (sourceArray is ILArray <float> )
            {
                data = (ILArray <float>)sourceArray;
            }
            else
            {
                data = ILMath.tosingle(sourceArray);
            }
            m_vertices            = new C4bV3f[data.Length + 1];
            m_vertexCount         = m_vertices.Length;
            m_updateCount         = 0;
            m_startID             = 0;
            m_properties          = new ILLineProperties();
            m_properties.Color    = Color.DarkBlue;
            m_properties.Changed += new EventHandler(m_properties_Changed);
            foreach (float val in data.Values)
            {
                vert.Position     = new ILPoint3Df(pos, val, 0);
                vert.Color        = Color.Red;
                m_vertices[pos++] = vert;
            }
            m_marker          = new ILMarker(panel);
            m_marker.Changed += new EventHandler(m_properties_Changed);
            m_graphType       = GraphType.Plot2D;
            m_localClipping.Set(new ILPoint3Df(0, data.MinValue, 0), new ILPoint3Df(data.Length - 1, data.MaxValue, 0));
        }
Example #14
0
        private void SetExampleScene(ILPanel panel)
        {
            ILScene scene = new ILScene();

            try {
                ILLabel.DefaultFont = new System.Drawing.Font("Helvetica", 8);
                //ilPanel1.Driver = RendererTypes.GDI;

                #region upper left plot
                // prepare some data
                ILArray <float> P = 1,
                                x = ILMath.linspace <float>(-2, 2, 40),
                                y = ILMath.linspace <float>(2, -2, 40);

                ILArray <float> F = ILMath.meshgrid(x, y, P);
                // a simple RBF
                ILArray <float> Z = ILMath.exp(-(1.2f * F * F + P * P));
                // surface expects a single matrix
                Z[":;:;2"] = F; Z[":;:;1"] = P;

                // add a plot cube
                var pc = scene.Add(new ILPlotCube {
                    // shrink viewport to upper left quadrant
                    ScreenRect = new RectangleF(0.05f, 0, 0.4f, 0.5f),
                    // 3D rotation
                    TwoDMode = false,
                    Children =
                    {
                        // add surface
                        new ILSurface(Z)
                        {
                            // disable mouse hover marking
                            Fill      = { Markable = false },
                            Wireframe ={ Markable                 = false },
                            // make it shiny
                            UseLighting = true,
                            Children    = { new ILColorbar() }
                        },
                        //ILLinePlot.CreateXPlots(Z["1:10;:;0"], markers: new List<MarkerStyle>() {
                        //    MarkerStyle.None,MarkerStyle.None,MarkerStyle.None,MarkerStyle.None,MarkerStyle.Circle, MarkerStyle.Cross, MarkerStyle.Plus, MarkerStyle.TriangleDown }),
                        //new ILLegend("hi","n","ku","zs","le", "blalblalblalblalb\\color{red} hier gehts rot")
                    },
                    Rotation = Matrix4.Rotation(new Vector3(1.1f, -0.4f, -0.69f), 1.3f)
                });

                #endregion

                #region top right plot
                // create a gear shape
                var gear = new ILGear(toothCount: 30, inR: 0.5f, outR: 0.9f)
                {
                    Fill = { Markable = false, Color = Color.DarkGreen }
                };
                // group with right clipping plane
                var clipgroup = new ILGroup()
                {
                    Clipping = new ILClipParams()
                    {
                        Plane0 = new Vector4(1, 0, 0, 0)
                    },
                    Children =
                    {
                        // a camera holding the (right) clipped gear
                        new ILCamera()
                        {
                            // shrink viewport to upper top quadrant
                            ScreenRect = new RectangleF(0.5f, 0, 0.5f, 0.5f),
                            // populate interactive changes back to the global scene
                            IsGlobal = true,
                            // adds the gear to the camera
                            Children ={ gear                },
                            Position = new Vector3(0, 0, -15)
                        }
                    }
                };
                // setup the scene
                var gearGroup = scene.Add(new ILGroup {
                    clipgroup, clipgroup // <- second time: group is cloned
                });

                gearGroup.First <ILCamera>().Parent.Clipping = new ILClipParams()
                {
                    Plane0 = new Vector4(-1, 0, 0, 0)
                };
                // make the left side transparent green
                gearGroup.First <ILTriangles>().Color = Color.FromArgb(100, Color.Green);

                // synchronize both cameras; source: left side
                gearGroup.First <ILCamera>().PropertyChanged += (s, arg) => {
                    gearGroup.Find <ILCamera>().ElementAt(1).CopyFrom(s as ILCamera, false);
                };
                #endregion

                #region left bottom plot
                // start value
                int nrBalls = 10; bool addBalls = true;
                var balls = new ILPoints("balls")
                {
                    Positions = ILMath.tosingle(ILMath.randn(3, nrBalls)),
                    Colors    = ILMath.tosingle(ILMath.rand(3, nrBalls)),
                    Color     = null,
                    Markable  = false
                };
                var leftBottomCam = scene.Add(new ILCamera {
                    ScreenRect = new RectangleF(0, 0.5f, 0.5f, 0.5f),
                    Projection = Projection.Perspective,
                    Children   = { balls }
                });
                // funny label
                string harmony    = @"\color{red}H\color{blue}a\color{green}r\color{yellow}m\color{magenta}o\color{cyan}n\color{black}y\reset
";
                var    ballsLabel = scene.Add(new ILLabel(tag: "harmony")
                {
                    Text     = harmony,
                    Fringe   = { Color = Color.FromArgb(240, 240, 240) },
                    Position = new Vector3(-0.75f, -0.25f, 0)
                });
                long   oldFPS          = 1;
                PointF currentMousePos = new PointF();
                // setup the swarm. Start with a few balls, increase number
                // until framerate drops below 60 fps.
                ILArray <float> velocity = ILMath.tosingle(ILMath.randn(3, nrBalls));
                EventHandler <ILRenderEventArgs> updateBallsRenderFrame = (s, arg) => {
                    // transform viewport coords into 3d scene coords
                    Vector3 mousePos = new Vector3(currentMousePos.X * 2 - 1,
                                                   currentMousePos.Y * -2 + 1, 0);
                    // framerate dropped? -> stop adding balls
                    if (panel.FPS < oldFPS && panel.FPS < 60)
                    {
                        addBalls = false;
                    }
                    oldFPS = panel.FPS;
                    Computation.UpdateBalls(mousePos, balls, velocity, addBalls);
                    // balls buffers have been changed -> must call configure() to publish
                    balls.Configure();
                    // update balls label
                    ballsLabel.Text = harmony + "(" + balls.Positions.DataCount.ToString() + " balls)";
                };

                // saving the mouse position in MouseMove is easier for
                // transforming the coordinates into the viewport
                leftBottomCam.MouseMove += (s, arg) => {
                    // save the mouse position
                    currentMousePos = arg.LocationF;
                };
                panel.BeginRenderFrame += updateBallsRenderFrame;
                m_cleanUpExample        = () => {
                    leftBottomCam.MouseMove -= (s, arg) => {
                        // save the mouse position
                        currentMousePos = arg.LocationF;
                    };
                    panel.BeginRenderFrame -= updateBallsRenderFrame;
                };
                #endregion

                panel.Scene = scene;
            } catch (Exception exc) {
                System.Diagnostics.Trace.WriteLine("ILPanel_Load Error:");
                System.Diagnostics.Trace.WriteLine("====================");
                System.Diagnostics.Trace.WriteLine(exc.ToString());
                MessageBox.Show(exc.ToString());
            }
        }
        /// <summary>
        /// Add new numeric graph(s) of arbitrary (math) type
        /// </summary>
        /// <param name="data">data to be plotted</param>
        /// <param name="properties">determine GraphType</param>
        /// <returns>List with newly created graph(s)</returns>
        public List <ILGraph> Add(ILBaseArray data, GraphType graphType)
        {
            if (!data.IsNumeric)
            {
                throw new ILArgumentException("Add graph: data array must be numeric!");
            }
            List <ILGraph>  ret = new List <ILGraph>();
            ILGraph         newGraph;
            ILArray <float> tmpData;

            lock (this) {
                #region add each graph type seperately
                switch (graphType)
                {
                case GraphType.Plot2D:
                    if (data.IsVector || data.IsScalar)
                    {
                        newGraph = m_graphFact.CreateGraph(data, graphType);
                        Add(newGraph);
                        newGraph.Changed += new ILGraphChangedEvent(GraphChanged);
                        m_clippingData.Update(newGraph.Limits);
                        newGraph.Limits.Changed += new ILClippingDataChangedEvent(Limits_Changed);
                        ret.Add(newGraph);
                    }
                    else if (data.IsMatrix)
                    {
                        // plot columns
                        m_clippingData.EventingSuspend();
                        tmpData = ILMath.tosingle(data);
                        for (int c = 0; c < tmpData.Dimensions[1]; c++)
                        {
                            newGraph = m_graphFact.CreateGraph(tmpData[null, c], graphType);
                            Add(newGraph);
                            newGraph.Changed += new ILGraphChangedEvent(GraphChanged);
                            ret.Add(newGraph);
                            m_clippingData.Update(newGraph.Limits);
                            newGraph.Limits.Changed += new ILClippingDataChangedEvent(Limits_Changed);
                        }
                        m_clippingData.EventingResume();
                    }
                    // trigger change event
                    OnChange(ret[0], GraphCollectionChangeReason.Added, ret[0] as IILPanelConfigurator);
                    break;

                case GraphType.Surf:
                    if (!data.IsMatrix)
                    {
                        throw new ILArgumentException("Surf: source data must be a matrix!");
                    }
                    tmpData = ILMath.tosingle(data);
                    m_clippingData.EventingSuspend();
                    // margin for Z-Direction
                    float min   = tmpData.MinValue;
                    float max   = tmpData.MaxValue;
                    float zmarg = (max - min > 0)? (float)(Math.Abs(max - min) / 10.0) : 0.0f;
                    m_clippingData.Update(new ILPoint3Df(0, 0, min - zmarg), new ILPoint3Df(data.Dimensions[1] - 1, data.Dimensions[0] - 1, max + zmarg));
                    m_clippingData.EventingResume();
                    newGraph = m_graphFact.CreateGraph(tmpData, graphType);
                    Add(newGraph);
                    newGraph.Changed += new ILGraphChangedEvent(GraphChanged);
                    // trigger change event
                    ret.Add(newGraph);
                    OnChange(newGraph, GraphCollectionChangeReason.Added, newGraph as IILPanelConfigurator);
                    break;

                case GraphType.Imagesc:
                    if (!data.IsMatrix)
                    {
                        throw new ILArgumentException("Surf: source data must be a matrix!");
                    }
                    tmpData = ILMath.tosingle(data);
                    // note, ImageSC does not contribute to global clipping, except that the clipping
                    // will be updated to include z = 0!
                    m_clippingData.EventingSuspend();
                    m_clippingData.Update(new ILPoint3Df(-0.5f, -.5f, 0), new ILPoint3Df(data.Dimensions[1] - 0.5f, data.Dimensions[0] - 0.5f, 0));
                    m_clippingData.EventingResume();
                    newGraph = m_graphFact.CreateGraph(tmpData, graphType);
                    Add(newGraph);
                    newGraph.Changed += new ILGraphChangedEvent(GraphChanged);
                    // trigger change event
                    OnChange(newGraph, GraphCollectionChangeReason.Added, newGraph as IILPanelConfigurator);
                    ret.Add(newGraph);
                    break;

                default:
                    throw new ILDrawingException("the type of drawing is not supported!");
                }
                #endregion
            }
            return(ret);
        }
Example #16
0
 /// <summary>
 /// construct new filled graph
 /// </summary>
 /// <param name="panel">panel hosting the graph</param>
 /// <param name="X">X coords, if null, range 0..[cols of Z] will be created</param>
 /// <param name="Y">Y coords, if null, range 0..[rows of Z] will be created</param>
 /// <param name="Z">Z coords (heights)</param>
 /// <param name="C">Colors for Z</param>
 /// <param name="clippingContainer">gloabal limits of panel</param>
 public ILFilledGraph(ILPanel panel, ILBaseArray X, ILBaseArray Y,
                      ILBaseArray Z, ILBaseArray C, ILClippingData clippingContainer)
     : base(panel, clippingContainer)
 {
     #region argument checking
     m_localClipping.EventingSuspend();
     if (Z == null || !Z.IsMatrix)
     {
         throw new ILArgumentException("ILFilledGraph: Z must be matrix!");
     }
     if (!Z.IsNumeric)
     {
         throw new ILArgumentException("ILFilledGraph: Z must be numeric!");
     }
     m_sourceArray = ILMath.tosingle(Z);
     m_rows        = m_sourceArray.Dimensions[0];
     m_cols        = m_sourceArray.Dimensions[1];
     ILArray <float> tmp;
     if (!object.Equals(X, null) && !X.IsEmpty)
     {
         if (!X.IsMatrix || !X.IsNumeric)
         {
             throw new ILArgumentException("ILFilledGraph: X must be numeric matrix!");
         }
         if (X.Dimensions.IsSameSize(Z.Dimensions))
         {
             tmp = ILMath.tosingle(X);
             tmp.ExportValues(ref m_xCoords);
             m_localClipping.XMax = tmp.MaxValue;
             m_localClipping.XMin = tmp.MinValue;
         }
         else
         {
             throw new ILArgumentException("ILFilledGraph: X must be of same size than Z!");
         }
     }
     else
     {
         ILMath.tosingle(ILMath.repmat(ILMath.counter(0.0, 1.0, 1, m_cols), m_rows, 1)).ExportValues(ref m_xCoords);
         m_localClipping.XMin = 0;
         m_localClipping.XMax = m_cols - 1;
     }
     if (!object.Equals(Y, null) && !Y.IsEmpty)
     {
         if (!Y.IsMatrix || !Y.IsNumeric)
         {
             throw new ILArgumentException("ILFilledGraph: Y must be numeric matrix!");
         }
         if (Y.Dimensions.IsSameSize(Z.Dimensions))
         {
             tmp = ILMath.tosingle(Y);
             tmp.ExportValues(ref m_yCoords);
             m_localClipping.YMax = tmp.MaxValue;
             m_localClipping.YMin = tmp.MinValue;
         }
         else
         {
             throw new ILArgumentException("ILFilledGraph: Y must be same size than Z!");
         }
     }
     else
     {
         ILMath.tosingle(ILMath.repmat(ILMath.counter(0.0, 1.0, m_rows, 1), 1, m_cols)).ExportValues(ref m_yCoords);
         m_localClipping.YMax = m_rows - 1;
         m_localClipping.YMin = 0;
     }
     if (object.Equals(C, null) || C.IsEmpty)
     {
         m_colors = null;
     }
     else
     {
         m_colors = ILMath.tosingle(C);
     }
     m_localClipping.ZMax = m_sourceArray.MaxValue;
     m_localClipping.ZMin = m_sourceArray.MinValue;
     #endregion
     m_Vertcount   = m_rows * m_cols;
     m_vertexReady = false;
     m_indexReady  = false;
     // default view properties
     m_opacity            = 1.0f;
     m_wireLines          = new ILLineProperties();
     m_wireLines.Changed += new EventHandler(m_wireLines_Changed);
     m_filled             = true;
     m_localClipping.EventingResume();
 }
Example #17
0
        private void PlotByNodesPoints(
            DenseMatrix dmListOfData,
            Dictionary <string, object> properties,
            string description = "")
        {
            strDataDescription = description;
            ThreadSafeOperations.SetText(lblDescription, strDataDescription, false);

            defaultProperties  = properties;
            strOutputDirectory = (string)defaultProperties["DefaultDataFilesLocation"];
            if (!ServiceTools.CheckIfDirectoryExists(strOutputDirectory))
            {
                strOutputDirectory = "";
            }

            dmDataList = dmListOfData.Copy();
            double dataMaxVal = dmDataList.Column(3).Max();
            double dataMinVal = dmDataList.Column(3).Min();

            ILScene scene = new ILScene();

            currSurfPlotCube          = new ILPlotCube();
            currSurfPlotCube.TwoDMode = false;

            ILArray <float> A =
                ILMath.tosingle((ILArray <double>)(dmDataList.SubMatrix(0, dmDataList.RowCount, 0, 3).ToArray()));

            ILArray <float> colors = ILMath.zeros <float>(4, dmDataList.RowCount);

            ColorScheme newCS = new ColorScheme("");


            double[] dvRvalues = DenseVector.Create(dmDataList.RowCount, (r) =>
            {
                Bgr currColor = newCS.GetColorByValueAndRange(dmDataList[r, 3], dataMinVal, dataMaxVal);
                return(currColor.Red / 255.0d);
            }).ToArray();
            double[] dvGvalues = DenseVector.Create(dmDataList.RowCount, (r) =>
            {
                Bgr currColor = newCS.GetColorByValueAndRange(dmDataList[r, 3], dataMinVal, dataMaxVal);
                return(currColor.Green / 255.0d);
            }).ToArray();
            double[] dvBvalues = DenseVector.Create(dmDataList.RowCount, (r) =>
            {
                Bgr currColor = newCS.GetColorByValueAndRange(dmDataList[r, 3], dataMinVal, dataMaxVal);
                return(currColor.Blue / 255.0d);
            }).ToArray();
            colors["0;:"] = ILMath.tosingle((ILArray <double>)dvRvalues);
            colors["1;:"] = ILMath.tosingle((ILArray <double>)dvGvalues);
            colors["2;:"] = ILMath.tosingle((ILArray <double>)dvBvalues);
            colors["3;:"] = 0.5f;

            ILPoints pts = new ILPoints
            {
                Positions = A,
                Colors    = colors,
            };

            pts.Color = null;
            currSurfPlotCube.Add(pts);

            currSurfPlotCube.Projection = Projection.Orthographic;
            currSurfPlotCube.Rotation   = Matrix4.Rotation(new Vector3(1, 1, 1), 0.5f);
            currSurfPlotCube.Plots.Reset();
            scene.Add(currSurfPlotCube);

            ilPanel1.Scene = scene;
        }
        /// <summary>
        /// update composite shape
        /// </summary>
        /// <param name="X">x coordinates, vector of length <see cref="ILNumerics.Drawing.Shapes.ILShape.VertexCount"/></param>
        /// <param name="Y">y coordinates, vector of length <see cref="ILNumerics.Drawing.Shapes.ILShape.VertexCount"/></param>
        /// <param name="Z">z coordinates, vector of length <see cref="ILNumerics.Drawing.Shapes.ILShape.VertexCount"/></param>
        /// <param name="mapping">Mapping of shapes, composes shapes out of vertices. Matrix having
        /// <see cref="ILNumerics.Drawing.Shapes.ILShape&lt;T>.VerticesPerShape"/> rows.
        /// Every element in a column specifies the index of a vertex according to its position in X,Y,Z.
        /// The <see cref="ILNumerics.Drawing.Shapes.ILShape&lt;T>.VerticesPerShape"/> elements in a column therefore
        /// compose a single shape. Vertices may get used arbitrary times (or not at all). All elements must be
        /// positive integer values in range 0...[<see cref="ILNumerics.Drawing.Shapes.ILShape.VertexCount"/>-1].</param>
        /// <param name="colors">The colors.</param>
        /// <remarks>All vertices of the shape are updated with the data specified in X,Y and Z. Neither the colors or any
        /// other data of vertices are changed. The shape is invalidated for reconfiguration at next redraw. </remarks>
        public void Update(ILBaseArray X, ILBaseArray Y, ILBaseArray Z, ILBaseArray mapping, ILBaseArray colors)
        {
            if (!VertexDefinition.StoresColor)
            {
                throw new NotSupportedException("The underlying vertex type cannot store individual color values! Use another shape or flat shading!");
            }
            if (!X.IsVector || !Y.IsVector || !Z.IsVector || X.Length != Y.Length || Y.Length != Z.Length)
            {
                throw new ILArgumentException("numeric vectors of same length expected for: X, Y and Z");
            }
            if ((colors.Dimensions[1] != 3 && colors.Dimensions[1] != 4) || colors.Length != X.Length)
            {
                throw new ILArgumentException("invalid size of colors data! Colors must have 3 or 4 columns with color components (RGB) or alpha value + color components (ARGB) respectively. Number of rows must match number of vertices.");
            }
            if (mapping == null || mapping.IsEmpty || !mapping.IsMatrix || !mapping.IsNumeric || mapping.Dimensions[0] != VerticesPerShape)
            {
                throw new ILArgumentException("mapping must be a numeric matrix, " + VerticesPerShape.ToString() + " rows, each column specifies indices for the vertices of a single shape.");
            }
            if (mapping is ILArray <int> )
            {
                m_shapeIndices = (mapping as ILArray <int>).C;
            }
            else
            {
                m_shapeIndices = ILMath.toint32(mapping);
            }
            if (m_shapeIndices.MinValue < 0 || m_shapeIndices.MaxValue >= X.Dimensions[1])
            {
                throw new ILArgumentException("invalid mapping: indices must point to existing vertex indices");
            }
            ILArray <float> fX   = ILMath.tosingle(X);
            ILArray <float> fY   = ILMath.tosingle(Y);
            ILArray <float> fZ   = ILMath.tosingle(Z);
            ILArray <byte>  fcol = ILMath.tobyte(colors);

            if (fcol.Dimensions[1] == 3)
            {
                for (int i = 0; i < m_vertices.Length; i++)
                {
                    m_vertices[i].XPosition = fX.GetValue(i);
                    m_vertices[i].YPosition = fY.GetValue(i);
                    m_vertices[i].ZPosition = fZ.GetValue(i);
                    m_vertices[i].Color     = Color.FromArgb(
                        fcol.GetValue(i, 0),
                        fcol.GetValue(i, 1),
                        fcol.GetValue(i, 2));
                }
            }
            else if (fcol.Dimensions[1] == 4)
            {
                for (int i = 0; i < m_vertices.Length; i++)
                {
                    m_vertices[i].XPosition = fX.GetValue(i);
                    m_vertices[i].YPosition = fY.GetValue(i);
                    m_vertices[i].ZPosition = fZ.GetValue(i);
                    m_vertices[i].Color     = Color.FromArgb(
                        fcol.GetValue(i, 1),
                        fcol.GetValue(i, 2),
                        fcol.GetValue(i, 3));
                    m_vertices[i].Alpha = fcol.GetValue(i);
                }
            }
            Invalidate();
        }
Example #19
0
        /// <summary>
        /// run all tests for ILMatFile
        /// </summary>
        public override void Run()
        {
            // tests: creation
            // =================
            Header();
            Test_TestMatlab();
            Test_StreamMatlab("testarray1.mat", ILMath.empty());
            Test_StreamMatlab("testarray1.mat", ILMath.ones(1, 1));
            Test_StreamMatlab("testarray1.mat", ILMath.rand(10, 1));
            Test_StreamMatlab("testarray1.mat", ILMath.rand(1, 10));
            Test_StreamMatlab("testarray1.mat", ILMath.rand(0, 1));
            Test_StreamMatlab("testarray1.mat", ILMath.rand(10, 100, 4));

            Test_StreamMatlab("testarray1.mat", ILMath.tosingle(ILMath.ones(1, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.tosingle(ILMath.empty()));
            Test_StreamMatlab("testarray1.mat", ILMath.tosingle(ILMath.rand(10, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.tosingle(ILMath.rand(1, 10)));
            Test_StreamMatlab("testarray1.mat", ILMath.tosingle(ILMath.rand(0, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.tosingle(ILMath.rand(10, 100, 4)));

            Test_StreamMatlab("testarray1.mat", ILMath.tological(ILMath.ones(1, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.tological(ILMath.empty()));
            Test_StreamMatlab("testarray1.mat", ILMath.tological(ILMath.rand(10, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.tological(ILMath.rand(1, 10)));
            Test_StreamMatlab("testarray1.mat", ILMath.tological(ILMath.rand(0, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.tological(ILMath.rand(10, 100, 4)));

            Test_StreamMatlab("testarray1.mat", new ILArray <complex>(new complex[] { new complex(1.0, 2.0) }));
            Test_StreamMatlab("testarray1.mat", ILMath.tocomplex(ILMath.empty()));
            Test_StreamMatlab("testarray1.mat", ILMath.tocomplex(ILMath.rand(10, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.tocomplex(ILMath.rand(1, 10)));
            Test_StreamMatlab("testarray1.mat", ILMath.tocomplex(ILMath.rand(0, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.tocomplex(ILMath.rand(10, 100, 4)));

            Test_StreamMatlab("testarray1.mat", new ILArray <fcomplex>(new fcomplex[] { new fcomplex(1.0f, 2.0f) }));
            Test_StreamMatlab("testarray1.mat", ILMath.tofcomplex(ILMath.empty()));
            Test_StreamMatlab("testarray1.mat", ILMath.tofcomplex(ILMath.rand(10, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.tofcomplex(ILMath.rand(1, 10)));
            Test_StreamMatlab("testarray1.mat", ILMath.tofcomplex(ILMath.rand(0, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.tofcomplex(ILMath.rand(10, 100, 4)));

            Test_StreamMatlab("testarray1.mat", new ILArray <char>(new char[] { 'A', 'B', 'F' }));
            Test_StreamMatlab("testarray1.mat", new ILArray <char>(new char[] { 'A', 'B', 'F' }).T);
            Test_StreamMatlab("testarray1.mat", ILMath.tochar(ILMath.empty()));
            Test_StreamMatlab("testarray1.mat", ILMath.tochar(ILMath.rand(10, 1) * 250));
            Test_StreamMatlab("testarray1.mat", ILMath.tochar(ILMath.rand(1, 10) * 250));
            Test_StreamMatlab("testarray1.mat", ILMath.tochar(ILMath.rand(0, 1) * 250));
            Test_StreamMatlab("testarray1.mat", ILMath.tochar(ILMath.rand(10, 100, 4) * 250));

            Test_StreamMatlab("testarray1.mat", ILMath.tobyte(ILMath.ones(1, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.tobyte(ILMath.empty()));
            Test_StreamMatlab("testarray1.mat", ILMath.tobyte(ILMath.rand(10, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.tobyte(ILMath.rand(1, 10) * 255));
            Test_StreamMatlab("testarray1.mat", ILMath.tobyte(ILMath.rand(0, 1) * 255));
            Test_StreamMatlab("testarray1.mat", ILMath.tobyte(ILMath.rand(10, 100, 4) * 255));

            Test_StreamMatlab("testarray1.mat", ILMath.toint16(ILMath.ones(1, 1) * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.toint16(ILMath.empty()) * 16000);
            Test_StreamMatlab("testarray1.mat", ILMath.toint16(ILMath.rand(10, 1) * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.toint16(ILMath.rand(1, 10) * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.toint16(ILMath.rand(0, 1) * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.toint16(ILMath.rand(10, 100, 4) * 16000));

            Test_StreamMatlab("testarray1.mat", ILMath.toint32(ILMath.ones(1, 1) * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.toint32(ILMath.empty() * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.toint32(ILMath.rand(10, 1) * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.toint32(ILMath.rand(1, 10) * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.toint32(ILMath.rand(0, 1) * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.toint32(ILMath.rand(10, 100, 4) * 16000));

            Test_StreamMatlab("testarray1.mat", ILMath.touint16(ILMath.ones(1, 1) * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.touint16(ILMath.empty() * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.touint16(ILMath.rand(10, 1) * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.touint16(ILMath.rand(1, 10) * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.touint16(ILMath.rand(0, 1) * 16000));
            Test_StreamMatlab("testarray1.mat", ILMath.touint16(ILMath.rand(10, 100, 4) * 16000));

            Test_StreamMatlab("testarray1.mat", ILMath.touint32(ILMath.ones(1, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.touint32(ILMath.empty()));
            Test_StreamMatlab("testarray1.mat", ILMath.touint32(ILMath.rand(10, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.touint32(ILMath.rand(1, 10)));
            Test_StreamMatlab("testarray1.mat", ILMath.touint32(ILMath.rand(0, 1)));
            Test_StreamMatlab("testarray1.mat", ILMath.touint32(ILMath.rand(10, 100, 4)));
            Test_ImportMatlab2();
            Test_ImportMatlab();
            Test_NameRestrictions();
            // summary
            Footer();
        }