/// <summary> /// Example computing module as private class /// </summary> /// /* * private class Computation : ILMath * { * /// <summary> * /// Create some test data for plotting * /// </summary> * /// <param name="ang">end angle for a spiral</param> * /// <param name="resolution">number of points to plot</param> * /// <returns>3d data matrix for plotting, points in columns</returns> * public static ILRetArray<float> CreateData(int ang, int resolution) * { * using (ILScope.Enter()) * { * ILArray<float> A = linspace<float>(0, ang * pi, resolution); * ILArray<float> Pos = zeros<float>(3, A.S[1]); * Pos["0;:"] = sin(A); * Pos["1;:"] = cos(A); * Pos["2;:"] = A; * return Pos; * } * } * * }*/ /// <summary> /// Plot only function. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnPlot_Click_1(object sender, EventArgs e) { var selectedFuncId = (int)comboFunctions.SelectedValue; if (selectedFuncId == 22) { Plot2D(selectedFuncId); return; } var dim = _benchmark.GetById((int)comboFunctions.SelectedValue).Dimension; _scene = new ILScene() { new ILPlotCube(twoDMode: false) { new ILSurface((x, y) => CallFunction(selectedFuncId, new float[] { x, y }), xmin: dim[0], xmax: dim[1], xlen: LENGTH, ymin: dim[0], ymax: dim[1], ylen: LENGTH, colormap: Colormaps.Cool) { new ILColorbar() } } }; //scene.First<ILPlotCube>().Rotation = Matrix4.Rotation(new Vector3(.8f, .5f, 0), .3f); ilPanel1.Scene = _scene; ilPanel1.Refresh(); }
private void Display(LabelledSeries<Tuple<double, double>>[] dataSeries) { var scene = new ILScene(); if (dataSeries == null) return; var PlotColors = new[] { Color.Blue, Color.Red, Color.Violet, Color.Brown, Color.Green, Color.Gold, Color.Olive }; for (var i = 0; i < dataSeries.Length; i++) { var timeSeriesItem = dataSeries[i]; var colorIndex = i % (PlotColors.Length - 1); var plotColor = PlotColors[colorIndex]; var count = timeSeriesItem.Series.Length; if (count > 0) { var plotCube = new ILPlotCube(); ILArray<float> array = GetMatrix(new[] { timeSeriesItem.Series.Select(s => (float)s.Item1).ToArray(), timeSeriesItem.Series.Select(s => (float)s.Item2).ToArray(), timeSeriesItem.Series.Select(s => (float)0).ToArray() }); plotCube.Add(new ILPoints { Positions = array, Color = plotColor }); scene.Add(plotCube); } } plotter.Scene = scene; plotter.Refresh(); }
public void RepresentDensityField3D() { ILScene scene = new ILScene(); currSurfPlotCube = new ILPlotCube(); currSurfPlotCube.TwoDMode = false; ILInArray <double> ilaDataMeshToShow = dmDensityMesh.ToArray(); ILInArray <double> ilaXvalues = dmDensityMeshXcoord.Row(0).ToArray(); ILInArray <double> ilaYvalues = dmDensityMeshYcoord.Column(0).ToArray(); ILSurface surf = new ILSurface(ilaDataMeshToShow, ilaXvalues, ilaYvalues); surf.UseLighting = true; surf.Colormap = Colormaps.ILNumerics; //surf.Children.Add(new ILColorbar()); currSurfPlotCube.Children.Add(surf); currSurfPlotCube.Rotation = Matrix4.Rotation(new Vector3(1, 0, 0), 1.2f) * Matrix4.Rotation(new Vector3(0, 0, 1), Math.PI); currSurfPlotCube.Projection = Projection.Perspective; scene.Add(currSurfPlotCube); ilPanel1.Scene = scene; }
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 void ilPanel1_Load(object sender, EventArgs e) { var inrows = 0; inrows = inrows + 1; tempX.Add(float.Parse(Gyrox, CultureInfo.InvariantCulture)); tempY.Add(float.Parse(Gyroy, CultureInfo.InvariantCulture)); tempZ.Add(float.Parse(Gyroz, CultureInfo.InvariantCulture)); ILArray <float> datasamples = ILMath.zeros <float>(3, (int)inrows); datasamples["0;:"] = tempX.ToArray(); datasamples["1;:"] = tempY.ToArray(); datasamples["2;:"] = tempZ.ToArray(); tempX.Clear(); tempY.Clear(); tempZ.Clear(); var scene = new ILScene { new ILPlotCube(twoDMode: false) { new ILPoints { Positions = datasamples, Color = Color.Blue, Size = 10 } } }; ilPanel1.Scene = scene; }
private void ilPanel1_Load(object sender, EventArgs e) { var scene = new ILScene(); scene.Camera.Add(new ILPlotCube() { new ILContourLine }); ilPanel1.Scene = scene; }
/// <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; }
public Field3Drepresentation(DenseMatrix dmDataToRepresent, Dictionary <string, object> properties, string description = "") { InitializeComponent(); strDataDescription = description; ThreadSafeOperations.SetText(lblDescription, strDataDescription, false); defaultProperties = properties; strOutputDirectory = (string)defaultProperties["DefaultDataFilesLocation"]; if (!ServiceTools.CheckIfDirectoryExists(strOutputDirectory)) { strOutputDirectory = ""; } dmData = dmDataToRepresent.Copy(); ILScene scene = new ILScene(); currSurfPlotCube = new ILPlotCube(); currSurfPlotCube.TwoDMode = false; ILSurface surf; ILInArray <double> ilaDataMeshToShow = dmData.ToArray(); if ((dmDataXcoord != null) && (dmDataYcoord != null)) { ILInArray <double> ilaXvalues = dmDataXcoord.Row(0).ToArray(); ILInArray <double> ilaYvalues = dmDataYcoord.Column(0).ToArray(); surf = new ILSurface(ilaDataMeshToShow, ilaXvalues, ilaYvalues); } else { surf = new ILSurface(ilaDataMeshToShow); } surf.UseLighting = true; surf.Colormap = Colormaps.ILNumerics; surf.Children.Add(new ILColorbar()); currSurfPlotCube.Children.Add(surf); currSurfPlotCube.Rotation = Matrix4.Rotation(new Vector3(1, 0, 0), 1.2f) * Matrix4.Rotation(new Vector3(0, 0, 1), Math.PI); currSurfPlotCube.Projection = Projection.Perspective; scene.Add(currSurfPlotCube); ilPanel1.Scene = scene; }
public View3DControl() { InitializeComponent(); var cm = new ContextMenu(); cm.MenuItems.Add(new MenuItem("Clear", Clear_Clicked)); this.ilPanel1.ContextMenu = cm; _ILScene = new ILScene(); _PlotCube = new ILPlotCube(twoDMode: false); _ILScene.Add(_PlotCube); ilPanel1.Scene = _ILScene; cmbColorMap.SelectedIndex = 9; checkedListBox1.Items.Clear(); ((ListBox)this.checkedListBox1).DisplayMember = "ID"; cmbColorMap.SelectedIndexChanged += cmbColorMap_SelectedIndexChanged; }
private void btnSaveAsImage_Click(object sender, EventArgs e) { string filename = strOutputDirectory + DateTime.UtcNow.ToString("s").Replace(":", "-") + ".png"; SaveFileDialog dlg = new SaveFileDialog(); dlg.InitialDirectory = strOutputDirectory; dlg.FileName = filename; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { filename = dlg.FileName; } ILScene currScene = ilPanel1.Scene; var drv = new ILGDIDriver(ilPanel1.Width, ilPanel1.Height, currScene); drv.Render(); drv.BackBuffer.Bitmap.Save(filename, System.Drawing.Imaging.ImageFormat.Png); }
protected override Image DoCreateChartImage() { var scene = new ILScene(); var tmpArray = new float[2, Parameters.SeriaData.Count()]; var i = 0; foreach (var item in Parameters.SeriaData) { tmpArray[0, i] = item.Key; tmpArray[1, i] = item.Value; i++; } ILArray<float> data = tmpArray; var cube = new ILPlotCube { AutoScaleOnAdd = true }; cube.Add(new ILLinePlot(data.T)); scene.Add(cube); var driver = new ILGDIDriver(Parameters.ChartWidth, Parameters.ChartHeight, scene, Color.White); driver.Render(); return driver.BackBuffer.Bitmap; }
private void RefreshModel() { Invoke(new Action(() => { scena = new ILScene { new ILPlotCube(twoDMode: false) { surface } }; if (dim == 2) { scena.First <ILPlotCube>().Rotation = Matrix4.Rotation(new Vector3(1, 1, 1), 0.3f); } scena.Screen.First <ILLabel>().Visible = false; ilgraf.Scene = scena; })); }
public Form1() { InitializeComponent(); InitFunctionsComboBox(); _evolveTimer = new Timer { Interval = 100 }; InitEventListeners(); _population = new Population(_functions[(string)functionsComboBox.SelectedItem], maxPopulationCount: 50, dimensions: 2); _plotCube = new ILPlotCube(); var scene = new ILScene { _plotCube }; var panel = new ILPanel { Scene = scene }; renderContainer.Controls.Add(panel); RenderFunction(); }
public void reDraw(float[,] givenLocs) { ILArray<float> ourPositions = givenLocs; var scene = new ILScene(); var plotCube = scene.Add(new ILPlotCube(null,false)); var ourPosBuffer = new ILPoints(); ourPosBuffer.Positions = ourPositions; ourPosBuffer.Size = 5; ourPosBuffer.Color = Color.White; plotCube.Add(ourPosBuffer); plotCube.FieldOfView = 60; plotCube.LookAt = new Vector3(0, 0, 0); plotCube.ScaleModes.XAxisScale = AxisScale.Linear; plotCube.ScaleModes.YAxisScale = AxisScale.Linear; plotCube.ScaleModes.ZAxisScale = AxisScale.Linear; //set label colors. This is all over the place. var xLabel = plotCube.Axes.XAxis.Ticks.DefaultLabel; xLabel.Color = Color.White; var yLabel = plotCube.Axes.YAxis.Ticks.DefaultLabel; yLabel.Color = Color.White; var zLabel = plotCube.Axes.ZAxis.Ticks.DefaultLabel; zLabel.Color = Color.White; plotCube.Axes.XAxis.Label.Color = Color.White; plotCube.Axes.YAxis.Label.Color = Color.White; plotCube.Axes.ZAxis.Label.Color = Color.White; //designed to create a starfield look. iLStarChart.Scene = scene; iLStarChart.BackColor = Color.Black; iLStarChart.ForeColor = Color.White; iLStarChart.Scene.Configure(); }
public Form1() { InitializeComponent(); InitFunctionsComboBox(); _evolveTimer = new Timer { Interval = 100 }; InitEventListeners(); _population = GetPopulation((string)algorithmsComboBox.SelectedItem, (string)functionsComboBox.SelectedItem); _plotCube = new ILPlotCube(); var scene = new ILScene { _plotCube }; var panel = new ILPanel { Scene = scene }; renderContainer.Controls.Add(panel); RenderFunction(); }
private void CreatePlot() { Scene = new ILScene(); Scene.Add(Space = new ILPlotCube(twoDMode: true)); }
private void SetExampleScene(IILPanelForm panel) { if (m_cleanUpExample != null) { m_cleanUpExample(); m_cleanUpExample = null; } 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.Panel.FPS < oldFPS && panel.Panel.FPS < 60) addBalls = false; oldFPS = panel.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.Panel.BeginRenderFrame += updateBallsRenderFrame; m_cleanUpExample = () => { leftBottomCam.MouseMove -= (s, arg) => { // save the mouse position currentMousePos = arg.LocationF; }; panel.Panel.BeginRenderFrame -= updateBallsRenderFrame; }; #endregion panel.Panel.Scene = scene; } catch (Exception exc) { System.Diagnostics.Trace.WriteLine("ILPanel_Load Error:"); System.Diagnostics.Trace.WriteLine("===================="); System.Diagnostics.Trace.WriteLine(exc.ToString()); System.Windows.Forms.MessageBox.Show(exc.ToString()); } }
public MainWindow() { InitializeComponent(); CBMat.ItemsSource = net.matList.Where(mat => mat.Name != ""); Designer.MatList.ItemsSource = net.matList.Where(mat => mat.Name != ""); Designer.TrackNode += Designer_TrackNode; CBMode.Items.Add("Paralelo"); CBMode.Items.Add("Série"); DGMatList.ItemsSource = net.matList; DGMatList.RowEditEnding += DGMatList_RowEditEnding; var scene = new ILScene(); plot = new ILPlotCube(twoDMode: false); scene.Add(plot); var signal = ILMath.ones<float>(10, 10); ILSurface surf = new ILSurface(signal) { Wireframe = { Color = System.Drawing.Color.FromArgb(50, 60, 60, 60) }, Colormap = Colormaps.Jet, }; plot.AllowPan = false; plot.AllowZoom = false; plot.Projection = Projection.Orthographic; plot.Position = new Vector3(1, 3, .5); plot.AllowRotation = false; plot.Add(surf); scene.First<ILPlotCube>().AspectRatioMode = AspectRatioMode.MaintainRatios; scene.First<ILPlotCube>().Rotation = Matrix4.Rotation(new Vector3(0.1, 0, 0), ILMath.pi / 2); ilPanel.Scene.Add(scene); ResultSeeker.ValueChanged += ResultSeeker_ValueChanged; var sceneHx = new ILScene(); plotHx = new ILPlotCube(twoDMode: false); sceneHx.Add(plotHx); var signalHx = ILMath.ones<float>(10, 10); ILSurface surfHx = new ILSurface(signalHx) { Wireframe = { Color = System.Drawing.Color.FromArgb(50, 60, 60, 60) }, Colormap = Colormaps.Jet, }; plotHx.Projection = Projection.Orthographic; plotHx.Position = new Vector3(1, 3, .5); plotHx.AllowRotation = false; plotHx.Add(surfHx); sceneHx.First<ILPlotCube>().AspectRatioMode = AspectRatioMode.MaintainRatios; sceneHx.First<ILPlotCube>().Rotation = Matrix4.Rotation(new Vector3(0.1, 0, 0), ILMath.pi / 2); ilPanelHx.Scene.Add(sceneHx); ResultSeekerHx.ValueChanged += ResultSeekerHx_ValueChanged; var sceneHy = new ILScene(); plotHy = new ILPlotCube(twoDMode: false); sceneHy.Add(plotHy); var signalHy = ILMath.ones<float>(10, 10); ILSurface surfHy = new ILSurface(signalHy) { Wireframe = { Color = System.Drawing.Color.FromArgb(50, 60, 60, 60) }, Colormap = Colormaps.Jet, }; plotHy.Projection = Projection.Orthographic; plotHy.Position = new Vector3(1, 3, .5); plotHy.AllowRotation = false; plotHy.Add(surfHy); sceneHy.First<ILPlotCube>().AspectRatioMode = AspectRatioMode.MaintainRatios; sceneHy.First<ILPlotCube>().Rotation = Matrix4.Rotation(new Vector3(0.1, 0, 0), ILMath.pi / 2); ilPanelHy.Scene.Add(sceneHy); ResultSeekerHy.ValueChanged += ResultSeekerHy_ValueChanged; var sceneHz = new ILScene(); plotHz = new ILPlotCube(twoDMode: false); sceneHz.Add(plotHz); var signalHz = ILMath.ones<float>(10, 10); ILSurface surfHz = new ILSurface(signalHz) { Wireframe = { Color = System.Drawing.Color.FromArgb(50, 60, 60, 60) }, Colormap = Colormaps.Jet, }; plotHz.Projection = Projection.Orthographic; plotHz.Position = new Vector3(1, 3, .5); //plotHz.AllowRotation = false; plotHz.Add(surfHz); sceneHz.First<ILPlotCube>().AspectRatioMode = AspectRatioMode.MaintainRatios; sceneHz.First<ILPlotCube>().Rotation = Matrix4.Rotation(new Vector3(0.1, 0, 0), ILMath.pi / 2); ilPanelHz.Scene.Add(sceneHz); ResultSeekerHz.ValueChanged += ResultSeekerHz_ValueChanged; var sceneEx = new ILScene(); plotEx = new ILPlotCube(twoDMode: false); sceneEx.Add(plotEx); var signalEx = ILMath.ones<float>(10, 10); ILSurface surfEx = new ILSurface(signalEx) { Wireframe = { Color = System.Drawing.Color.FromArgb(50, 60, 60, 60) }, Colormap = Colormaps.Jet, }; plotEx.Projection = Projection.Orthographic; plotEx.Position = new Vector3(1, 3, .5); //plotEx.AllowRotation = false; plotEx.Add(surfEx); sceneEx.First<ILPlotCube>().AspectRatioMode = AspectRatioMode.MaintainRatios; sceneEx.First<ILPlotCube>().Rotation = Matrix4.Rotation(new Vector3(0.1, 0, 0), ILMath.pi / 2); ilPanelEx.Scene.Add(sceneEx); ResultSeekerEx.ValueChanged += ResultSeekerEx_ValueChanged; var sceneEy = new ILScene(); plotEy = new ILPlotCube(twoDMode: false); sceneEy.Add(plotEy); var signalEy = ILMath.ones<float>(10, 10); ILSurface surfEy = new ILSurface(signalEy) { Wireframe = { Color = System.Drawing.Color.FromArgb(50, 60, 60, 60) }, Colormap = Colormaps.Jet, }; plotEy.Projection = Projection.Orthographic; plotEy.Position = new Vector3(1, 3, .5); //plotEy.AllowRotation = false; plotEy.Add(surfEy); sceneHy.First<ILPlotCube>().AspectRatioMode = AspectRatioMode.MaintainRatios; sceneHy.First<ILPlotCube>().Rotation = Matrix4.Rotation(new Vector3(0.1, 0, 0), ILMath.pi / 2); ilPanelEy.Scene.Add(sceneEy); ResultSeekerEy.ValueChanged += ResultSeekerEy_ValueChanged; }
public void SetSurface() { points = new ILPoints(); points.Size = 10; points.Color = null; scene = new ILScene(); plotCube = new ILPlotCube(twoDMode: false); surface = new ILSurface( (x, y) => { return Calculate(new double[] { x, y }); }, xmin: Min, xmax: Max, xlen: 100, ymin: YMin, ymax: YMax, ylen: 100, colormap: Colormaps.ILNumerics ); plotCube.Add(surface); }
public static ILScene Plot(Func <double, double, double> zOfxy, double x0, double xf, double y0, double yf, double pointsPerDimension = 700) { // create some test data (RBF) ILArray <float> Y = 1; double dx = (xf - x0) / pointsPerDimension; double dy = (yf - y0) / pointsPerDimension; ILArray <float> result = ILMath.array <float>(new ILSize(xf, yf)); for (double x = x0; x < xf; x += dx) { for (double y = y0; y < yf; y += dy) { result[x, y] = (float)zOfxy(x, y); } } //ILArray<float> X = ILMath.meshgrid( // ILMath.linspace<float>(-2f, 2f, 100), // ILMath.linspace<float>(-2f, 2f, 100), Y); //Y = X * X; //Y = X * X + Y * Y; //ILArray<float> A = 1 - ILMath.exp(-Y * 2f);Charting.Plot(xyz, 0, 10, 0, 15) // create new scene, add plot cube var scene = new ILScene { new ILPlotCube(twoDMode: false) { // rotate around X axis only Rotation = Matrix4.Rotation(new Vector3(1, 0, 0), 1.1f), // set perspective projection Projection = Projection.Perspective, // add plot cube contents Childs = { // add surface plot, default configuration //new ILSurface(A, 1 - A) { Alpha = 0.9f }, new ILSurface(result) { Alpha = 0.9f }, //new ILSurface(A) { Alpha = 0.9f }, // add contour plot in 3D, configure individual levels //new ILContourPlot(A, new List<ContourLevel> { // new ContourLevel() { Value = 0.8f, LineWidth = 4, ShowLabel = false }, // new ContourLevel() { Value = 0.5f, LineWidth = 4, ShowLabel = false }, // new ContourLevel() { Value = 0.2f, LineWidth = 4, ShowLabel = false, LineColor = 1 }, // new ContourLevel() { Value = 0.02f, LineWidth = 4, ShowLabel = false}, //}, create3D: true), //// add contour plot in 2D, default levels, no labels //new ILContourPlot(1 - A, showLabels: false), //// add legend, label first contour plots levels only //new ILLegend("0.8","0.5","0.2","0.02") { // // move legend to upper right corner // Location = new System.Drawing.PointF(0.97f,0.05f), // Anchor = new System.Drawing.PointF(1,0) //} } } }; return(scene); }
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; }
public Field4Drepresentation( DenseMatrix dmListOfData, Dictionary <string, object> properties, Dictionary <string, int> valuesColumnsIndeces = null, SlicingVariable varSliceBy = SlicingVariable.z, string description = "") { InitializeComponent(); variableSliceBy = varSliceBy; if (valuesColumnsIndeces == null) { valuesColumnsIndeces = new Dictionary <string, int>(); valuesColumnsIndeces.Add("x", 0); valuesColumnsIndeces.Add("y", 1); valuesColumnsIndeces.Add("z", 2); valuesColumnsIndeces.Add("values", 3); } 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; List <List <DenseMatrix> > lDataMatricesForSurfices = ReshapeDataToMatrices(dmDataList, variableSliceBy); foreach (List <DenseMatrix> currSurfMatricesList in lDataMatricesForSurfices) { ILInArray <double> ilaXvalues = currSurfMatricesList[0].ToArray(); ILInArray <double> ilaYvalues = currSurfMatricesList[1].ToArray(); ILInArray <double> ilaZvalues = currSurfMatricesList[2].ToArray(); MathNet.Numerics.LinearAlgebra.Single.DenseMatrix floatDMcolors = MathNet.Numerics.LinearAlgebra.Single.DenseMatrix.Create(currSurfMatricesList[0].RowCount, currSurfMatricesList[0].ColumnCount, 0.0f); currSurfMatricesList[3].MapConvert <Single>(dval => Convert.ToSingle(dval), floatDMcolors, MathNet.Numerics.LinearAlgebra.Zeros.Include); ILInArray <float> ilaForColorValues = floatDMcolors.ToArray(); ILSurface currSurf = new ILSurface(ilaZvalues, ilaXvalues, ilaYvalues); currSurf.ColorMode = ILSurface.ColorModes.RBGA; ColorScheme newCS = new ColorScheme(""); //ColorSchemeRuler newCSR = new ColorSchemeRuler(newCS, dataMinVal, dataMaxVal); double[,] dmRvalues = DenseMatrix.Create(floatDMcolors.RowCount, floatDMcolors.ColumnCount, (r, c) => { Bgr currColor = newCS.GetColorByValueAndRange(currSurfMatricesList[3][r, c], dataMinVal, dataMaxVal); return(currColor.Red / 255.0d); }).ToArray(); double[,] dmGvalues = DenseMatrix.Create(floatDMcolors.RowCount, floatDMcolors.ColumnCount, (r, c) => { Bgr currColor = newCS.GetColorByValueAndRange(currSurfMatricesList[3][r, c], dataMinVal, dataMaxVal); return(currColor.Green / 255.0d); }).ToArray(); double[,] dmBvalues = DenseMatrix.Create(floatDMcolors.RowCount, floatDMcolors.ColumnCount, (r, c) => { Bgr currColor = newCS.GetColorByValueAndRange(currSurfMatricesList[3][r, c], dataMinVal, dataMaxVal); return(currColor.Blue / 255.0d); }).ToArray(); float[, ,] rgbaArrData = new float[4, dmRvalues.GetLength(0), dmRvalues.GetLength(1)]; for (int i = 0; i < dmRvalues.GetLength(0); i++) { for (int j = 0; j < dmRvalues.GetLength(1); j++) { rgbaArrData[0, i, j] = Convert.ToSingle(dmRvalues[i, j]); rgbaArrData[1, i, j] = Convert.ToSingle(dmGvalues[i, j]); rgbaArrData[2, i, j] = Convert.ToSingle(dmBvalues[i, j]); rgbaArrData[3, i, j] = 0.3f; } } currSurf.UpdateRGBA(null, rgbaArrData); currSurf.UseLighting = true; currSurfPlotCube.Children.Add(currSurf); //if (currSurfPlotCube.Children.Count() > 4) //{ // currSurfPlotCube.Children.Add(new ILColorbar()); //} //if (currSurfPlotCube.Children.Count() > 4) //{ // break; //} } // surf.Children.Add(new ILColorbar()); //currSurfPlotCube.Children.Add(new ILColorbar()); //currSurfPlotCube.Rotation = Matrix4.Rotation(new Vector3(1, 0, 0), 1.2f) * // Matrix4.Rotation(new Vector3(0, 0, 1), Math.PI); currSurfPlotCube.Projection = Projection.Orthographic; currSurfPlotCube.Plots.Reset(); scene.Add(currSurfPlotCube); ilPanel1.Scene = scene; }
private void UpdateTrackerPlot() { ilPanelTracker.Scene.Children.Clear(); var scene = new ILScene(); // add plot cube tracker = scene.Add(new ILPlotCube()); // meterialize new colormap ILColormap m = new ILColormap(Colormaps.Lines); //// create a line plot for each entry in the colormap var legendas = tracker.Add( new ILLegend { Location = new PointF(1, 0.02f), Anchor = new PointF(1, 0) }); //foreach (var data in datas) foreach (var node in Designer.TrackingNodes) { double[] data = node.GetAllEZs().ToArray(); ILArray<float> d = ILMath.tosingle((ILArray<double>)data); d = d.Reshape(new int[] { 1, d.Count() }); var lp = tracker.Add(new ILLinePlot(d)); legendas.Items.Add(new ILLegendItem(lp, String.Format("Node: {0}:{1}", node.i, node.j))); //legendas.Add(); } ilPanelTracker.Scene.Add(scene); }
private void PlotByIsolines( 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; List <List <DenseMatrix> > llDataMatricesSlicedByZ = ReshapeDataToMatrices(dmDataList, SlicingVariable.z); DenseMatrix dmXvalues = llDataMatricesSlicedByZ[0][0].Copy(); DenseMatrix dmYvalues = llDataMatricesSlicedByZ[0][1].Copy(); List <List <DataValuesOver3DGrid> > lDataVectorsForSurfices = Group_DVOG_DataByValues(dmDataList); foreach (List <DataValuesOver3DGrid> currSurfVectorsList in lDataVectorsForSurfices) { //ILInArray<float> ilaXvalues = // currSurfVectorsList.ConvertAll<float>(dvog => Convert.ToSingle(dvog.x)).ToArray(); //ILInArray<float> ilaYvalues = // currSurfVectorsList.ConvertAll<float>(dvog => Convert.ToSingle(dvog.y)).ToArray(); //ILInArray<float> ilaZvalues = // currSurfVectorsList.ConvertAll<float>(dvog => Convert.ToSingle(dvog.z)).ToArray(); //ILSurface currSurf = new ILSurface(ilaZvalues, ilaXvalues, ilaYvalues); // не катит - надо, чтобы сетка z была m*n, сетка x = m*[1|n], сетка y - [1|m]*n // поэтому просто список точек, которые должны составить поверхность, - не катят // => или отрисовывать множества точек, без привязки именно к понятию поверхности. Это пока не получилось // => или переформировать список точек так, чтобы они составили m*n поверхность // скомпоновать матрицу значений Z, соответствующих значениям x и y DenseMatrix dmZvalues = DenseMatrix.Create(dmXvalues.RowCount, dmXvalues.ColumnCount, (r, c) => { double x = dmXvalues[r, c]; double y = dmYvalues[r, c]; int idx = currSurfVectorsList.FindIndex(dvog => ((dvog.x == x) && (dvog.y == y))); if (idx == -1) // ничего нужного нет { return(double.NaN); } else { return(currSurfVectorsList[idx].z); } }); ILArray <double> arrXvalues = (ILArray <double>)(dmXvalues.ToArray()); ILArray <double> arrYvalues = (ILArray <double>)(dmYvalues.ToArray()); ILArray <double> arrZvalues = (ILArray <double>)(dmZvalues.ToArray()); // сформируем colors array ColorScheme newCS = new ColorScheme(""); DenseMatrix dmValues = DenseMatrix.Create(dmXvalues.RowCount, dmXvalues.ColumnCount, (r, c) => { double x = dmXvalues[r, c]; double y = dmYvalues[r, c]; int idx = currSurfVectorsList.FindIndex(dvog => ((dvog.x == x) && (dvog.y == y))); if (idx == -1) // ничего нужного нет { return(double.NaN); } else { return(currSurfVectorsList[idx].values[0]); } }); double[,] dmRvalues = DenseMatrix.Create(dmValues.RowCount, dmValues.ColumnCount, (r, c) => { Bgr currColor = newCS.GetColorByValueAndRange(dmValues[r, c], dataMinVal, dataMaxVal); return(currColor.Red / 255.0d); }).ToArray(); double[,] dmGvalues = DenseMatrix.Create(dmValues.RowCount, dmValues.ColumnCount, (r, c) => { Bgr currColor = newCS.GetColorByValueAndRange(dmValues[r, c], dataMinVal, dataMaxVal); return(currColor.Green / 255.0d); }).ToArray(); double[,] dmBvalues = DenseMatrix.Create(dmValues.RowCount, dmValues.ColumnCount, (r, c) => { Bgr currColor = newCS.GetColorByValueAndRange(dmValues[r, c], dataMinVal, dataMaxVal); return(currColor.Blue / 255.0d); }).ToArray(); float[, ,] rgbaArrData = new float[4, dmRvalues.GetLength(0), dmRvalues.GetLength(1)]; for (int i = 0; i < dmRvalues.GetLength(0); i++) { for (int j = 0; j < dmRvalues.GetLength(1); j++) { rgbaArrData[0, i, j] = Convert.ToSingle(dmRvalues[i, j]); rgbaArrData[1, i, j] = Convert.ToSingle(dmGvalues[i, j]); rgbaArrData[2, i, j] = Convert.ToSingle(dmBvalues[i, j]); rgbaArrData[3, i, j] = 0.3f; } } ILSurface currSurf = new ILSurface(ILMath.convert <double, float>(arrZvalues), ILMath.convert <double, float>(arrXvalues), ILMath.convert <double, float>(arrYvalues), rgbaArrData); currSurf.UseLighting = true; currSurfPlotCube.Children.Add(currSurf); } currSurfPlotCube.Projection = Projection.Orthographic; currSurfPlotCube.Plots.Reset(); scene.Add(currSurfPlotCube); ilPanel1.Scene = scene; }
private void RepresentData() { ThreadSafeOperations.SetText(lblFileName, dataFileName, false); ILInArray <double> dataValues = dmDataToShow.ToArray(); ILScene scene = new ILScene(); ILPlotCube currSurfPlotCube = new ILPlotCube(); currSurfPlotCube.TwoDMode = false; ILSurface surf = new ILSurface(dataValues); surf.UseLighting = true; surf.Colormap = Colormaps.Jet; surf.Children.Add(new ILColorbar()); currSurfPlotCube.Children.Add(surf); currSurfPlotCube.Rotation = Matrix4.Rotation(new Vector3(1, 0, 0), 1.2f) * Matrix4.Rotation(new Vector3(0, 0, 1), Math.PI); currSurfPlotCube.Projection = Projection.Perspective; scene.Add(currSurfPlotCube); //scene.First<ILSurface>().MouseClick += (s, arg) => //{ // // we start at the mouse event target -> this will be the // // surface group node (the parent of "Fill" and "Wireframe") // var group = arg.Target.Parent; // if (group != null) // { // // walk up to the next camera node // Matrix4 trans = group.Transform; // while (!(group is ILCamera) && group != null) // { // group = group.Parent; // // collect all nodes on the path up // trans = group.Transform * trans; // } // if (group != null && (group is ILCamera)) // { // // convert args.LocationF to world coords // // The Z coord is not provided by the mouse! -> choose arbitrary value // var pos = new Vector3(arg.LocationF.X * 2 - 1, arg.LocationF.Y * -2 + 1, 0); // // invert the matrix. // trans = Matrix4.Invert(trans); // // trans now converts from the world coord system (at the camera) to // // the local coord system in the 'target' group node (surface). // // In order to transform the mouse (viewport) position, we // // left multiply the transformation matrix. // pos = trans * pos; // // view result in the window title // //Text = "Model Position: " + pos.ToString(); // ThreadSafeOperations.SetText(lblStatus, pos.ToString(), false); // } // } //}; ilPanel1.Scene = scene; }
/// <summary> /// Draws the adjusted function into a two-dimensional grid. /// </summary> private void draw2DShape() { var scene = new ILScene(); // Copying all adjusted expression for further adjustments string[] polishAdjusted = new string[adjustedExpressionTree.Length]; for (int i = 0; i < polishAdjusted.Length; i++) polishAdjusted[i] = String.Copy(adjustedExpressionTree[i]); NumericOption option = currentModel .getNumericOption(firstAxisCombobox.SelectedItem.ToString()); // Replace remaining options with variables and actual values for (int i = 0; i < polishAdjusted.Length; i++) { if (currentModel.getNumericOption(polishAdjusted[i]) != null) { if (polishAdjusted[i].Equals(option.Name)) polishAdjusted[i] = "XY"; else { // All other options will be set on the value they have been set in the // settings option. float value = 0; numericSettings.TryGetValue(currentModel.getNumericOption(polishAdjusted[i]), out value); string[] parts = value.ToString().Split(new char[] {'.', ',' }); if (parts.Length == 1) polishAdjusted[i] = parts[0]; else if (parts.Length == 2) polishAdjusted[i] = parts[0] + "." + parts[1]; else throw new Exception("An illegal number was found!"); } } else if (currentModel.getBinaryOption(polishAdjusted[i]) != null) polishAdjusted[i] = "1.0"; } // Define plot cube ILPlotCube cube = new ILPlotCube(twoDMode: true); cube.Axes.XAxis.Label.Text = option.Name; cube.Axes.YAxis.Label.Text = PERFORMANCE_AXIS_LABEL; // Calculate values for the measurements ILArray<float> XY = Array.ConvertAll(option.getAllValues().ToArray(), x => (float) x); XY = XY.T; XY["0;:"] = XY; XY["1;:"] = calculateFunction(polishAdjusted, new string[] { "XY" }, new ILArray<float>[] { XY }); // Adding interactive points to the cube for (int i = 0; i < XY.Size[1]; i++) { ILPoints point = createPoint(XY[0, i], XY[1, i], 0, pointPositionLabel); // Adding events to the point to display its coordinates on the screen point.MouseMove += (s, a) => { Vector3 coor = point.GetPosition(); pointPositionLabel.Text = option.Name + ": " + coor.X.ToString() + ", " + PERFORMANCE_AXIS_LABEL + ": " + coor.Y.ToString(); pointPositionLabel.Visible = true; }; cube.Add(point); } calculatedPerformances = ILMath.zeros<float>(0, 0); for (int i = 0; i < XY.Size[0]; i++) for (int j = 0; j < XY.Size[1]; j++) calculatedPerformances[i, j] = XY[i, j]; // Calculated values for the plot XY = ILMath.linspace<float>(option.Min_value, option.Max_value, 50); XY["0;:"] = XY; XY["1;:"] = calculateFunction(polishAdjusted, new string[] { "XY" }, new ILArray<float>[] { XY }); // Adding a lineplot to the cube ILLinePlot linePlot = new ILLinePlot(XY) { Line = { Color = calculatedColor } }; cube.Add(linePlot); ilFunctionPanel.Scene = new ILScene() { cube }; // Saving the coordinates/values of the points for the measurements drawnPerformances = XY; }
private void StartBtn_Click(object sender, EventArgs e) { //string f = FunctionSelectionCombo.SelectedItem.ToString(); //if (!String.IsNullOrEmpty(funkcja)&&!funkcja.Equals("Proszę wybrać funkcję do optymalizacji")) //{ // ileCzastek = Convert.ToInt16(ParticleQuantityUpDown.Value); // maxEpochs = Convert.ToInt16(MaxEpochUpDown.Value); // optymalizacja = new PSO(dziedzinyFunkcji[funkcja], ileCzastek, maxEpochs, funkcja); // MessageBox.Show(string.Format("Znalezione minimum to {0} z błędem {1}", PSO.PSOSolution().Item1, PSO.PSOSolution().Item2),"Rezultat optymalizacji",MessageBoxButtons.OK,MessageBoxIcon.Information); // } // else MessageBox.Show("Nie wybrano funkcji do optymalizacji","BŁĄD!",MessageBoxButtons.OK,MessageBoxIcon.Error); // instrukcja do przycisku start List <Populacja> tmp = new PSO(numberIterations, inertiaw, c1, c2, r1r2, linearinertia).PSOALG(population); this.functionButtonSet(false); animace = new Thread(ShowParticleMove); animace.IsBackground = true; animace.Start(tmp); if (thesame == true) { resetB.Enabled = true; } double[] tab = new double[testnumber]; float[] sum = new float[numberIterations]; float[] best = new float[numberIterations]; float[] worst = new float[numberIterations]; float[] bgfworst = new float[numberIterations]; float[] bgfbest = new float[numberIterations]; float[] bgfav = new float[numberIterations]; float[] globalmin = new float[testnumber]; double wynik = 0; double bestresult = 0; double worstresult = 0; double percentsucess = 0; double tmpbest = 0; double tmpworst = 0; for (int i = 0; i < testnumber; ++i) { population = new Populacja(PopulationSize, dim, Funkcje.FunctionName.type); population.SetRangeOfPopulation(Funkcje.FunctionName.type, error); population.GeneratePopulation(dim); population.ObliczPopulFitness(Funkcje.FunctionName.type); //List<Populacja> tmp = new PSO(numberIterations, inertiaw, c1, c2, r1r2, linearinertia).PSOALG(population);//numberIterations, inertiaw tmp.Remove(tmp.Last()); tab[i] = tmp.Min((x => x.NajlepszaFitness)); //tablica wartości wyników-z tego obliczyc % sukcesów wynik += tab[i]; globalmin[i] = (float)tmp.Min((x => x.NajlepszaFitness)); if (Math.Abs(tab[i] - tmp.First().min) < tmp.First().exitError) { percentsucess++; } if (i == 0) { tmpbest = tab[i]; tmpworst = tab[i]; } int popnumber = 0; foreach (Populacja pop in tmp) { float b = 0; float c = 0; bgfav[popnumber] += (float)pop.NajlepszaFitness / testnumber; var scene = new ILScene(); scene.Screen.First <ILLabel>().Visible = false; foreach (Particle item in pop.population) { // MessageBox.Show(a.Length.ToString()+" " +tmp.populationSize.ToString()); b += (float)item.fitnessValue; } c = (b / pop.population.Count) / testnumber; sum[popnumber] += c; if (tab[i] <= tmpbest) { best[popnumber] = b / pop.population.Count; bgfbest[popnumber] = (float)pop.NajlepszaFitness; bestresult = pop.NajlepszaFitness; tmpbest = tab[i]; } if (tab[i] >= tmpworst) { worst[popnumber] = b / pop.population.Count; bgfworst[popnumber] = (float)pop.NajlepszaFitness; worstresult = pop.NajlepszaFitness; tmpworst = tab[i]; } popnumber++; } } frm.richTextBox1.AppendText("Średnie wartości funkci: " + wynik / testnumber + "\n" + "\n"); frm.richTextBox1.AppendText("Najlepsza wartość funkcji: " + bestresult + "\n" + "\n"); frm.richTextBox1.AppendText("Najgorsza wartość funkcji: " + worstresult + "\n" + "\n"); frm.richTextBox1.AppendText("Procent sukcesu: " + percentsucess / testnumber * 100 + "%" + "\n" + "\n"); var scena = new ILScene(); using (ILScope.Enter()) { ILArray <float> AV = sum; ILArray <float> BEST = best; ILArray <float> WORST = worst; ILArray <float> BGFworst = bgfworst; ILArray <float> BGFbest = bgfbest; ILArray <float> BGFav = bgfav; ILArray <float> GLOBAL = globalmin; var plot = scena.Add(new ILPlotCube() { ScreenRect = new RectangleF(0, 0, 1, 0.4f), Children = { new ILLinePlot(AV.T, lineColor:Color.Yellow), new ILLinePlot(BEST.T, lineColor:Color.Blue), new ILLinePlot(WORST.T, lineColor:Color.Red), } }); var plot1 = scena.Add(new ILPlotCube() { ScreenRect = new RectangleF(0, 0.33f, 1, 0.4f), Children = { new ILLinePlot(BGFav.T, lineColor:Color.Yellow), new ILLinePlot(BGFbest.T, lineColor:Color.Blue), new ILLinePlot(BGFworst.T, lineColor:Color.Red), }, }); var plot2 = scena.Add(new ILPlotCube() { ScreenRect = new RectangleF(0, 0.66f, 1, 0.3f), Children = { new ILLinePlot(GLOBAL.T, markerStyle: MarkerStyle.Diamond, lineColor: Color.Black) }, }); var dg2 = plot2.AddDataGroup(); dg2.Add(new ILLinePlot(GLOBAL.T, markerStyle: MarkerStyle.Diamond, lineColor: Color.Red));//,lineColor: Color.Red)); dg2.ScaleModes.YAxisScale = AxisScale.Logarithmic; var axisY2 = plot2.Axes.Add(new ILAxis(dg2) { AxisName = AxisNames.YAxis, Position = new Vector3(1, 0, 0), Label = { Text = "osiągnięte minimum (log)", Color = Color.Red }, Ticks = { DefaultLabel = { Color = Color.Red } } }); frm.ilgraf.Scene = scena; frm.Show(); } }
/// <summary> /// Draws the adjusted function into a three-dimencional grid. /// </summary> private void draw3DShape() { var scene = new ILScene(); // Copying all adjusted expression for further adjustments string[] polishAdjusted = new string[adjustedExpressionTree.Length]; for (int i = 0; i < polishAdjusted.Length; i++) polishAdjusted[i] = String.Copy(adjustedExpressionTree[i]); // Getting selected options for axes NumericOption firstOption = currentModel.getNumericOption(firstAxisCombobox.SelectedItem.ToString()); NumericOption secondOption = currentModel.getNumericOption(secondAxisCombobox.SelectedItem.ToString()); // Replace remaining options with variables and actual values for (int i = 0; i < polishAdjusted.Length; i++) { if (currentModel.getNumericOption(polishAdjusted[i]) != null) { if (polishAdjusted[i].Equals(firstOption.Name)) polishAdjusted[i] = "XMat"; else if (polishAdjusted[i].Equals(secondOption.Name)) polishAdjusted[i] = "YMat"; else { // All other options will be set on the value they have been set in the // settings option. NumericOption option = currentModel.getNumericOption(polishAdjusted[i]); float value = 0; numericSettings.TryGetValue(option, out value); string[] parts = value.ToString().Split(new char[] { '.', ',' }); if (parts.Length == 1) polishAdjusted[i] = parts[0]; else if (parts.Length == 2) polishAdjusted[i] = parts[0] + "." + parts[1]; else throw new Exception("An illegal number was found!"); } } else if (currentModel.getBinaryOption(polishAdjusted[i]) != null) polishAdjusted[i] = "1.0"; } // Define the ranges of the axes ILArray<float> X, Y, A; ILPlotCube cube = new ILPlotCube(twoDMode: false); cube.Axes.XAxis.Label.Text = firstOption.Name; cube.Axes.YAxis.Label.Text = secondOption.Name; cube.Axes.ZAxis.Label.Text = PERFORMANCE_AXIS_LABEL; // Calculating the surface X = Array.ConvertAll(firstOption.getAllValues().ToArray(), x => (float)x); Y = Array.ConvertAll(secondOption.getAllValues().ToArray(), y => (float)y); ILArray<float> XMat = 1; ILArray<float> YMat = ILMath.meshgrid(Y, X, XMat); A = ILMath.zeros<float>(X.Length, Y.Length, 3); // Fill array with values A[":;:;0"] = calculateFunction(polishAdjusted, new string[] { "XMat", "YMat" }, new ILArray<float>[] { XMat, YMat }); A[":;:;1"] = XMat; A[":;:;2"] = YMat; cube.Add(new ILSurface(A)); calculatedPerformances = ILMath.zeros<float>(0, 0, 0); // Saving the coordinates/values of the points for the measurements for (int i = 0; i < A.Size[0]; i++) for (int j = 0; j < A.Size[1]; j++) for (int k = 0; k < A.Size[2]; k++) calculatedPerformances[i, j, k] = A[i, j, k]; // Calculating the points on the surface X = X.T; Y = Y.T; XMat = 1; YMat = ILMath.meshgrid(Y, X, XMat); ILArray<float> resultArray = calculateFunction(polishAdjusted, new string[] { "XMat", "YMat" }, new ILArray<float>[] { XMat, YMat }).GetArrayForRead(); ILArray<float> xArray = XMat.GetArrayForRead(); ILArray<float> yArray = YMat.GetArrayForRead(); // Fill array with values A = ILMath.zeros<float>(3, resultArray.Length); A["0;:"] = xArray.T; A["1;:"] = yArray.T; A["2;:"] = resultArray.T; for (int i = 0; i < A.Size[1]; i++) { ILPoints point = createPoint(A[0, i], A[1, i], A[2, i], pointPositionLabel); // Adding events to the point to display its coordinates on the screen point.MouseMove += (s, a) => { Vector3 coor = point.GetPosition(); pointPositionLabel.Text = firstOption.Name + ": " + coor.X.ToString() + ", " + secondOption.Name + ": " + coor.Y.ToString() + ", " + PERFORMANCE_AXIS_LABEL + ": " + coor.Z.ToString(); pointPositionLabel.Visible = true; }; cube.Add(point); } ilFunctionPanel.Scene = new ILScene() { cube }; }
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()); } }
public static void Plot(this ILPanel panel, Lib.func f, float min, float max, float step, bool refresh=true) { ILScene scene = null; //bool resetcam=false; Matrix4 rotation = default(Matrix4); try { rotation = panel.GetCurrentScene().First<ILPlotCube>().Rotation; } catch { rotation = Matrix4.Rotation(new Vector3(2, 0.55, 0.64), Math.PI / 2); } //if (panel.Scene.First<ILPlotCube>() == null) // resetcam = true; //else // rotation = panel.Scene.First<ILPlotCube>().Rotation; // setup the scene + plot cube + surface scene = new ILScene() { new ILPlotCube(twoDMode: false) { new ILSurface(new Func<float,float,float>(f.Encapsulation3D), min, max, (int)((max-min)*step+1), min, max, (int)((max-min)*step+1), colormap: Colormaps.Hsv) { UseLighting = true, }, } }; panel.Scene = scene; //if (resetcam) // panel.ResetCamera(refresh); panel.ResetCamera(rotation, refresh); }