Beispiel #1
0
        private void DrawCurveGraph()
        {
            GraphPane myPane = zedGraphControl1.GraphPane;

            myPane.CurveList.Clear();
            myPane.GraphObjList.Clear();
            zedGraphControl1.RestoreScale(zedGraphControl1.GraphPane);



            m_dBaseAlt = System.Convert.ToDouble(textBoxBaseAlt.Text);



            myPane.Legend.IsVisible = false;



            PointPairList listHLAbove = new PointPairList();
            PointPairList listAbove   = new PointPairList();
            PointPairList listHLBelow = new PointPairList();
            PointPairList listBelow   = new PointPairList();
            PointPairList listEqual   = new PointPairList();
            PointPairList listBase    = new PointPairList();

            ArrayList arryHLAbove = new ArrayList();
            ArrayList arryHLBelow = new ArrayList();

            ArrayList arryAbove = new ArrayList();
            ArrayList arryBelow = new ArrayList();



            int    nPointCount = m_pnt3ds.Count;
            double dOneSegLen  = m_dXTotalLength / (nPointCount - 1);



            int nSegmentType = -1; //0=m_dBaseAlt,1=above,2=below

            for (int i = 0; i < m_pnt3ds.Count; i++)
            {
                double x = i * dOneSegLen;
                double y = (int)(Math.Round(m_pnt3ds[i].Z * 100)) / 100.0; // 精确到厘米就行了

                if (y > m_dBaseAlt)
                {
                    // 如果当前段是基准线下面的段
                    if (nSegmentType == 2)
                    {
                        arryHLBelow.Add(listHLBelow);
                        arryBelow.Add(listBelow);
                        listHLBelow = new PointPairList();
                        listBelow   = new PointPairList();
                    }
                    nSegmentType = 1;
                    listAbove.Add(x, y);
                    listHLAbove.Add(x, y, m_dBaseAlt);
                }
                else if (y < m_dBaseAlt)
                {
                    if (nSegmentType == 1)
                    {
                        arryHLAbove.Add(listHLAbove);
                        arryAbove.Add(listAbove);
                        listHLAbove = new PointPairList();
                        listAbove   = new PointPairList();
                    }
                    nSegmentType = 2;
                    listBelow.Add(x, y);
                    listHLBelow.Add(x, m_dBaseAlt, y);
                }
                else
                {
                    if (nSegmentType == 2)
                    {
                        arryHLBelow.Add(listHLBelow);
                        arryBelow.Add(listBelow);
                        listHLBelow = new PointPairList();
                        listBelow   = new PointPairList();
                    }
                    else if (nSegmentType == 1)
                    {
                        arryHLAbove.Add(listHLAbove);
                        arryAbove.Add(listAbove);
                        listHLAbove = new PointPairList();
                        listAbove   = new PointPairList();
                    }
                    nSegmentType = 0;
                    listEqual.Add(x, y, m_dBaseAlt);
                }
            }

            if (nSegmentType == 2)
            {
                arryHLBelow.Add(listHLBelow);
                arryBelow.Add(listBelow);
            }
            else if (nSegmentType == 1)
            {
                arryHLAbove.Add(listHLAbove);
                arryAbove.Add(listAbove);
            }


            listBase.Add(0, m_dBaseAlt);
            listBase.Add(m_dXTotalLength, m_dBaseAlt);


            LineItem myCurveBase = myPane.AddCurve("基线剖面", listBase, Color.Blue, SymbolType.None);

            myCurveBase.Line.IsAntiAlias = true;
            myCurveBase.Line.Width       = 2;


            int k = 0;

            for (k = 0; k < arryHLAbove.Count; k++)
            {
                LineItem myCurveAbove = myPane.AddCurve("高于基线剖面", (PointPairList)arryAbove[k], Color.Red, SymbolType.None);
                myCurveAbove.Line.IsAntiAlias = true;
                myCurveAbove.Line.Width       = 2;
                myCurveAbove.Line.IsSmooth    = true;


                HiLowBarItem hlAboveItem = myPane.AddHiLowBar("高于基线", (PointPairList)arryHLAbove[k], Color.Red);
                hlAboveItem.Bar.Border.Color = Color.Red;
            }
            for (k = 0; k < arryHLBelow.Count; k++)
            {
                LineItem myCurveBelow = myPane.AddCurve("低于基线剖面", (PointPairList)arryBelow[k], Color.Green, SymbolType.None);
                myCurveBelow.Line.IsAntiAlias = true;
                myCurveBelow.Line.Width       = 2;
                myCurveBelow.Line.IsSmooth    = true;

                HiLowBarItem hlBolowItem = myPane.AddHiLowBar("低于基线", (PointPairList)arryHLBelow[k], Color.Green);
                hlBolowItem.Bar.Border.Color = Color.Green;
            }


            /*
             *
             * LineItem myCurveAbove = myPane.AddCurve("高于基线剖面", listAbove, Color.Red, SymbolType.None);
             * //myCurve.Symbol.Fill = new Fill(Color.White);
             * myCurveAbove.Line.IsAntiAlias = true;
             * myCurveAbove.Line.Width = 2;
             * myCurveAbove.Line.IsSmooth = true;
             *
             *
             *
             *
             * // myCurveAbove.Line.Fill = new Fill(Color.Yellow, Color.LightGray, 45.0f);
             *
             *
             * LineItem myCurveBelow = myPane.AddCurve("低于基线剖面", listBelow, Color.Blue, SymbolType.None);
             * //myCurve.Symbol.Fill = new Fill(Color.White);
             * myCurveBelow.Line.IsAntiAlias = true;
             * myCurveBelow.Line.Width = 2;
             * myCurveBelow.Line.IsSmooth = true;
             *
             *
             * //myCurveBelow.Line.Fill = new Fill(Color.Yellow, Color.LightGray, 45.0f);
             *
             *
             * LineItem myCurveEqual = myPane.AddCurve("等于基线剖面", listEqual, Color.DarkOrange, SymbolType.None);
             * //myCurve.Symbol.Fill = new Fill(Color.White);
             * myCurveEqual.Line.IsAntiAlias = true;
             * myCurveEqual.Line.Width = 2;
             * //myCurveEqual.Line.Fill = new Fill(Color.Yellow, Color.LightGray, 45.0f);
             *
             *
             * // LineItem myCurveBase = myPane.AddCurve("基线剖面", listBase, Color.Green, SymbolType.None);
             * //myCurveBase.Line.IsAntiAlias = true;
             * //myCurveBase.Line.Width = 2;
             * */



            // Show the x axis grid
            myPane.XAxis.MajorGrid.IsVisible  = true;
            myPane.XAxis.IsAxisSegmentVisible = true;

            if (m_bSetMinX)
            {
                myPane.XAxis.Scale.Min = 0;
            }


            if (m_bSetMinY)
            {
                myPane.YAxis.Scale.Min = m_pntMin.Z;
            }


            //myPane.XAxis.Scale.Min = 0;

            myPane.YAxis.MajorGrid.IsVisible = true;
            // Don't display the Y zero line
            myPane.YAxis.MajorGrid.IsZeroLine = false;
            // Align the Y axis labels so they are flush to the axis
            myPane.YAxis.Scale.Align = AlignP.Inside;
            // Manually set the axis range
            //myPane.YAxis.Scale.Min = -1000;
            // myPane.YAxis.Scale.Max = 1000;


            // Fill the axis background with a gradient
            myPane.Chart.Fill = new Fill(Color.White, Color.LightGray, 45.0f);


            // Enable scrollbars if needed
            //zedGraphControl1.IsShowHScrollBar = true;
            //zedGraphControl1.IsShowVScrollBar = true;
            zedGraphControl1.IsAutoScrollRange = true;


            // OPTIONAL: Show tooltips when the mouse hovers over a point
            zedGraphControl1.IsShowPointValues = true;
            zedGraphControl1.PointValueEvent  += new ZedGraphControl.PointValueHandler(MyPointValueHandler);


            // OPTIONAL: Handle the Zoom Event
            zedGraphControl1.ZoomEvent += new ZedGraphControl.ZoomEventHandler(MyZoomEvent);

            zedGraphControl1.AxisChange();

            if (m_bXYSameScale)
            {
                graphPane_AxisChangeEvent();
            }
            // Make sure the Graph gets redrawn
            zedGraphControl1.Invalidate();
        }
Beispiel #2
0
        private void drawtempline(string name, int ID)
        {
            string    sql = "select dt,GT1,BT1,GT2,BT2,GTB2,OT,WI1,OD from tblGRData where DeviceID =" + ID + " and dt>='" + this.dateTimePicker4.Value.ToString() + "' and dt<'" + dateTimePicker3.Value.ToString() + "' order by dt ";
            DataTable dt  = Tool.DB.getDt(sql);

            PointPairList list1 = new PointPairList();
            PointPairList list2 = new PointPairList();
            PointPairList list3 = new PointPairList();
            PointPairList list4 = new PointPairList();
            PointPairList list5 = new PointPairList();
            PointPairList list6 = new PointPairList();
            PointPairList list7 = new PointPairList();
            PointPairList list8 = new PointPairList();

            for (int j = 0; j < dt.Rows.Count; j++)
            {
                DateTime time = (DateTime)dt.Rows[j][0];
                double   x    = new XDate(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second);
                double   y    = Convert.ToDouble(dt.Rows[j][1]);
                list1.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][2]);
                list2.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][3]);
                list3.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][4]);
                list4.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][5]);
                list5.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][6]);
                list6.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][7]);
                list7.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][8]);
                list8.Add(x, y);
            }

            GraphPane myPane = zedGraphControl3.GraphPane;

            myPane.CurveList.Clear();
            this.zedGraphControl3.ZoomOutAll(myPane);
            myPane.Title.Text                = name + " " + dateTimePicker4.Value.ToString() + " 至 " + dateTimePicker3.Value.ToString() + " 温度曲线";
            myPane.XAxis.Title.Text          = "时间(h)";
            myPane.YAxis.Title.Text          = "温度(℃)";
            myPane.XAxis.Type                = AxisType.Date;
            myPane.XAxis.MajorGrid.IsVisible = true;  //珊格子
            myPane.YAxis.MajorGrid.IsVisible = true;
            myPane.XAxis.Scale.Format        = "MM/dd HH:mm";

            LineItem myCurve1 = null;

            if (checkBox2.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("一次供温℃", list1, panel3.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox10.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("一次回温℃", list2, panel20.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox12.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("二次供温℃", list3, panel24.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox11.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("二次回温℃", list4, panel26.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox9.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("供温基准℃", list5, panel22.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox1.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("室外温度℃", list6, panel18.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox14.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("一次流量m3/h", list7, panel29.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox18.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("阀位反馈%", list8, panel37.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (myCurve1 == null)
            {
                MessageBox.Show("请选择某条曲线!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                return;
            }

            zedGraphControl3.IsShowPointValues = true;
            zedGraphControl3.PointValueEvent  += new ZedGraphControl.PointValueHandler(MyPointValueHandler);

            zedGraphControl3.AxisChange();
            zedGraphControl3.Invalidate();
        }
        protected void addAverageCurve(GraphPane pane)
        {
            LineItem curve = pane.AddCurve(averageResult.title, averageResult, Color.Red, SymbolType.None);

            curve.Line.Width = 2;
        }
Beispiel #4
0
        private void button9_Click(object sender, EventArgs e)
        {
            if (building == "")
            {
                sql = "select count(*) from student_indor";
            }
            else
            {
                sql = String.Format("select count(*) from student_indor where building='{0}'", building);
            }
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                conn.Open();                                //打开数据库                    
                SqlDataReader reader = cmd.ExecuteReader(); //执行sql语句 
                while (reader.Read())
                {
                    textBox10.Text = String.Format("{0}", reader[0]);
                }
                reader.Close();
                conn.Close();//关闭数据库                     
            }

            if (building == "")
            {
                sql = "select count(*) from visitor";
            }
            else
            {
                sql = String.Format("select count(*) from visitor where vbuilding='{0}'", building);
            }

            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                conn.Open();                                //打开数据库                    
                SqlDataReader reader = cmd.ExecuteReader(); //执行sql语句 
                while (reader.Read())
                {
                    textBox11.Text = String.Format("{0}", reader[0]);
                }
                reader.Close();
                conn.Close();//关闭数据库                     
            }

            string now   = DateTime.Now.ToShortDateString();
            string start = Convert.ToDateTime(now).ToString("yyyy-MM-01");

            if (building == "")
            {
                sql = String.Format("select count(*) from visitor where vtime between '{0}'and'{1}'", start, now);
            }
            else
            {
                sql = String.Format("select count(*) from visitor where vbuilding='{0}' and vtime between '{1}'and'{2}'", building, start, now);
            }
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                conn.Open();                                //打开数据库                    
                SqlDataReader reader = cmd.ExecuteReader(); //执行sql语句 
                while (reader.Read())
                {
                    textBox12.Text = String.Format("{0}", reader[0]);
                }
                reader.Close();
                conn.Close();//关闭数据库                     
            }


            // get a reference to the GraphPane
            GraphPane myPane1 = zgc1.GraphPane;

            // Set the Titles
            myPane1.Title.Text       = "visit of this year";
            myPane1.XAxis.Title.Text = "month";
            myPane1.YAxis.Title.Text = "total visit";

            // Make up some data arrays based on the Sine function
            double        x;
            double        y;
            PointPairList list1 = new PointPairList();

            myPane1.XAxis.Scale.Min           = 1;
            myPane1.XAxis.Scale.Max           = 12;  //http://www.cnblogs.com/gywei/p/3340827.html
            myPane1.XAxis.Scale.MajorStepAuto = true;
            string month = DateTime.Now.Year.ToString() + "-01-01";
            int    i     = 1;
            string monthend;
            string end = DateTime.Now.AddMonths(1).ToString("yyyy-MM-01");

            while (month != end)
            {
                x = i;
                if (i != 12)
                {
                    monthend = String.Format("{0:D2}-{1:D2}-01", DateTime.Now.Year.ToString(), i + 1);
                }
                else
                {
                    monthend = DateTime.Now.AddMonths(1).ToString("yyyy-MM-01");
                }

                if (building == "")
                {
                    sql = String.Format("select count(*) from visitor where vtime between'{0}'and'{1}'", month, monthend);
                }
                else
                {
                    sql = String.Format("select count(*) from visitor where vbuilding='{0}' and vtime between'{1}'and'{2}' ", building, month, monthend);
                }

                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    conn.Open();             
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        y = double.Parse(String.Format("{0}", reader[0]));
                        list1.Add(x, y);
                        Console.WriteLine(sql);
                        Console.WriteLine(x);
                        Console.WriteLine(y);
                    }
                    reader.Close();
                    conn.Close();              
                }
                i++;
                month = monthend;
            }
                
            LineItem myCurve = myPane1.AddCurve("", list1, Color.Blue, SymbolType.Circle);

            zgc1.AxisChange();
            zgc1.Invalidate(); //update the graph
        }
Beispiel #5
0
        private void GenerateGraphUserAgent1()
        {
            GraphPane pane = zedUserAgent1.GraphPane;

            pane.CurveList.Clear();

            if (cboReport.SelectedIndex == 0)
            {
                pane.Title.Text         = String.Format("Total Hist/Month by User Agent for Year {0} Graph", cboParams.SelectedValue);
                pane.XAxis.Type         = AxisType.DateAsOrdinal;
                pane.XAxis.Scale.Format = "MMM-yyyy";
            }
            else
            {
                pane.Title.Text         = String.Format("Total Hist/Day by User Agent for {0} Graph", cboParams.SelectedValue);
                pane.XAxis.Type         = AxisType.DateAsOrdinal;
                pane.XAxis.Scale.Format = "MMM-dd-yyyy";
            }

            pane.XAxis.Title.Text = "Time";
            pane.YAxis.Title.Text = "Total Hits";
            pane.Legend.Position  = LegendPos.Bottom;
            pane.Chart.Fill       = new Fill(Color.White, Color.SkyBlue, 90F);
            pane.Fill             = new Fill(Color.FromArgb(250, 250, 255));

            if (_listAgentData.Count > 0)
            {
                double x;
                Dictionary <string, PointPairList> list = new Dictionary <string, PointPairList>();

                if (cboReport.SelectedIndex == 0)
                {
                    int year = Convert.ToInt32(cboParams.SelectedItem);
                    for (int i = 0; i < _listAgentData.Count; i++)
                    {
                        DateTime date = new DateTime(year, _listAgentData[i].Month, 1);
                        x = date.ToOADate();

                        if (!list.ContainsKey(_listAgentData[i].User_Agent))
                        {
                            PointPairList tmp = new PointPairList();
                            tmp.Add(x, Convert.ToDouble(_listAgentData[i].Total));
                            list.Add(_listAgentData[i].User_Agent, tmp);
                        }
                        else
                        {
                            list[_listAgentData[i].User_Agent].Add(x, Convert.ToDouble(_listAgentData[i].Total));
                        }
                    }
                }
                else
                {
                    string   itm  = cboParams.SelectedItem.ToString();
                    string[] ls   = itm.Split(new char[] { '-' });
                    int      year = Convert.ToInt32(ls[1]);
                    for (int i = 0; i < _listAgentData.Count; i++)
                    {
                        DateTime date = new DateTime(year, _listAgentData[i].Month, _listAgentData[i].Day);
                        x = date.ToOADate();

                        if (!list.ContainsKey(_listAgentData[i].User_Agent))
                        {
                            PointPairList tmp = new PointPairList();
                            tmp.Add(x, Convert.ToDouble(_listAgentData[i].Total));
                            list.Add(_listAgentData[i].User_Agent, tmp);
                        }
                        else
                        {
                            list[_listAgentData[i].User_Agent].Add(x, Convert.ToDouble(_listAgentData[i].Total));
                        }
                    }
                }

                foreach (KeyValuePair <string, PointPairList> item in list)
                {
                    LineItem curve = null;
                    if (item.Key == "MS Internet Explorer")
                    {
                        curve = pane.AddCurve(item.Key, item.Value, Color.Blue, SymbolType.Diamond);
                    }
                    if (item.Key == "Firefox")
                    {
                        curve = pane.AddCurve(item.Key, item.Value, Color.Red, SymbolType.Diamond);
                    }

                    if (item.Key == "Safari")
                    {
                        curve = pane.AddCurve(item.Key, item.Value, Color.Green, SymbolType.Diamond);
                    }

                    if (item.Key == "Google Chrome")
                    {
                        curve = pane.AddCurve(item.Key, item.Value, Color.Cyan, SymbolType.Diamond);
                    }

                    if (item.Key == "Mozilla")
                    {
                        curve = pane.AddCurve(item.Key, item.Value, Color.Yellow, SymbolType.Diamond);
                    }

                    if (item.Key == "Netscape")
                    {
                        curve = pane.AddCurve(item.Key, item.Value, Color.Brown, SymbolType.Diamond);
                    }

                    if (item.Key == "Mobile Browser")
                    {
                        curve = pane.AddCurve(item.Key, item.Value, Color.Magenta, SymbolType.Diamond);
                    }

                    if (item.Key == "Unknown")
                    {
                        curve = pane.AddCurve(item.Key, item.Value, Color.Black, SymbolType.Diamond);
                    }
                    if (curve != null)
                    {
                        curve.Line.IsSmooth      = true;
                        curve.Line.SmoothTension = 0.5F;
                    }
                }
            }

            zedUserAgent1.IsShowPointValues = true;
            zedUserAgent1.AxisChange();
        }
Beispiel #6
0
        private void DrawNeuronData(int id)
        {
            // Получим панель для рисования
            GraphPane pane = zedGraphControl.GraphPane;

            pane.IsFontsScaled         = false;
            pane.Title.IsVisible       = false;
            pane.XAxis.Title.IsVisible = false;
            pane.YAxis.Title.IsVisible = false;
            pane.XAxis.Title.Text      = "Время (кадр)";
            pane.YAxis.Title.Text      = "Номер нейрона";
            // Очистим список кривых на тот случай, если до этого сигналы уже были нарисованы
            pane.CurveList.Clear();
            LineItem myCurve;

            pane.XAxis.Scale.Min = 0;
            pane.XAxis.Scale.Max = NeuronDataManager.Neurons[id].IntensityCleanData.Count + 10;

            //чистый сигнал
            double[] raw = NeuronDataManager.Neurons[id].IntensityCleanData.ToArray();
            double[] x   = new double[raw.Length];
            //заполним x от 0 до N
            for (int j = 0; j < x.Length; j++)
            {
                x[j] = j;
            }

            myCurve = pane.AddCurve("", x, raw, Color.Black, SymbolType.None);
            myCurve.Line.IsSmooth      = true;
            myCurve.Line.SmoothTension = 1;

            // сырой сигнал
            if (drawAverageChB.Checked)
            {
                //raw = NeuronDataManager.Neurons[id].IntensityRawData.ToArray();
                //x = new double[raw.Length];
                //заполним x от 0 до N
                //for (int j = 0; j < x.Length; j++) x[j] = j;
                //myCurve = pane.AddCurve("", x, raw, Color.Blue, SymbolType.None);
                // myCurve.Line.IsSmooth = true;
                // myCurve.Line.SmoothTension = 1;
            }

            if (DrawSigmaChB.Checked)
            {
            }
            if (DrawSelectLevelChB.Checked)
            {
                //Уровень отсечения ввспышек
                raw = (NeuronSelector.SelectedItem as SingleNeuron).SparklesLevel;
                ///x = new double[raw.Length];
                //заполним x от 0 до N
                //for (int j = 0; j < x.Length; j++) x[j] = j;
                myCurve = pane.AddCurve("", x, raw, Color.Red, SymbolType.None);
                myCurve.Line.IsSmooth      = true;
                myCurve.Line.SmoothTension = 1;
            }
            if (DrawSparklesChB.Checked)
            {
                raw = new double[2] {
                    1, 1
                };
                for (int i = 0; i < (NeuronSelector.SelectedItem as SingleNeuron).SparkleIndexes.Count; i++)
                {
                    x       = (NeuronSelector.SelectedItem as SingleNeuron).SparkleIndexes[i];
                    myCurve = pane.AddCurve("", x, raw, Color.Blue, SymbolType.None);
                    myCurve.Line.IsSmooth      = true;
                    myCurve.Line.Width         = 3;
                    myCurve.Line.SmoothTension = 1;
                }
            }
            // Вызываем метод AxisChange (), чтобы обновить данные об осях.
            // В противном случае на рисунке будет показана только часть графика,
            // которая умещается в интервалы по осям, установленные по умолчанию
            zedGraphControl.AxisChange();

            // Обновляем график
            zedGraphControl.Invalidate();

            // Отобразим изображения нейрона
            NeuronMask.Image = NeuronDataManager.Neurons[SelectedID].Mask.Clone();
            NeuronBody.Image = NeuronDataManager.Neurons[SelectedID].Patch.Clone();
        }
Beispiel #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            z1.GraphPane.CurveList.Clear();
            //GraphPane pane = z1.GraphPane;
            //pane.Title = "cosX";
            PointPairList list       = new PointPairList();
            double        xmin       = /*-1.5*/ Convert.ToDouble(numericUpDown1.Value);
            double        xmax       = /*3.5*/ Convert.ToDouble(numericUpDown2.Value);
            double        xmin_limit = -10;
            double        xmax_limit = 80;
            double        ymin_limit = -1.0;
            double        ymax_limit = 1.0;

            for (double x = xmin; x <= xmax; x += 0.1)
            {
                list.Add(x, func(x));
            }
            // !!!
            // Ось X будет пересекаться с осью Y на уровне Y = 0
            pane.XAxis.Cross = 0.0;

            // Ось Y будет пересекаться с осью X на уровне X = 0
            pane.YAxis.Cross = 0.0;

            // Отключим отображение первых и последних меток по осям
            pane.XAxis.Scale.IsSkipFirstLabel = true;
            pane.XAxis.Scale.IsSkipLastLabel  = true;

            // Отключим отображение меток в точке пересечения с другой осью
            pane.XAxis.Scale.IsSkipCrossLabel = true;


            // Отключим отображение первых и последних меток по осям
            pane.YAxis.Scale.IsSkipFirstLabel = true;

            // Отключим отображение меток в точке пересечения с другой осью
            pane.YAxis.Scale.IsSkipLastLabel  = true;
            pane.YAxis.Scale.IsSkipCrossLabel = true;

            // Спрячем заголовки осей
            pane.XAxis.Title.IsVisible = false;
            pane.YAxis.Title.IsVisible = false;
            LineItem myCurve = pane.AddCurve("Function", list, Color.Blue, SymbolType.None);

            //pane.XAxis.Scale.Min = xmin_limit;
            //pane.XAxis.Scale.Max = xmax_limit;
            //pane.YAxis.Scale.Min = ymin_limit;
            //pane.YAxis.Scale.Max = ymax_limit;

            // !!! Установим заливку для кривой
            // Используем градиентную заливку от красного цвета до голубого через желтый
            // Последний параметр задает угол наклона градиента
            myCurve.Line.Fill = new ZedGraph.Fill(Color.Red, Color.Yellow, Color.Blue, 90.0f);

            z1.AxisChange();
            z1.Invalidate();

            if (flag1 && flag2)
            {
                label7.Text = "Порядок точности - " + Math.Abs(firstAnswer - secondAnswer);
            }
        }
        public void DoEffectiveLine()
        {
            try
            {
                results = new List <Portfolio>(); //new List<double[]>();


                if (start == 0)
                {
                    start = step;
                }
                if (start > finish)
                {
                    finish = 1;
                }

                results = ClassAssistant.DoListPortfolio(finalArray, selectedAssets, start, finish, step, constraints);

                GraphPane gp = zGC.GraphPane;
                gp.CurveList.Clear();

                zGC.AxisChange();
                zGC.Invalidate();

                if (results.Count == 0)
                {
                    MessageBox.Show("Решения для данных параметров не найдены", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    zGC.IsShowPointValues = true;

                    double[] x = new double[results.Count];
                    double[] y = new double[results.Count];
                    int      i = 0;
                    foreach (var a in results)
                    {
                        x[i] = a.Risk;
                        y[i] = a.Profit;
                        i++;
                    }
                    LineItem line = gp.AddCurve("Эффективная граница", x, y, Color.Red);
                    line.Symbol.Fill.Type = FillType.Solid;

                    CurveList cl = gp.CurveList;
                    zGC.AxisChange();
                    zGC.Invalidate();

                    double[] xSP = new double[1];
                    double[] ySP = new double[1];
                    xSP[0] = sp.Risk;
                    ySP[0] = sp.Profit;
                    LineItem lineSP = gp.AddCurve("ЕП", xSP, ySP, Color.Blue);
                    lineSP.Symbol.Fill.Type = FillType.Solid;

                    cl = gp.CurveList;
                    zGC.AxisChange();
                    zGC.Invalidate();
                    label_.Text = "Портфели: " + Convert.ToString(results.Count);
                }
            }
            catch (FormatException)
            {
                MessageBox.Show("Неверный формат числа!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #9
0
        /// <summary>
        ///
        /// </summary>
        public void UpdatePane()
        {
            // Make up some random data points
            string[] labels = { "1", "2", "3", "4", "5", "6", "7" };
            double[] y      = { loop1, loop2, loop3, loop4, loop5, loop6, loop7 };
            double[] z      = { loopwdead1, loopwdead2, loopwdead3, loopwdead4, loopwdead5, loopwdead6, loopwdead7 };
            double[] avgy   = { avgloop1, avgloop2, avgloop3, avgloop4, avgloop5, avgloop6, avgloop7 };
            double[] avgz   = { avgloopwdead1, avgloopwdead2, avgloopwdead3, avgloopwdead4, avgloopwdead5, avgloopwdead6, avgloopwdead7 };
            try
            {
                // Generate a red bar with "Curve 1" in the legend
                if (myBar1 == null)
                {
                    /// Generate a black line with "Curve 4" in the legend
                    average7curve = graphpane.AddCurve("Avg Hands()", null, avgy, Color.Aqua, SymbolType.Circle);
                    //average7curve.Line.Fill = new Fill(Color.White, Color.LightSkyBlue, -45F);
                    //// Fix up the curve attributes a little
                    average7curve.Symbol.Size = 8.0F;
                    average7curve.Symbol.Fill = new Fill(Color.White);
                    average7curve.Line.Width  = 2.0F;

                    /// Generate a black line with "Curve 4" in the legend
                    average5curve = graphpane.AddCurve("Avg Hands() w/dead", null, avgz, Color.BlueViolet, SymbolType.TriangleDown);
                    //average7curve.Line.Fill = new Fill(Color.White, Color.LightSkyBlue, -45F);
                    //// Fix up the curve attributes a little
                    average5curve.Symbol.Size = 8.0F;
                    average5curve.Symbol.Fill = new Fill(Color.White);
                    average5curve.Line.Width  = 2.0F;


                    myBar1 = graphpane.AddBar("Inline", null, y, Color.Violet);
                    myBar2 = graphpane.AddBar("Inline W/Dead", null, z, Color.Blue);


                    myBar1.Bar.Fill = new Fill(Color.Aqua, Color.White, Color.Aqua);
                    myBar2.Bar.Fill = new Fill(Color.CadetBlue, Color.White, Color.CadetBlue);
                }
                else
                {
                    int size = myBar1.NPts;
                    for (int i = 0; i < size; i++)
                    {
                        myBar1.RemovePoint(0);
                    }

                    foreach (double v in y)
                    {
                        myBar1.AddPoint(v, v);
                    }

                    size = myBar2.NPts;
                    for (int i = 0; i < size; i++)
                    {
                        myBar2.RemovePoint(0);
                    }

                    foreach (double v in z)
                    {
                        myBar2.AddPoint(v, v);
                    }

                    size = average7curve.NPts;
                    for (int i = 0; i < size; i++)
                    {
                        average7curve.RemovePoint(0);
                    }

                    foreach (double v in avgy)
                    {
                        average7curve.AddPoint(v, v);
                    }

                    size = average5curve.NPts;
                    for (int i = 0; i < size; i++)
                    {
                        average5curve.RemovePoint(0);
                    }

                    foreach (double v in avgz)
                    {
                        average5curve.AddPoint(v, v);
                    }
                }

                // Draw the X tics between the labels instead of
                // at the labels
                //graph.GraphPane.XAxis.M.IsBetweenLabels = true;

                // Set the XAxis labels
                graphpane.XAxis.Scale.TextLabels = labels;
                // Set the XAxis to Text type
                graphpane.XAxis.Type = AxisType.Text;
            }
            catch
            {
            }
        }
Beispiel #10
0
        private void button1_Click(object sender, EventArgs e)
        {
            int    n = Convert.ToInt32(textBox1.Text);
            double a = Convert.ToDouble(textBox2.Text);

            LinkList p = new LinkList();

            Random rnd = new Random();

            for (int i = 0; i < n; i++)
            {
                double u = (double)rnd.Next(10000000) / 10000000.0;
                double nu;

                if (u < 0.5)
                {
                    nu = -1.0 * Math.Sqrt(Math.Sqrt(2.0 - 4.0 * u));

                    p.insertup(nu);
                }
                else
                {
                    nu = Math.Acos(1.0 + a / 2.0 - a * u) / a;

                    p.insertup(nu);
                }
            }

            dataGridView1.Rows.Clear();

            p.printDGV(dataGridView1);

            double mo = (-2.0 / 5.0) * Math.Sqrt(Math.Sqrt(2.0)) - ((1.0 - a / 2.0) / (a * a)) * Math.Acos(1.0 - a / 2.0) + (1.0 / (a * a)) * Math.Sqrt(a - a * a / 4.0);
            double x  = p.vs(n);
            double d  = Math.Sqrt(2.0) / 3.0 - 1.0 / (a * a) + (1.0 / (a * a * a)) * Math.Acos(1.0 - a / 2.0) * (Math.Sqrt(a - a * a / 4.0) - (1.0 - a / 2.0) * Math.Acos(1.0 - a / 2.0));
            double s  = p.vd(n, x);
            double me = p.vm(n);
            double r  = p.rv();

            dataGridView2.Rows[0].Cells[0].Value = mo;
            dataGridView2.Rows[0].Cells[1].Value = x;
            dataGridView2.Rows[0].Cells[2].Value = Math.Abs(mo - x);
            dataGridView2.Rows[0].Cells[3].Value = d;
            dataGridView2.Rows[0].Cells[4].Value = s;
            dataGridView2.Rows[0].Cells[5].Value = Math.Abs(d - s);
            dataGridView2.Rows[0].Cells[6].Value = me;
            dataGridView2.Rows[0].Cells[7].Value = r;

            GraphPane panel = zedGraphControl1.GraphPane;

            panel.CurveList.Clear();

            double b1 = Math.Acos(1.0 - a / 2.0) / a;
            double dd = p.artGraph(zedGraphControl1, FR, n, b1);

            double a0 = p.leftgr();
            double b0 = p.rightgr();
            double a1 = -1.0 * Math.Sqrt(Math.Sqrt(2.0));

            double h = (b1 - a1) / 1000.0;

            PointPairList f_list = new PointPairList();

            for (int j = 0; j < 1000; j++)
            {
                double xx = a1 + j * h;
                f_list.Add(xx, FR(xx));
            }

            f_list.Add(b1, FR(b1));

            LineItem Curve = panel.AddCurve("F(x)", f_list, Color.Red, SymbolType.None);

            zedGraphControl1.AxisChange();
            zedGraphControl1.Invalidate();

            dataGridView2.Rows[0].Cells[8].Value = dd;

            int k = Convert.ToInt32(textBox3.Text);

            double[] gran = new double[k];

            if (!checkBox1.Checked)
            {
                for (int i = 0; i < k - 1; i++)
                {
                    gran[i] = Convert.ToDouble(dataGridView4.Rows[i].Cells[0].Value);
                }

                gran[k - 1] = b1 + 0.000000000000001;
            }
            else
            {
                h = (b0 - a0) / (double)k;

                for (int j = 0; j < k - 1; j++)
                {
                    gran[j] = a0 + (j + 1) * h;

                    dataGridView4.Rows[j].Cells[0].Value = gran[j];
                }

                gran[k - 1] = b1 + 0.000000000000001;
            }

            dataGridView3.Rows.Clear();

            double ddd = p.gistogram(gran, dataGridView3, zedGraphControl2, pFR, n);

            dataGridView2.Rows[0].Cells[9].Value = ddd;

            double r0    = p.teoria(gran, dataGridView4, intpFR, n);
            double f_    = 1 - inthi(0.0, r0, n, k - 1);
            double alpha = Convert.ToDouble(textBox4.Text);

            dataGridView2.Rows[0].Cells[10].Value = f_;


            if (f_ < alpha)
            {
                label5.Text = "Решение: отвергаем";
            }
            else
            {
                label5.Text = "Решение: принимаем";
            }
        }
Beispiel #11
0
        /// <summary>
        /// Plot solution
        /// </summary>
        /// <param name="sender">sender object</param>
        /// <param name="e">Event arguments</param>
        private void PlotButton_Click(object sender, EventArgs e)
        {
            pane.CurveList.Clear();

            // Prey population equation
            Func <double, double, double> preyPop = (x, y) =>
                                                    x * ((double)PreyBirthRate.Value - (double)PreyDeathRate.Value * y);

            // Predator population equation
            Func <double, double, double> predatorPop = (x, y) =>
                                                        y * ((double)PredatorBirthRate.Value * x - (double)PredatorDeathRate.Value);

            // Solution for predator and prey
            double[,] preyAndPredatorCurves;

            try
            {
                // checking what algorith to use
                if (RKF45.Checked)
                {
                    preyAndPredatorCurves = RungeKutta.Rkf45(preyPop, predatorPop, (double)PreyPopulation.Value,
                                                             (double)PredatorPopulation.Value, (int)TimeSpan.Value, 0.01);
                }
                else
                {
                    preyAndPredatorCurves = RungeKutta.Rk4(preyPop, predatorPop, (double)PreyPopulation.Value,
                                                           (double)PredatorPopulation.Value, (int)TimeSpan.Value, (double)StepSize.Value);
                }

                PointPairList preySolution = new PointPairList();

                for (int i = 0; i <= preyAndPredatorCurves.GetUpperBound(1); i++)
                {
                    preySolution.Add(preyAndPredatorCurves[2, i], preyAndPredatorCurves[0, i]);
                }

                PointPairList predatorSolution = new PointPairList();

                for (int i = 0; i <= preyAndPredatorCurves.GetUpperBound(1); i++)
                {
                    predatorSolution.Add(preyAndPredatorCurves[2, i], preyAndPredatorCurves[1, i]);
                }

                // Adding prey population curve
                LineItem preyCurve = pane.AddCurve("Prey population",
                                                   preySolution, Color.Green, SymbolType.None);
                preyCurve.Line.Width    = 2;
                preyCurve.Line.IsSmooth = true;

                // Adding predator population curve
                LineItem predatorCurve = pane.AddCurve("Predator population",
                                                       predatorSolution, Color.Red, SymbolType.None);
                predatorCurve.Line.Width    = 2;
                predatorCurve.Line.IsSmooth = true;
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message + "\nPlease enter smaller parameters", "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            // Changing axis to fit the curves
            GraphControl.AxisChange();
            GraphControl.Invalidate();
        }
 /// <summary>
 /// Creates a new CurveItem using the PointPairList and add it the the given pane.
 /// </summary>
 /// <param name="pane">the GraphPane object to which to add the new curve</param>
 /// <param name="points">a PointPairList collection defining the points for this curve</param>
 /// <returns>the newly created CurveItem added to the given GraphPane</returns>
 /// <remarks>This method must be overriden by childs</remarks>
 public override CurveItem CreateInPane( GraphPane pane, PointPairList points )
 {
     LineItem x = pane.AddCurve( this.Label, points, this.Color );
     this.CopyTo( x );
     return x;
 }
        /// <summary>
        ///  Plots the lists into a zedgraph
        /// </summary>
        private void PlotGraph()
        {
            GraphPane myPane = zedGraphControl1.GraphPane;

            zedGraphControl1.GraphPane.CurveList.Clear();
            zedGraphControl1.GraphPane.GraphObjList.Clear();
            // Set the Titles
            myPane.Title.Text       = "Cycle Chart Data";
            myPane.XAxis.Title.Text = "Seconds";
            myPane.YAxis.Title.Text = "Value";
            myPane.XAxis.Title.Text = "Time";
            TimeSpan timer = new TimeSpan();

            timer = timer.Add(TimeSpan.FromSeconds(interval));
            zedGraphControl1.IsShowPointValues = true;
            int start = Int32.Parse(PointsArray[0]);
            int end   = Int32.Parse(PointsArray[1]);

            StartPoint                     = start;
            EndPoint                       = end;
            Difference                     = EndPoint - StartPoint;
            myPane.XAxis.Scale.Max         = Difference;
            myPane.XAxis.ScaleFormatEvent += new Axis.ScaleFormatHandler(Axis_ScaleFormatEvent); //lets the x axis change to interval timespan rather than leaving it in seconds format

            PointPairList HRSpeed1   = new PointPairList();
            PointPairList HeartRate1 = new PointPairList();
            PointPairList Cadeance1  = new PointPairList();
            PointPairList Altitude1  = new PointPairList();
            PointPairList Power1     = new PointPairList();

            /*
             */
            HeartRate = heartrate.Select(int.Parse).ToArray();
            if (SpeedCheck)
            {
                Speed = HRSpeed.Select(int.Parse).ToArray();
            }

            if (AltCheck)
            {
                Altitude = altitude.Select(int.Parse).ToArray();
            }
            if (CadenceCheck)
            {
                Cadeance = cadence.Select(int.Parse).ToArray();
            }
            if (PowerCheck)
            {
                Power = power.Select(int.Parse).ToArray();
            }
            if (PowerBICheck)
            {
                PowerBalance = powerbalance.Select(int.Parse).ToArray();
            }

            int i2 = 0;

            // plot to curves
            for (int i = start; i < end; i++)
            {
                i2 = i2 + 1;
                if (!HRCheck)
                {
                    HeartRate1.Add(i2, HeartRate[i]);
                }
                else
                {
                    HeartRate1.Add(i2, HeartRate[i]);
                    if (SpeedCheck)
                    {
                        int speed = Speed[i] / 10;
                        HRSpeed1.Add(i2, speed);
                    }
                    if (CadenceCheck)
                    {
                        Cadeance1.Add(i2, Cadeance[i]);
                    }
                    if (AltCheck)
                    {
                        Altitude1.Add(i2, Altitude[i]);
                    }
                    if (PowerCheck)
                    {
                        Power1.Add(i2, Power[i]);
                    }
                }
            }

            //loads curves based if they are selected in the options & checked in smode

            LineItem HeartRateCurve = myPane.AddCurve("Heart Rate",
                                                      HeartRate1, Color.Blue, SymbolType.None);

            if (SpeedCheck)
            {
                LineItem AltitudeCurve = myPane.AddCurve("Speed",
                                                         HRSpeed1, Color.Red, SymbolType.None);
            }

            if (AltCheck)
            {
                LineItem AltitudeCurve = myPane.AddCurve("Altitude",
                                                         Altitude1, Color.Green, SymbolType.None);
            }

            if (CadenceCheck)
            {
                LineItem CadenceCurve = myPane.AddCurve("Cadence",
                                                        Cadeance1, Color.Purple, SymbolType.None);
            }
            if (PowerCheck)
            {
                LineItem PowerCurve = myPane.AddCurve("Power",
                                                      Power1, Color.Orange, SymbolType.None);
            }


            zedGraphControl1.AxisChange();
            zedGraphControl1.Refresh();

            //zedGraphControl1.RestoreScale(zedGraphControl1.GraphPane); //unzooms graph whenever it is reloaded
        }
Beispiel #14
0
        public static GraphControl Create()
        {
            GraphControl z = new GraphControl()
            {
                Dock = DockStyle.Fill
            };
            var p  = z.GraphPane;
            var po = new GraphPane();
            var c  = po.AddCurve(null, new PointPairList(), Color.Black);

            c.Symbol.Type            = SymbolType.None;
            po.XAxis.Type            = AxisType.Linear;
            po.XAxis.Scale.IsVisible = false;
            po.XAxis.Title.IsVisible = false;
            po.XAxis.Scale.MaxAuto   = false;
            po.XAxis.Scale.Max       = SortingAlgorithm.BigOXMax;
            po.YAxis.Type            = AxisType.Linear;
            po.YAxis.Scale.IsVisible = false;
            po.YAxis.Title.IsVisible = false;
            po.YAxis.Scale.MaxAuto   = false;
            po.YAxis.Scale.Max       = SortingAlgorithm.BigOYMax;
            z.MasterPane.Add(po);

            var cbar = p.AddBar("compare", new PointPairList(), Color.DarkOrange);

            cbar.Bar.Fill.Type        = FillType.Solid;
            cbar.Bar.Border.IsVisible = false;

            var sbar = p.AddBar("swap", new PointPairList(), Color.Red);

            sbar.Bar.Fill.Type        = FillType.Solid;
            sbar.Bar.Border.IsVisible = false;

            var setbar = p.AddBar("working-set", new PointPairList(), Color.Blue);

            setbar.Bar.Fill.Type        = FillType.Solid;
            setbar.Bar.Border.IsVisible = false;

            var bar = p.AddBar("Data", new PointPairList(), Color.LightBlue);

            bar.Bar.Fill.Type        = FillType.Solid;
            bar.Bar.Border.IsVisible = false;

            p.Title.IsVisible       = true;
            p.Legend.IsVisible      = false;
            p.XAxis.Title.IsVisible = false;
            p.XAxis.Type            = AxisType.Linear;
            p.XAxis.Scale.Min       = 0;
            p.XAxis.MinorTic.Size   = 0;
            p.YAxis.Title.IsVisible = false;
            p.YAxis.Type            = AxisType.Linear;
            p.YAxis.Scale.Max       = App.YMax;
            p.BarSettings.Type      = BarType.Overlay;
            z.IsEnableVZoom         = false;
            z.IsEnableZoom          = false;
            z.Dock = DockStyle.None;

            // Layout the GraphPanes using a default Pane Layout
            using (Graphics g = z.CreateGraphics())
            {
                z.MasterPane.SetLayout(g, false, new int[] { 1, 1 }, new float[] { 2f, 1f });
            }

            return(z);
        }
Beispiel #15
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            GraphPane     myPane        = zedGraphControl1.GraphPane;
            PointPairList listPointsTwo = new PointPairList();
            string        selected      = comboBox1.Text;

            ACOK.SipRegisters sel = EnumDescriptor.ToEnum <ACOK.SipRegisters>(selected);
            if (selected == "Data1")
            {
                Dispdata(sel);
                //button6_Click(this, null);
            }
            if (selected != "Data1")
            {
                //if (axisflag == 1)
                //{
                //    myPane.YAxis.Max = 40;
                //    myPane.YAxis.Min = 0;
                //    myPane.XAxis.Min = 0;
                //    myPane.XAxis.Max = 50;
                //}

                if (i * yscalectrl > myPane.XAxis.Max - 5)
                {
                    myPane.XAxis.Max = (i + 10);
                    axisflag         = 0;
                }
                i++;


                Sipval[(i - 1)] = Data.GetVal(sel);


                zedGraphControl1.AxisChange();
                zedGraphControl1.Refresh();

                myPane.ScaledGap(1);

                Rangscale(sel);


                myPane.IsFontsScaled = true;


                PointPairList approx2 = new PointPairList();


                if (i > 1)
                {
                    a = (sumxy * (i - 1) - sumy * sumx) / (sumx2 * (i - 1) - Math.Pow(sumx, 2));
                    b = (sumy - a * sumx) / (i - 1);
                    for (double x = i - 1; x <= i; x += 0.5)
                    {
                        approx2.Add(x, a1 * x + b1);
                    }
                }
                sumx  += i;
                sumy  += Data.GetVal(sel);
                sumx2 += Math.Pow(i, 2);
                sumxy += i * Data.GetVal(sel);

                a = (sumxy * i - sumy * sumx) / (sumx2 * i - Math.Pow(sumx, 2));
                b = (sumy - a * sumx) / i;
                PointPairList approx1 = new PointPairList();
                approx1.Clear();
                for (double x = 1; x <= i; x += 0.5)
                {
                    approx1.Add(x, a * x + b);
                }

                /*
                 * LineItem f1_curve = myPane.AddCurve(null, approx1, Color.Black, SymbolType.None);
                 */
                myPane.CurveList.Clear();

                for (int u = 0; u < Sipval.Length; u++)
                {
                    listPointsTwo.Add(u + 1, Sipval[u]);
                }
                LineItem myCurveTwo = myPane.AddCurve("real T", listPointsTwo, Color.Black, SymbolType.None);
                if (i > 2)
                {
                    bezcurv(Sipval, i);
                }
                Array.Resize <double>(ref Sipval, Sipval.Length + 1);

                //byte[] temBuf = new byte[4];
                //int index = 0;

                //private void COM3_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
                //{

                //    ////byte[] tempval = new byte[3];
                //    //int[] tempval = new int[3];// tempval[3];
                //    //int j = 0;

                //        int count = COM3.BytesToRead;
                //        while (count > 0)
                //        {
                //            byte[] buf = new byte[count];
                //            COM3.Read(buf, 0, count);

                //            int wrCount = ((temBuf.Length - index) < count) ? count : count; //(temBuf.Length - index);
                //            Array.Copy(buf, 0, temBuf, index, wrCount);

                //            index += wrCount;
                //            if (index >= temBuf.Length)
                //            {
                //                index = 0;
                //                float temp = 0;
                //                try
                //                {
                //                    temp = BitConverter.ToSingle(temBuf, 0);
                //                }
                //                catch {}

                //                richTextBox1.Invoke(new Action(() =>
                //                {
                //                    richTextBox2.Text = string.Format("{0:F3}", temp); ;
                //                }));
                //            }

                //            //tempval[j]= COM3.Read(buf, 0, count);
                //            //richTextBox4.Text += tempval[j];
                //            //j++;
                //            //if (j > 2)
                //            //{
                //            //    j = 0;
                //            //};



                //            //string strB = "";
                //            //for (int i = 0; i < count; i++)
                //            //{
                //            //    strB += string.Format("{0:X2}", buf[i]);
                //            //    strB += "\t";
                //            //}

                //            //richTextBox1.Invoke(new Action(() =>
                //            //{
                //            //   richTextBox2.Text += strB;
                //            //}));

                //            count = COM3.BytesToRead;
                //        }
                //    }

                //private void COM3_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
                //{

                //}
                //
                #endregion // Events
                //-------------------------------------------------------------------------



                //button1_Click_1(this, null);
            }
        }
Beispiel #16
0
        /// <summary>
        /// 初始化图表控件
        /// </summary>
        public void chart_initial()
        {
            zedGraphControl1.IsShowContextMenu = false;
            zedGraphControl1.IsEnableHPan      = false; zedGraphControl1.IsEnableVPan = false;
            zedGraphControl1.IsEnableHZoom     = false; zedGraphControl1.IsEnableZoom = false;
            GraphPane myPane = zedGraphControl1.GraphPane;

            // myPane.Fill = new Fill(Color.FromArgb(28, 29, 31));
            myPane.Fill               = new Fill(Color.Black);
            myPane.Chart.Fill         = new Fill(Color.Black);
            myPane.IsFontsScaled      = false;
            myPane.Border.Color       = Color.White;
            myPane.Chart.Border.Color = Color.Gray;
            // Set the titles and axis labels
            myPane.Legend.IsVisible = false;
            myPane.Title.Text       = " ";
            //x轴
            myPane.XAxis.Title.Text               = "时间(分钟)";
            myPane.XAxis.MajorGrid.Color          = Color.White;
            myPane.XAxis.Scale.FontSpec.FontColor = Color.White;
            myPane.XAxis.Scale.FontSpec.Size      = 15;
            myPane.XAxis.Title.FontSpec.Size      = 15;
            myPane.XAxis.Title.FontSpec.FontColor = Color.White;
            myPane.XAxis.Scale.Min           = 0;  //X轴最小值0
            myPane.XAxis.Scale.Max           = 30; //X轴最大30
            myPane.XAxis.MajorTic.IsInside   = false;
            myPane.XAxis.MinorTic.IsInside   = false;
            myPane.XAxis.MajorTic.IsOpposite = false;
            myPane.XAxis.MinorTic.IsOpposite = false;
            myPane.XAxis.MajorTic.Color      = Color.White;
            myPane.XAxis.MinorTic.Color      = Color.White;
            myPane.XAxis.Scale.MajorStep     = 5;//X轴大步长为5,也就是显示文字的大间隔
            myPane.XAxis.MajorGrid.IsVisible = true;
            //y轴
            myPane.YAxis.MajorTic.IsInside  = false;
            myPane.YAxis.MajorGrid.Color    = Color.White;
            myPane.YAxis.MinorTic.IsInside  = false;
            myPane.Y2Axis.MajorTic.IsInside = false;
            myPane.Y2Axis.MajorGrid.Color   = Color.White;
            myPane.Y2Axis.MinorTic.IsInside = false;

            // Make up some data points based on the Sine function
            PointPairList List1 = new PointPairList();
            PointPairList List2 = new PointPairList();
            PointPairList List3 = new PointPairList();
            PointPairList List4 = new PointPairList();
            PointPairList List5 = new PointPairList();
            PointPairList List6 = new PointPairList();


            // 根据配置信息,生成曲线坐标轴的样式
            LineItem myCurve = myPane.AddCurve(paraLine3.Tagname,
                                               List1, paraLine3.Color, SymbolType.None);

            myCurve.Line.Width = 1;

            myCurve = myPane.AddCurve(paraLine4.Tagname,
                                      List2, paraLine4.Color, SymbolType.None);
            myCurve.Line.Width = 1;
            myCurve.IsY2Axis   = true;


            myCurve = myPane.AddCurve(paraLine2.Tagname,
                                      List3, paraLine2.Color, SymbolType.None);
            myCurve.Line.Width = 1;
            myCurve.YAxisIndex = 1;

            myCurve = myPane.AddCurve(paraLine5.Tagname,
                                      List4, paraLine5.Color, SymbolType.None);
            myCurve.Line.Width = 1;
            myCurve.IsY2Axis   = true;
            myCurve.YAxisIndex = 1;

            myCurve = myPane.AddCurve(paraLine1.Tagname,
                                      List5, paraLine1.Color, SymbolType.None);
            myCurve.Line.Width = 1;
            myCurve.YAxisIndex = 2;

            myCurve = myPane.AddCurve(paraLine6.Tagname,
                                      List6, paraLine6.Color, SymbolType.None);
            myCurve.Line.Width = 1;
            myCurve.IsY2Axis   = true;
            myCurve.YAxisIndex = 2;

            // Make the Y axis
            myPane.YAxis.Scale.FontSpec.FontColor = paraLine3.Color;
            myPane.YAxis.Scale.FontSpec.Size      = 15;
            myPane.YAxis.Title.FontSpec.FontColor = paraLine3.Color;
            myPane.YAxis.Title.FontSpec.Size      = 15;
            myPane.YAxis.Color = paraLine3.Color;
            // turn off the opposite tics so the Y tics don't show up on the Y2 axis
            myPane.YAxis.MajorTic.IsOpposite = false;
            myPane.YAxis.MajorTic.Color      = paraLine3.Color;
            myPane.YAxis.MinorTic.IsOpposite = false;
            myPane.YAxis.MinorTic.Color      = paraLine3.Color;
            // Don't display the Y zero line
            myPane.YAxis.MajorGrid.IsZeroLine = false;
            // Align the Y axis labels so they are flush to the axis
            myPane.YAxis.Scale.Align = AlignP.Inside;
            myPane.YAxis.Scale.Max   = int.Parse(paraLine3.Max);
            myPane.YAxis.Scale.Min   = int.Parse(paraLine3.Min);

            // Enable the Y2 axis
            myPane.Y2Axis.IsVisible = true;
            // Make the Y2 axis scale black
            myPane.Y2Axis.Scale.FontSpec.FontColor = paraLine4.Color;
            myPane.Y2Axis.Scale.FontSpec.Size      = 15;
            myPane.Y2Axis.Title.FontSpec.FontColor = paraLine4.Color;
            myPane.Y2Axis.Title.FontSpec.Size      = 15;
            myPane.Y2Axis.Color = paraLine4.Color;
            // turn off the opposite tics so the Y2 tics don't show up on the Y axis
            myPane.Y2Axis.MajorTic.IsOpposite = false;
            myPane.Y2Axis.MajorTic.Color      = paraLine4.Color;
            myPane.Y2Axis.MinorTic.IsOpposite = false;
            myPane.Y2Axis.MinorTic.Color      = paraLine4.Color;
            // Display the Y2 axis grid lines
            myPane.Y2Axis.MajorGrid.IsVisible = true;
            // Align the Y2 axis labels so they are flush to the axis
            myPane.Y2Axis.Scale.Align = AlignP.Inside;
            myPane.Y2Axis.Scale.Max   = int.Parse(paraLine4.Max);
            myPane.Y2Axis.Scale.Min   = int.Parse(paraLine4.Min);

            // Create a second Y Axis
            YAxis yAxis3 = new YAxis(paraLine2.Tagname + "(" + paraLine2.Unit + ")");

            myPane.YAxisList.Add(yAxis3);
            yAxis3.Scale.FontSpec.FontColor = paraLine2.Color;
            yAxis3.Scale.FontSpec.Size      = 15;
            yAxis3.Title.FontSpec.FontColor = paraLine2.Color;
            yAxis3.Title.FontSpec.Size      = 15;
            yAxis3.Color = paraLine2.Color;
            // turn off the opposite tics so the Y2 tics don't show up on the Y axis
            yAxis3.MajorTic.IsInside   = false;
            yAxis3.MinorTic.IsInside   = false;
            yAxis3.MajorTic.IsOpposite = false;
            yAxis3.MajorTic.Color      = paraLine2.Color;
            yAxis3.MinorTic.IsOpposite = false;
            yAxis3.MinorTic.Color      = paraLine2.Color;
            // Align the Y2 axis labels so they are flush to the axis
            yAxis3.Scale.Align = AlignP.Inside;
            yAxis3.Scale.Max   = int.Parse(paraLine2.Max);
            yAxis3.Scale.Min   = int.Parse(paraLine2.Min);


            // Create a third Y Axis
            YAxis yAxis5 = new YAxis(paraLine1.Tagname + "(" + paraLine1.Unit + ")");

            myPane.YAxisList.Add(yAxis5);
            yAxis5.Scale.FontSpec.FontColor = paraLine1.Color;
            yAxis5.Scale.FontSpec.Size      = 15;
            yAxis5.Title.FontSpec.FontColor = paraLine1.Color;
            yAxis5.Title.FontSpec.Size      = 15;
            yAxis5.Color = paraLine1.Color;
            // turn off the opposite tics so the Y2 tics don't show up on the Y axis
            yAxis5.MajorTic.IsInside   = false;
            yAxis5.MinorTic.IsInside   = false;
            yAxis5.MajorTic.IsOpposite = false;
            yAxis5.MajorTic.Color      = paraLine1.Color;
            yAxis5.MinorTic.IsOpposite = false;
            yAxis5.MinorTic.Color      = paraLine1.Color;
            // Align the Y2 axis labels so they are flush to the axis
            yAxis5.Scale.Align = AlignP.Inside;
            yAxis5.Scale.Max   = int.Parse(paraLine1.Max);
            yAxis5.Scale.Min   = int.Parse(paraLine1.Min);


            // Create a second Y2 Axis
            Y2Axis yAxis4 = new Y2Axis(paraLine5.Tagname + "(" + paraLine5.Unit + ")");

            yAxis4.IsVisible = true;
            myPane.Y2AxisList.Add(yAxis4);
            yAxis4.Scale.FontSpec.FontColor = paraLine5.Color;
            yAxis4.Scale.FontSpec.Size      = 15;
            yAxis4.Title.FontSpec.FontColor = paraLine5.Color;
            yAxis4.Title.FontSpec.Size      = 15;
            yAxis4.Color = paraLine5.Color;
            // turn off the opposite tics so the Y2 tics don't show up on the Y axis
            yAxis4.MajorTic.IsInside   = false;
            yAxis4.MinorTic.IsInside   = false;
            yAxis4.MajorTic.IsOpposite = false;
            yAxis4.MajorTic.Color      = paraLine5.Color;
            yAxis4.MinorTic.IsOpposite = false;
            yAxis4.MinorTic.Color      = paraLine5.Color;
            // Align the Y2 axis labels so they are flush to the axis
            yAxis4.Scale.Align = AlignP.Inside;
            yAxis4.Scale.Max   = int.Parse(paraLine5.Max);
            yAxis4.Scale.Min   = int.Parse(paraLine5.Min);

            // Create a third Y2 Axis
            Y2Axis yAxis6 = new Y2Axis(paraLine6.Tagname + "(" + paraLine6.Unit + ")");

            yAxis6.IsVisible = true;
            myPane.Y2AxisList.Add(yAxis6);
            yAxis6.Scale.FontSpec.FontColor = paraLine6.Color;
            yAxis6.Scale.FontSpec.Size      = 15;
            yAxis6.Title.FontSpec.FontColor = paraLine6.Color;
            yAxis6.Title.FontSpec.Size      = 15;
            yAxis6.Color = paraLine6.Color;
            // turn off the opposite tics so the Y2 tics don't show up on the Y axis
            yAxis6.MajorTic.IsInside   = false;
            yAxis6.MinorTic.IsInside   = false;
            yAxis6.MajorTic.IsOpposite = false;
            yAxis6.MajorTic.Color      = paraLine6.Color;
            yAxis6.MinorTic.IsOpposite = false;
            yAxis6.MinorTic.Color      = paraLine6.Color;
            // Align the Y2 axis labels so they are flush to the axis
            yAxis6.Scale.Align = AlignP.Inside;
            yAxis6.Scale.Max   = int.Parse(paraLine6.Max);
            yAxis6.Scale.Min   = int.Parse(paraLine6.Min);
            // Fill the axis background with a gradient
            //  myPane.Chart.Fill = new Fill(Color.White, Color.LightGoldenrodYellow, 45.0f);


            //新增,y轴不显示名称及零线
            foreach (YAxis y in myPane.YAxisList)
            {
                y.MajorGrid.IsZeroLine = false;
                y.Title.IsVisible      = false;
            }
            foreach (Y2Axis y in myPane.Y2AxisList)
            {
                y.MajorGrid.IsZeroLine = false;
                y.Title.IsVisible      = false;
            }
            //新增,读取配置文件的曲线颜色信息,更新曲线
            trend_refresh("1"); trend_refresh("2"); trend_refresh("3");
            trend_refresh("4"); trend_refresh("5"); trend_refresh("6");
            trend_refresh(paraLine1.checkBox1.Checked, "1"); trend_refresh(paraLine4.checkBox1.Checked, "4");
            trend_refresh(paraLine2.checkBox1.Checked, "2"); trend_refresh(paraLine5.checkBox1.Checked, "5");
            trend_refresh(paraLine3.checkBox1.Checked, "3"); trend_refresh(paraLine6.checkBox1.Checked, "6");

            zedGraphControl1.AxisChange();
        }
Beispiel #17
0
        public void DrawNeuronActivities(List <List <List <PointD> > > input, string filename)
        {
            #region Variables
            int max_Count = 0;

            List <List <PointD> > normalisedInput = new List <List <PointD> >();
            PointD        nullPointD = new PointD(0, 0);
            List <PointD> tmpList    = new List <PointD>();

            List <double> X = new List <double>(); for (int i = 1; i <= max_Count; i++)
            {
                X.Add(i);
            }
            List <double> Y = new List <double>();

            GraphPane     pane1 = zedGraphControl.GraphPane;
            PointPairList list1;
            LineItem      myCurve1;
            #endregion

            // сгенерировать список цветов от 380 до 740
            List <List <PointD> > curInput = new List <List <PointD> >();

            // найти максимум
            max_Count = int.MinValue;
            for (int N = 0; N < input.Count; N++)
            {
                curInput = input[N];

                for (int i = 0; i < curInput.Count; i++)
                {
                    if (max_Count < curInput[i][curInput[i].Count - 1].X)
                    {
                        max_Count = (int)curInput[i][curInput[i].Count - 1].X;
                    }
                }
            }

            //Нормализовать список списков
            for (int N = 0; N < input.Count; N++)
            {
                curInput = input[N];
                for (int i = 0; i < curInput.Count; i++)
                {
                    //  for (int j = 0; j < (int)curInput[i][0].X; j++) tmpList.Add(nullPointD);
                    for (int j = 0; j < curInput[i].Count; j++)
                    {
                        tmpList.Add(curInput[i][j]);
                    }
                    //  for (int j = tmpList.Count; j < max_Count; j++) tmpList.Add(nullPointD);

                    normalisedInput.Add(tmpList);
                    tmpList = new List <PointD>();
                }
            }


            pane1.XAxis.Scale.Max = max_Count + 20;
            pane1.Title.Text      = filename;

            List <Color> Colors = new List <Color>();
            for (int i = 0; i < normalisedInput.Count; i++)
            {
                Colors.Add(Plotter.Colors.waveToColor(380 + i * (int)((740 - 380) / normalisedInput.Count)));
            }

            pane1.CurveList.Clear();


            for (int N = 0; N < normalisedInput.Count; N++)
            {
                //Нарисовать список списков
                //        pane1.CurveList.Clear();

                Y = new List <double>();
                for (int j = 0; j < normalisedInput[N].Count; j++)
                {
                    Y.Add(normalisedInput[N][j].Y);
                }

                list1 = new PointPairList(X.ToArray(), Y.ToArray());

                myCurve1 = pane1.AddCurve("", list1, Colors[N], SymbolType.None);
                myCurve1.Line.IsAntiAlias = true;
                myCurve1.Line.IsSmooth    = true;
            }

            List <int> sum = new List <int>();
            //for (int i = 0; i < normalisedInput.Count; i++)
            //  sum.Add((int)normalisedInput[i][0].Sum());

            Image bp1 = zedGraphControl.GetImage();
            //bp1.Save(Path_toSave + filename + "_" + CurrentFolder.Replace("\\", String.Empty) + ".png");
            bp1.Save(Path_toSave + filename + ".png");

            int k = 0;

            zedGraphControl.AxisChange();
            zedGraphControl.Invalidate();
        }
Beispiel #18
0
        public void CreateChart(ZedGraphControl zgc)
        {
            GraphPane myPane = zgc.GraphPane;

            // Set the titles and axis labels
            myPane.Title.Text       = "Elevation above ground";
            myPane.XAxis.Title.Text = "Distance (m)";
            myPane.YAxis.Title.Text = "Elevation (m)";

            LineItem myCurve;

            myCurve = myPane.AddCurve("Planned Path", list1, Color.Red, SymbolType.None);
            myCurve = myPane.AddCurve("Google", list2, Color.Green, SymbolType.None);
            myCurve = myPane.AddCurve("DEM", list3, Color.Blue, SymbolType.None);

            foreach (PointPair pp in list1)
            {
                // Add a another text item to to point out a graph feature
                TextObj text = new TextObj((string)pp.Tag, pp.X, pp.Y);
                // rotate the text 90 degrees
                text.FontSpec.Angle     = 90;
                text.FontSpec.FontColor = Color.White;
                // Align the text such that the Right-Center is at (700, 50) in user scale coordinates
                text.Location.AlignH = AlignH.Right;
                text.Location.AlignV = AlignV.Center;
                // Disable the border and background fill options for the text
                text.FontSpec.Fill.IsVisible   = false;
                text.FontSpec.Border.IsVisible = false;
                myPane.GraphObjList.Add(text);
            }

            // Show the x axis grid
            myPane.XAxis.MajorGrid.IsVisible = true;

            myPane.XAxis.Scale.Min = 0;
            myPane.XAxis.Scale.Max = distance;

            // Make the Y axis scale red
            myPane.YAxis.Scale.FontSpec.FontColor = Color.Red;
            myPane.YAxis.Title.FontSpec.FontColor = Color.Red;
            // turn off the opposite tics so the Y tics don't show up on the Y2 axis
            myPane.YAxis.MajorTic.IsOpposite = false;
            myPane.YAxis.MinorTic.IsOpposite = false;
            // Don't display the Y zero line
            myPane.YAxis.MajorGrid.IsZeroLine = true;
            // Align the Y axis labels so they are flush to the axis
            myPane.YAxis.Scale.Align = AlignP.Inside;
            // Manually set the axis range
            //myPane.YAxis.Scale.Min = -1;
            //myPane.YAxis.Scale.Max = 1;

            // Fill the axis background with a gradient
            //myPane.Chart.Fill = new Fill(Color.White, Color.LightGray, 45.0f);

            // Calculate the Axis Scale Ranges
            try
            {
                zg1.AxisChange();
            }
            catch
            {
            }
        }
Beispiel #19
0
        public void Window_Loaded(object sender, RoutedEventArgs e)
        {
            GraphPane myPane1 = ze1.GraphPane;
            GraphPane myPane2 = ze2.GraphPane;
            GraphPane myPane3 = ze3.GraphPane;

            myPane1.Title.Text       = "F(x,y)";
            myPane1.XAxis.Title.Text = "x";
            myPane1.YAxis.Title.Text = "y";

            myPane2.Title.Text       = "F(x,y)";
            myPane2.XAxis.Title.Text = "x";
            myPane2.YAxis.Title.Text = "y";

            myPane3.Title.Text       = "F(x,y)";
            myPane3.XAxis.Title.Text = "x";
            myPane3.YAxis.Title.Text = "y";

            PointPairList list1 = new PointPairList();
            PointPairList list2 = new PointPairList();
            PointPairList list3 = new PointPairList();
            PointPairList list4 = new PointPairList();
            PointPairList list5 = new PointPairList();
            PointPairList list6 = new PointPairList();

            for (double x = x0; x <= xk; x += delta)
            {
                list1.Add(x, Func1(x));
                list2.Add(x, Func2(x));
            }
            LineItem myCurve1 = myPane1.AddCurve("x^2", list1, Color.Green, SymbolType.Triangle);

            myPane1.AddCurve("10x", list2, Color.Black, SymbolType.HDash);

            for (double x = x0; x <= 2.5; x += delta)
            {
                list3.Add(x, Func1(x));
                list4.Add(x, Func2(x));
            }
            LineItem myCurve2 = myPane2.AddCurve("x^2", list3, Color.Blue, SymbolType.Diamond);

            myPane2.AddCurve("10x", list4, Color.Brown, SymbolType.Plus);

            for (double x = 2.5; x <= xk; x += delta)
            {
                list5.Add(x, Func1(x));
                list6.Add(x, Func2(x));
            }

            LineItem myCurve3 = myPane3.AddCurve("x^2", list5, Color.DarkBlue, SymbolType.XCross);

            myPane3.AddCurve("10x", list6, Color.DarkGreen, SymbolType.TriangleDown);

            ze1.AxisChange();
            ze1.Invalidate();

            ze2.AxisChange();
            ze2.AxisChange();

            ze3.AxisChange();
            ze3.AxisChange();

            ze1.Invalidate();
            ze2.Invalidate();
            ze3.Invalidate();
        }
Beispiel #20
0
        private void PlotButton_Click(object sender, EventArgs e)
        {
            //очистка графических объектов
            dependencyGraphPanel.CurveList.Clear();
            phasePortraitPanel.CurveList.Clear();

            // формула для жертв
            Func <double, double, double> preyPop = (x, y) =>
                                                    x * ((double)PreyBirthRate.Value - (double)PreyDeathRate.Value * y);

            // формула для хищников
            Func <double, double, double> predatorPop = (x, y) =>
                                                        y * ((double)PredatorBirthRate.Value * x - (double)PredatorDeathRate.Value);

            // переменная для хранения точек графиков
            double[,] preyAndPredatorCurves;

            try
            {
                //получение точек для построения графиков
                preyAndPredatorCurves = RungeKutta.Rkf45(preyPop, predatorPop, (double)PreyPopulation.Value,
                                                         (double)PredatorPopulation.Value, (int)TimeSpan.Value, 0.01);

                //переменные для графических объектов
                PointPairList preySolution            = new PointPairList();
                PointPairList predatorSolution        = new PointPairList();
                PointPairList preyAndPredatorSolution = new PointPairList();
                //присваивание значений переменным для графических объектов
                for (int i = 0; i <= preyAndPredatorCurves.GetUpperBound(1); i++)
                {
                    preySolution.Add(preyAndPredatorCurves[2, i], preyAndPredatorCurves[0, i]);
                    predatorSolution.Add(preyAndPredatorCurves[2, i], preyAndPredatorCurves[1, i]);

                    preyAndPredatorSolution.Add(preyAndPredatorCurves[0, i], preyAndPredatorCurves[1, i]);
                }

                // Добавление кривой для жертв
                LineItem preyCurve = dependencyGraphPanel.AddCurve("Популяция жертв",
                                                                   preySolution, Color.Green, SymbolType.None);
                preyCurve.Line.Width    = 2;
                preyCurve.Line.IsSmooth = true;

                // Добавление кривой для хищников
                LineItem predatorCurve = dependencyGraphPanel.AddCurve("Популяция хищников",
                                                                       predatorSolution, Color.Red, SymbolType.None);
                predatorCurve.Line.Width    = 2;
                predatorCurve.Line.IsSmooth = true;

                //кривая для фазового портрета
                LineItem predatorAndPreyCurve = phasePortraitPanel.AddCurve("",
                                                                            preyAndPredatorSolution, Color.Red, SymbolType.None);
                predatorAndPreyCurve.Line.Width    = 2;
                predatorAndPreyCurve.Line.IsSmooth = true;
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message + "\nPlease enter smaller parameters", "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            // Изменение графиков в соответствии с кривыми
            dependencyGraphControl.AxisChange();
            dependencyGraphControl.Invalidate();

            phasePortraitGraphControl.AxisChange();
            phasePortraitGraphControl.Invalidate();
        }
        private void Button2_Click(object sender, EventArgs e)
        {
            double xmin;
            double xmax;
            bool   is_double1 = double.TryParse(textBox1.Text, out xmin);
            bool   is_double2 = double.TryParse(textBox2.Text, out xmax);

            if (is_double1 && is_double2)
            {
                График_Функции график_Функции = new График_Функции();
                GraphPane      pane           = график_Функции.zedGraphControl1.GraphPane;
                pane.CurveList.Clear();

                // Создадим список точек
                PointPairList list = new PointPairList();
                for (double x = xmin; x <= xmax; x += 0.00001)
                {
                    // добавим в список точку
                    list.Add(x, FunctionsApp.f(x));
                }
                LineItem myCurve = pane.AddCurve("f(x)", list, Color.Blue, SymbolType.None);
                pane.XAxis.MajorGrid.IsVisible = true;

                // Задаем вид пунктирной линии для крупных рисок по оси X:
                // Длина штрихов равна 10 пикселям, ...
                pane.XAxis.MajorGrid.DashOn = 10;

                // затем 5 пикселей - пропуск
                pane.XAxis.MajorGrid.DashOff = 5;


                // Включаем отображение сетки напротив крупных рисок по оси Y
                pane.YAxis.MajorGrid.IsVisible = true;

                // Аналогично задаем вид пунктирной линии для крупных рисок по оси Y
                pane.YAxis.MajorGrid.DashOn  = 10;
                pane.YAxis.MajorGrid.DashOff = 5;


                // Включаем отображение сетки напротив мелких рисок по оси X
                pane.YAxis.MinorGrid.IsVisible = true;

                // Задаем вид пунктирной линии для крупных рисок по оси Y:
                // Длина штрихов равна одному пикселю, ...
                pane.YAxis.MinorGrid.DashOn = 1;

                // затем 2 пикселя - пропуск
                pane.YAxis.MinorGrid.DashOff = 2;

                // Включаем отображение сетки напротив мелких рисок по оси Y
                pane.XAxis.MinorGrid.IsVisible = true;

                // Аналогично задаем вид пунктирной линии для крупных рисок по оси Y
                pane.XAxis.MinorGrid.DashOn  = 1;
                pane.XAxis.MinorGrid.DashOff = 2;
                // Вызываем метод AxisChange (), чтобы обновить данные об осях.
                // В противном случае на рисунке будет показана только часть графика,
                // которая умещается в интервалы по осям, установленные по умолчанию
                график_Функции.zedGraphControl1.AxisChange();

                // Обновляем график
                график_Функции.zedGraphControl1.Invalidate();
                график_Функции.Show();
            }
            else
            {
                MessageBox.Show("Неверный формат чисел", "Ошибка", MessageBoxButtons.OK);
            }
        }
Beispiel #22
0
        /// <summary>
        /// Refreshes the chart.
        /// </summary>

        protected void RefreshChart( )
        {
            GraphPane pane = chart1.GraphPane;

            pane.CurveList.Clear();
            pane.GraphObjList.Clear();

            // generate spectral gradients
            if (showSpectrumCheckBox.Checked)
            {
                pane.GraphObjList.Add(new BoxObj(400.0, 100.0, 40.0, 100.0, Color.Transparent, Color.FromArgb(spectrumAlpha, 170, 0, 255), Color.FromArgb(spectrumAlpha, 0, 0, 255)));
                pane.GraphObjList.Add(new BoxObj(440.0, 100.0, 50.0, 100.0, Color.Transparent, Color.FromArgb(spectrumAlpha, 0, 0, 255), Color.FromArgb(spectrumAlpha, 0, 255, 255)));
                pane.GraphObjList.Add(new BoxObj(490.0, 100.0, 20.0, 100.0, Color.Transparent, Color.FromArgb(spectrumAlpha, 0, 255, 255), Color.FromArgb(spectrumAlpha, 0, 255, 0)));
                pane.GraphObjList.Add(new BoxObj(510.0, 100.0, 70.0, 100.0, Color.Transparent, Color.FromArgb(spectrumAlpha, 0, 255, 0), Color.FromArgb(spectrumAlpha, 255, 255, 0)));
                pane.GraphObjList.Add(new BoxObj(580.0, 100.0, 65.0, 100.0, Color.Transparent, Color.FromArgb(spectrumAlpha, 255, 255, 0), Color.FromArgb(spectrumAlpha, 255, 0, 0)));
                pane.GraphObjList.Add(new BoxObj(645.0, 100.0, 55.0, 100.0, Color.Transparent, Color.FromArgb(spectrumAlpha, 255, 0, 0), Color.FromArgb(spectrumAlpha, 255, 0, 0)));

                foreach (var obj in pane.GraphObjList)
                {
                    obj.ZOrder = ZOrder.F_BehindGrid;
                    obj.IsClippedToChartRect = true;
                }
            }

            // draw D65 illuminant
            if (showCieD65CheckBox.Checked)
            {
                PointPairList list = new PointPairList();

                foreach (var entry in cieD65.Data)
                {
                    list.Add(entry.Key, entry.Value);
                }

                LineItem curve = pane.AddCurve("d65", list, Color.Gray, SymbolType.None);

                curve.IsY2Axis           = true;
                curve.Line.IsSmooth      = smoothCurvesCheckBox.Checked;
                curve.Line.SmoothTension = 0.5f;
            }

            // draw samples
            int measurementIndex = 0;

            foreach (var measurement in samples)
            {
                ++measurementIndex;

                PointPairList list = new PointPairList();

                foreach (var spectralDensity in measurement)
                {
                    list.Add(spectralDensity.Key, spectralDensity.Value);
                }

                LineItem curve = pane.AddCurve("s" + measurementIndex.ToString(), list, Color.Gray, SymbolType.None);

                curve.Line.IsSmooth      = smoothCurvesCheckBox.Checked;
                curve.Line.SmoothTension = 0.5f;
            }

            // redraw chart
            chart1.AxisChange();
            chart1.Invalidate();
        }
Beispiel #23
0
            /// <summary>
            /// Обновить содержание в графической субобласти "сутки по-часам"
            /// </summary>
            public void Draw(IEnumerable <HandlerSignalQueue.VALUE> srcValues
                             , string textConnSettType, string textDate)
            {
                double[] values     = null;
                int      itemscount = -1;
                Color    colorChart
                , colorPCurve;
                double minimum
                , minimum_scale
                , maximum
                , maximum_scale;
                bool noValues = false;

                itemscount = srcValues.Count();

                //names = new string[itemscount];

                values = new double[itemscount];

                minimum  = double.MaxValue;
                maximum  = double.MinValue;
                noValues = true;

                for (int i = 0; i < itemscount; i++)
                {
                    //names[i] = string.Format(@"{0}", new DateTime(TimeSpan.FromMinutes((i + 1) * 30).Ticks).ToString("HH:mm"));

                    values[i] = srcValues.ElementAt(i).value < 0 ? -1 * srcValues.ElementAt(i).value : srcValues.ElementAt(i).value;

                    if ((minimum > values[i]) && (!(values[i] == 0)))
                    {
                        minimum  = values[i];
                        noValues = false;
                    }
                    else
                    {
                        ;
                    }

                    if (maximum < values[i])
                    {
                        maximum = values[i];
                    }
                    else
                    {
                        ;
                    }
                }

                if (!(FormMain.formGraphicsSettings.scale == true))
                {
                    minimum = 0;
                }
                else
                {
                    ;
                }

                if (noValues)
                {
                    minimum_scale = 0;
                    maximum_scale = 10;
                }
                else
                {
                    if (minimum != maximum)
                    {
                        minimum_scale = minimum - (maximum - minimum) * 0.2;
                        if (minimum_scale < 0)
                        {
                            minimum_scale = 0;
                        }
                        maximum_scale = maximum + (maximum - minimum) * 0.2;
                    }
                    else
                    {
                        minimum_scale = minimum - minimum * 0.2;
                        maximum_scale = maximum + maximum * 0.2;
                    }
                }

                // получить цветовую гамму
                getColorZEDGraph((CONN_SETT_TYPE)Tag, out colorChart, out colorPCurve);

                GraphPane pane = GraphPane;

                pane.CurveList.Clear();
                pane.Chart.Fill = new Fill(colorChart);
                pane.Fill       = new Fill(BackColor);

                if (FormMain.formGraphicsSettings.m_graphTypes == FormGraphicsSettings.GraphTypes.Bar)
                {
                    pane.AddBar("Мощность", null, values, colorPCurve);
                }
                else
                if (FormMain.formGraphicsSettings.m_graphTypes == FormGraphicsSettings.GraphTypes.Linear)
                {
                    ////Вариант №1
                    //double[] valuesFactLinear = new double[itemscount];
                    //for (int i = 0; i < itemscount; i++)
                    //    valuesFactLinear[i] = valsMins[i];
                    //Вариант №2
                    PointPairList ppl = new PointPairList();
                    for (int i = 0; i < itemscount; i++)
                    {
                        if (values[i] > 0)
                        {
                            ppl.Add(i, values[i]);
                        }
                        else
                        {
                            ;
                        }
                    }
                    //LineItem
                    pane.AddCurve("Мощность"
                                  ////Вариант №1
                                  //, null, valuesFactLinear
                                  //Вариант №2
                                  , ppl
                                  , colorPCurve);
                }
                else
                {
                    ;
                }

                //// Ось X будет пересекаться с осью Y на уровне Y = 0
                //pane.XAxis.Cross = 65.0;
                //// Отключим отображение первых и последних меток по осям
                pane.XAxis.Scale.IsSkipFirstLabel = false;
                pane.XAxis.Scale.IsSkipLastLabel  = true;
                //// Отключим отображение меток в точке пересечения с другой осью
                //pane.XAxis.Scale.IsSkipCrossLabel = true;
                //// Спрячем заголовки осей
                //pane.XAxis.Title.IsVisible = false;

                //Для размещения в одной позиции ОДНого значения
                pane.BarSettings.Type = BarType.Overlay;

                //...из minutes
                pane.XAxis.Scale.Min       = 0.5;
                pane.XAxis.Scale.Max       = pane.XAxis.Scale.Min + itemscount;
                pane.XAxis.Scale.MinorStep = 1;
                pane.XAxis.Scale.MajorStep = itemscount / (itemscount / DIV_MAJOR_STEP);

                pane.XAxis.Type = AxisType.Linear; //...из minutes
                                                   //pane.XAxis.Type = AxisType.Text;
                pane.XAxis.Title.Text = "t, ЧЧ:мм";
                pane.YAxis.Title.Text = "P, кВт";
                pane.Title.Text       = textConnSettType;
                pane.Title.Text      += new string(' ', 29);
                pane.Title.Text      += textDate;

                //pane.XAxis.Scale.TextLabels = names;
                pane.XAxis.Scale.IsPreventLabelOverlap = true;

                // Включаем отображение сетки напротив крупных рисок по оси X
                pane.XAxis.MajorGrid.IsVisible = true;
                // Задаем вид пунктирной линии для крупных рисок по оси X:
                // Длина штрихов равна 10 пикселям, ...
                pane.XAxis.MajorGrid.DashOn = 10;
                // затем 5 пикселей - пропуск
                pane.XAxis.MajorGrid.DashOff = 5;
                // толщина линий
                pane.XAxis.MajorGrid.PenWidth = 0.1F;
                pane.XAxis.MajorGrid.Color    = FormMain.formGraphicsSettings.COLOR(FormGraphicsSettings.INDEX_COLOR.GRID);

                // Включаем отображение сетки напротив крупных рисок по оси Y
                pane.YAxis.MajorGrid.IsVisible = true;
                // Аналогично задаем вид пунктирной линии для крупных рисок по оси Y
                pane.YAxis.MajorGrid.DashOn  = 10;
                pane.YAxis.MajorGrid.DashOff = 5;
                // толщина линий
                pane.YAxis.MajorGrid.PenWidth = 0.1F;
                pane.YAxis.MajorGrid.Color    = FormMain.formGraphicsSettings.COLOR(FormGraphicsSettings.INDEX_COLOR.GRID);

                // Включаем отображение сетки напротив мелких рисок по оси Y
                pane.YAxis.MinorGrid.IsVisible = true;
                // Длина штрихов равна одному пикселю, ...
                pane.YAxis.MinorGrid.DashOn  = 1;
                pane.YAxis.MinorGrid.DashOff = 2;
                // толщина линий
                pane.YAxis.MinorGrid.PenWidth = 0.1F;
                pane.YAxis.MinorGrid.Color    = FormMain.formGraphicsSettings.COLOR(FormGraphicsSettings.INDEX_COLOR.GRID);

                // Устанавливаем интересующий нас интервал по оси Y
                pane.YAxis.Scale.Min = minimum_scale;
                pane.YAxis.Scale.Max = maximum_scale;

                AxisChange();

                Invalidate();
            }
        private void btnIniciarAG_Click(object sender, EventArgs e)
        {
            //Variaveis enriquecidas com os dados do txt
            double taxaMutacao   = double.Parse(txtTaxaMutacao.Text);
            double taxaCrossover = double.Parse(txtTaxaMutacao.Text);
            int    iteracoes     = int.Parse(txtIteracoes.Text);

            //Criar Algoritmo Genetico
            Class.AlgoritmoGenetico ag = new Class.AlgoritmoGenetico(taxaCrossover, taxaMutacao);

            for (int i = 0; i < iteracoes; i++)
            {
                pop = ag.executaAG(pop);

                mediaPopulacao.Add(i, pop.getMediaPopulacao());

                zedMediaPopulacao.GraphPane.CurveList.Clear(); //Limpar zed toda vez que o for é executado
                zedMediaPopulacao.GraphPane.GraphObjList.Clear();

                zedPopulacao.GraphPane.CurveList.Clear();
                zedPopulacao.GraphPane.GraphObjList.Clear();

                populacaoGrafico = new PointPairList();

                for (int j = 0; j < Constants.sizePopulacao; j++)
                {
                    populacaoGrafico.Add(pop.getPopulacao()[j].getInt(), pop.getPopulacao()[j].getFitness());
                }

                //Incluindo no gráfico
                LineItem media = paneMedia.AddCurve("Média", mediaPopulacao, Color.Red, SymbolType.None);
                LineItem func  = panePop.AddCurve("Função", curvaGrafico, Color.Red, SymbolType.None);
                LineItem indv  = panePop.AddStick("Individuo", populacaoGrafico, Color.Red);

                //Atualizar Valores
                zedPopulacao.AxisChange();
                zedPopulacao.Invalidate();
                zedPopulacao.Refresh();

                zedMediaPopulacao.AxisChange();
                zedMediaPopulacao.Invalidate();
                zedMediaPopulacao.Refresh();
            }

            //Ordenar novamente a população
            pop.OrdenarPopulacao();

            string pioresInds = string.Empty;

            for (int i = 0; i < 10; i++)
            {
                pioresInds += pop.getPopulacao()[i].PrintIndividuo() + "\n";
            }

            string melhoresInds = string.Empty;

            for (int i = Constants.sizePopulacao - 1; i > (Constants.sizePopulacao - 1) - 10; i--)
            {
                melhoresInds += pop.getPopulacao()[i].PrintIndividuo() + "\n";
            }

            //Imprimindo no Form
            txtMelhoresInd.Text = melhoresInds;
            txtPioresInd.Text   = pioresInds;
        }
        private void CreateChart(ZedGraphControl zgc, string table, string titre, Color couleurCourbe, Color couleurFond)
        {
            GraphPane myPane = zgc.GraphPane;

            // Set the titles and axis labels
            myPane.Title.Text       = titre;
            myPane.XAxis.Title.Text = "TEMPS (s)";
            myPane.YAxis.Title.Text = null;


            // Build a PointPairList with points based on Sine wave
            PointPairList list = new PointPairList();

            int ID_max = parent.BaseDeDonnees.DernierID(table);

            double x;
            double y;

            if (ID_max == 0)
            {
                myPane.XAxis.Scale.Min = 0;
                myPane.XAxis.Scale.Max = (TempsFenetre * 60) - 1;
            }
            else
            {
                if (ID_max > TempsFenetre * 60)
                {
                    for (int i = 0; i < ID_max; i++)
                    {
                        x = i;
                        y = parent.BaseDeDonnees.LireValeur(table, i + 1);

                        list.Add(x, y);
                    }
                    myPane.XAxis.Scale.Min = ID_max - (TempsFenetre * 60);
                    myPane.XAxis.Scale.Max = ID_max - 1;
                }
                else
                {
                    for (int i = 0; i < TempsFenetre * 60; i++)
                    {
                        if (i < ID_max)
                        {
                            x = i;
                            y = parent.BaseDeDonnees.LireValeur(table, i + 1);
                            list.Add(x, y);
                        }
                    }
                    myPane.XAxis.Scale.Min = 0;
                    myPane.XAxis.Scale.Max = (TempsFenetre * 60) - 1;
                }
            }

            // Hide the legend
            myPane.Legend.IsVisible = false;

            zgc.GraphPane.CurveList.Clear(); // effacer la vieille courbe

            // Add a curve
            LineItem curve = myPane.AddCurve("label", list, couleurCourbe, SymbolType.None);

            curve.Line.Width = 1.5F;
            //curve.Symbol.Fill = new Fill(Color.White);
            //curve.Symbol.Size = 5;

            // Make the XAxis start with the first label at 50
            myPane.XAxis.Scale.BaseTic = 50;

            // Fill the axis background with a gradient
            myPane.Chart.Fill = new Fill(couleurFond, couleurFond, 45.0F);

            // Calculate the Axis Scale Ranges
            zgc.AxisChange();

            // Refresh to paint the graph components
            Refresh();
        }
Beispiel #26
0
        public void initialDateAxis()
        {
            if (this.m_dtLine1 == null && this.m_dtLine2 == null)
            {
                return;
            }


            GraphPane myPane = base.GraphPane;

            // Set the titles and axis labels
            myPane.Title = this.m_strTitle;

            myPane.XAxis.Title = "日期";

            myPane.YAxis.Title = this.m_yAxisTitle;

            // Make up some data points based on the Sine function
            PointPairList list = new PointPairList();

            for (int i = 0; i < this.m_dtLine1.Rows.Count; i++)
            {
                DateTime dt = Convert.ToDateTime(this.m_dtLine1.Rows[i]["x"].ToString());

                double x = (double)new XDate(dt.Year, dt.Month, dt.Day);

                double y = Convert.ToDouble(this.m_dtLine1.Rows[i]["y"].ToString());

                list.Add(x, y);
            }

            PointPairList list1 = new PointPairList();

            for (int i = 0; i < this.m_dtLine2.Rows.Count; i++)
            {
                DateTime dt = Convert.ToDateTime(this.m_dtLine2.Rows[i]["x"].ToString());

                double x = (double)new XDate(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);

                double y = Convert.ToDouble(this.m_dtLine2.Rows[i]["y"].ToString());

                list1.Add(x, y);
            }

            int iCount = 0;

            string[] strXLabels;

            if (this.m_dtLine2.Rows.Count > this.m_dtLine1.Rows.Count)
            {
                iCount     = this.m_dtLine2.Rows.Count;
                strXLabels = new string[iCount];
                for (int i = 0; i < iCount; i++)
                {
                    DateTime dt = Convert.ToDateTime(this.m_dtLine2.Rows[i]["x"].ToString());

                    if (this.m_strState != "Day")
                    {
                        strXLabels[i] = String.Format("{0}-{1}-{2}", dt.Year.ToString(), dt.Month.ToString(), dt.Day.ToString());
                    }
                    else
                    {
                        strXLabels[i] = String.Format("{0}:{1}:{2}", dt.Hour.ToString(), dt.Minute.ToString(), dt.Second.ToString());
                    }
                }
            }
            else
            {
                iCount     = this.m_dtLine1.Rows.Count;
                strXLabels = new string[iCount];
                for (int i = 0; i < iCount; i++)
                {
                    DateTime dt = Convert.ToDateTime(this.m_dtLine1.Rows[i]["x"].ToString());

                    if (this.m_strState != "Day")
                    {
                        strXLabels[i] = String.Format("{0}-{1}-{2}", dt.Year.ToString(), dt.Month.ToString(), dt.Day.ToString());
                    }
                    else
                    {
                        strXLabels[i] = String.Format("{0}:{1}:{2}", dt.Hour.ToString(), dt.Minute.ToString(), dt.Second.ToString());
                    }
                }
            }
            // Generate a red curve with diamond
            // symbols, and "My Curve" in the legend
            LineItem myCurve = myPane.AddCurve(this.m_strLine1Name,
                                               list, Color.Red, SymbolType.Diamond);

            myCurve = myPane.AddCurve(this.m_strLine2Name,
                                      list1, Color.Green, SymbolType.Diamond);


            myPane.XAxis.Type       = AxisType.Text;
            myPane.XAxis.TextLabels = strXLabels;



            base.ZedGraphControl.AxisChange();
        }
Beispiel #27
0
        private void drawpressline(string name, int ID)
        {
            string    sql = "select dt,GP1,BP1 ,GP2,BP2,PA2,BPB2 from tblGRData where DeviceID =" + ID + " and dt>='" + this.dateTimePicker2.Value.ToString() + "' and dt<'" + dateTimePicker1.Value.ToString() + "' order by dt ";
            DataTable dt  = Tool.DB.getDt(sql);

            PointPairList list1 = new PointPairList();
            PointPairList list2 = new PointPairList();
            PointPairList list3 = new PointPairList();
            PointPairList list4 = new PointPairList();
            PointPairList list5 = new PointPairList();
            PointPairList list6 = new PointPairList();

            for (int j = 0; j < dt.Rows.Count; j++)
            {
                DateTime time = (DateTime)dt.Rows[j][0];
                double   x    = new XDate(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second);
                double   y    = Convert.ToDouble(dt.Rows[j][1]);
                list1.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][2]);
                list2.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][3]);
                list3.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][4]);
                list4.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][5]);
                list5.Add(x, y);
                y = Convert.ToDouble(dt.Rows[j][6]);
                list6.Add(x, y);
            }

            GraphPane myPane = zedGraphControl2.GraphPane;

            myPane.CurveList.Clear();
            this.zedGraphControl2.ZoomOutAll(myPane);
            myPane.Title.Text                = name + " " + dateTimePicker2.Value.ToString() + " 至 " + dateTimePicker1.Value.ToString() + " 压力曲线";
            myPane.XAxis.Title.Text          = "时间(h)";
            myPane.YAxis.Title.Text          = "压力(MPa)";
            myPane.XAxis.Type                = AxisType.Date;
            myPane.XAxis.MajorGrid.IsVisible = true;  //珊格子
            myPane.YAxis.MajorGrid.IsVisible = true;
            myPane.YAxis.Scale.Max           = 1;
            myPane.YAxis.Scale.Min           = 0;
            myPane.YAxis.Scale.MajorStep     = 0.1;
            myPane.XAxis.Scale.Format        = "MM/dd HH:mm";

            LineItem myCurve1 = null;

            if (checkBox3.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("一次供压MPa", list1, panel7.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox4.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("一次回压MPa", list2, panel9.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox5.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("二供次压MPa", list3, panel11.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox6.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("二次回压MPa", list4, panel13.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox7.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("压差设定MPa", list5, panel15.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (checkBox8.Checked == true)
            {
                myCurve1                  = myPane.AddCurve("补水设定MPa", list6, panel17.BackColor, SymbolType.None);
                myCurve1.Symbol.Size      = 2.5f;
                myCurve1.Line.Width       = 2.0F;
                myCurve1.Line.IsAntiAlias = true; //抗锯齿
            }
            if (myCurve1 == null)
            {
                MessageBox.Show("请选择某条曲线!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                return;
            }

            zedGraphControl2.IsShowPointValues = true;
            zedGraphControl2.PointValueEvent  += new ZedGraphControl.PointValueHandler(MyPointValueHandler);

            zedGraphControl2.AxisChange();
            zedGraphControl2.Invalidate();
        }
        private void btnEvaluate_Click(object sender, EventArgs e)
        {
            double time_step  = 0.1;
            double start_time = 0;
            double end_time   = 40;
            double mu         = 0;
            double sigma      = 0;
            double Kp         = 0.5;
            double Ki         = 0.5;
            double Kd         = 0.5;

            double.TryParse(txtTimeStep.Text, out time_step);
            double.TryParse(txtStartTime.Text, out start_time);
            double.TryParse(txtEndTime.Text, out end_time);
            double.TryParse(txtNoiseMean.Text, out mu);
            double.TryParse(txtNoiseSigma.Text, out sigma);
            double.TryParse(txtKd.Text, out Kd);
            double.TryParse(txtKp.Text, out Kp);
            double.TryParse(txtKi.Text, out Ki);

            mNoise.Mean   = mu;
            mNoise.StdDev = sigma;

            PIDController controller = FindController();
            IModel        model      = FindProblem();

            PointPairList setpoint_ppl       = new PointPairList();
            PointPairList state_value_ppl    = new PointPairList();
            PointPairList noise_ppl          = new PointPairList();
            PointPairList state_variable_ppl = new PointPairList();

            controller.MaxOutput = model.MaxOutput;
            controller.MinOutput = model.MinOutput;
            controller.Kp        = Kp;
            controller.Ki        = Ki;
            controller.Kd        = Kd;

            controller.ResetState();
            double state_value = 0;

            GraphPane gpane = chtTimeSeries.GraphPane;

            gpane.CurveList.Clear();

            if (chkDisplaySetpoints.Checked)
            {
                LineItem litem = gpane.AddCurve("Setpoint Trajectory", setpoint_ppl, Color.Blue);
                litem.Symbol.IsVisible = false;
            }

            if (chkDisplayControllerStateValue.Checked)
            {
                LineItem litem = gpane.AddCurve("State value Trajectory", state_value_ppl, Color.Red);
                litem.Symbol.IsVisible = false;
            }

            if (chkDisplayControllerStateVariable.Checked)
            {
                LineItem litem = gpane.AddCurve("State variable Trajectory", state_variable_ppl, Color.Black);
                litem.Symbol.IsVisible = false;
            }

            if (chkDisplayNoise.Checked)
            {
                LineItem litem = gpane.AddCurve("Noise Trajectory", noise_ppl, Color.Orange);
                litem.Symbol.IsVisible = false;
            }

            BackgroundWorker worker = new BackgroundWorker();

            worker.WorkerSupportsCancellation = true;
            worker.WorkerReportsProgress      = true;

            worker.DoWork += (s1, e1) =>
            {
                for (double time = start_time; time < end_time; time += time_step)
                {
                    double setpoint = model.getValue(time);

                    controller.Input    = state_value;
                    controller.Setpoint = setpoint;

                    double state_variable = controller.PerformPID();
                    double noise          = mNoise.Next();

                    state_value += state_variable;
                    state_value += noise;

                    setpoint_ppl.Add(time, setpoint);
                    state_value_ppl.Add(time, state_value);
                    noise_ppl.Add(time, noise);
                    state_variable_ppl.Add(time, state_variable);

                    worker.ReportProgress(0);
                }
            };
            worker.RunWorkerCompleted += (s1, e1) =>
            {
                gpane.AxisChange();
                chtTimeSeries.Invalidate();
            };

            worker.ProgressChanged += (s1, e1) =>
            {
                gpane.AxisChange();
                chtTimeSeries.Invalidate();

                DataTable table = new DataTable();
                table.Columns.Add("Time");
                table.Columns.Add("Setpoint");
                table.Columns.Add("StateValue");
                table.Columns.Add("StateVariable");
                table.Columns.Add("Noise");

                int point_count = setpoint_ppl.Count;

                for (int i = 0; i < point_count; ++i)
                {
                    table.Rows.Add(setpoint_ppl[i].X, setpoint_ppl[i].Y, state_value_ppl[i].Y, state_variable_ppl[i].Y, noise_ppl[i].Y);
                }

                dgvTimeSeries.DataSource = table;
            };
            worker.RunWorkerAsync();
        }
Beispiel #29
0
        private void UpdateArchiveGraph()
        {
            GraphPane g = _graphArchive.GraphPane;

            g.CurveList.Clear();

            var archive = _info.Archive();

            archive.Sort((a, b) => a.ID.CompareTo(b.ID));

            double[]      ii          = new double[archive.Count];
            double[]      score       = new double[archive.Count];
            double[]      averageWins = new double[archive.Count];
            double[]      averageRank = new double[archive.Count];
            PointPairList gold        = new PointPairList();

            double avgW = 0;
            double avgR = 0;

            for (int i = 0; i < ii.Length; i++)
            {
                ii[i]    = i;
                score[i] = archive[i].Score;

                avgR          += archive[i].Rank;
                averageRank[i] = avgR / (i + 1);

                avgW          += archive[i].Wins; //==avgR when single opponent
                averageWins[i] = avgW / (i + 1);

                if (archive[i].Wins == _info.OpponentPool.Length && archive[i].Rank == 1.0)
                {
                    gold.Add(new PointPair(i, score[i]));
                }
            }

            Color[] greyscale = new Color[4]
            {
                Color.FromArgb(180, 180, 180), //lightest
                Color.FromArgb(120, 120, 120),
                Color.FromArgb(60, 60, 60),
                Color.FromArgb(0, 0, 0) //darkest
            };

            var gp = g.AddCurve("Optimal Behavior", gold, greyscale[3], SymbolType.Diamond);

            gp.Line.IsVisible = false;
            gp.Symbol.Size    = 6;
            gp.Symbol.Fill    = new Fill(greyscale[3]);

            var ar = g.AddCurve("Average Rank", ii, averageRank, greyscale[2], SymbolType.None);

            ar.IsY2Axis   = true;
            ar.YAxisIndex = 1;
            ar.Line.Width = 3;

            var aw = g.AddCurve("Average Wins", ii, averageWins, greyscale[0], SymbolType.None);

            aw.IsY2Axis   = true;
            aw.Line.Width = 3;

            var s = g.AddCurve("Behavior", ii, score, greyscale[1], SymbolType.HDash);

            s.Line.IsVisible = false;
            s.Symbol.Size    = 3;

            _graphArchive.AxisChange();
        }
Beispiel #30
0
        private void Form_Update_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                switch (stateForm)
                {
                case WorkState.Idle:
                    EnableControl(false);
                    break;

                case WorkState.Update:
                    EnableControl(true);
                    if (state == State.New)
                    {
                        tick++;
                        RED.Add(tick, Regs.Red_freq);
                        BLUE.Add(tick, Regs.Blue_freq);
                        GREEN.Add(tick, Regs.Green_freq);
                        WHITE.Add(tick, Regs.White_freq);
                        Drop.Add(tick, Regs.Drop_ADC);
                        IR.Add(tick, Regs.Ir_ADC);
                        myPane.CurveList.Clear();
                        myPane2.CurveList.Clear();
                        myPane3.CurveList.Clear();
                        LineItem Curve  = myPane.AddCurve("RED", RED, Color.Red, SymbolType.None);
                        LineItem Curve1 = myPane.AddCurve("BLUE", BLUE, Color.Blue, SymbolType.None);
                        LineItem Curve2 = myPane.AddCurve("GREEN", GREEN, Color.Green, SymbolType.None);
                        LineItem Curve3 = myPane.AddCurve("WHITE", WHITE, Color.Black, SymbolType.None);

                        LineItem Curve4 = myPane2.AddCurve("DropADC", Drop, Color.Black, SymbolType.None);



                        LineItem IR_line = myPane3.AddCurve("IR", IR, Color.Black, SymbolType.None);



                        zedGraphControl1.AxisChange();
                        DropGraph.AxisChange();
                        IR_graph.AxisChange();
                        // Обновляем график
                        zedGraphControl1.Invalidate();
                        DropGraph.Invalidate();
                        IR_graph.Invalidate();
                        DropVal.Invoke((MethodInvoker) delegate
                        {
                            DropVal.Text = Regs.Drop_ADC.ToString();
                        });
                        //DropVal.Text = Regs.Drop_ADC.ToString();

                        TempVal.Invoke((MethodInvoker) delegate
                        {
                            TempVal.Text = Regs.Temperature.ToString();
                        });
                        // TempVal.Text = Regs.Temperature.ToString();

                        scale_color();

                        state = State.Read;
                    }
                    break;
                }
            }

            //throw new NotImplementedException();
        }
        public void CreateResultScatterplot(ZedGraphControl zgc, double[][] inputs, double[] expected, double[] output)
        {
            GraphPane myPane = zgc.GraphPane;

            myPane.CurveList.Clear();

            // Set the titles
            myPane.Title.IsVisible  = false;
            myPane.XAxis.Title.Text = sourceColumns[0];
            myPane.YAxis.Title.Text = sourceColumns[1];



            // Classification problem
            PointPairList list1 = new PointPairList(); // Z = -1, OK
            PointPairList list2 = new PointPairList(); // Z = +1, OK
            PointPairList list3 = new PointPairList(); // Z = -1, Error
            PointPairList list4 = new PointPairList(); // Z = +1, Error

            for (int i = 0; i < output.Length; i++)
            {
                if (output[i] == -1)
                {
                    if (expected[i] == -1)
                    {
                        list1.Add(inputs[i][0], inputs[i][1]);
                    }
                    if (expected[i] == 1)
                    {
                        list3.Add(inputs[i][0], inputs[i][1]);
                    }
                }
                else
                {
                    if (expected[i] == -1)
                    {
                        list4.Add(inputs[i][0], inputs[i][1]);
                    }
                    if (expected[i] == 1)
                    {
                        list2.Add(inputs[i][0], inputs[i][1]);
                    }
                }
            }

            // Add the curve
            LineItem
                myCurve = myPane.AddCurve("G1 Hits", list1, Color.Blue, SymbolType.Diamond);

            myCurve.Line.IsVisible          = false;
            myCurve.Symbol.Border.IsVisible = false;
            myCurve.Symbol.Fill             = new Fill(Color.Blue);

            myCurve = myPane.AddCurve("G2 Hits", list2, Color.Green, SymbolType.Diamond);
            myCurve.Line.IsVisible          = false;
            myCurve.Symbol.Border.IsVisible = false;
            myCurve.Symbol.Fill             = new Fill(Color.Green);

            myCurve = myPane.AddCurve("G1 Miss", list3, Color.Blue, SymbolType.Plus);
            myCurve.Line.IsVisible          = false;
            myCurve.Symbol.Border.IsVisible = true;
            myCurve.Symbol.Fill             = new Fill(Color.Blue);

            myCurve = myPane.AddCurve("G2 Miss", list4, Color.Green, SymbolType.Plus);
            myCurve.Line.IsVisible          = false;
            myCurve.Symbol.Border.IsVisible = true;
            myCurve.Symbol.Fill             = new Fill(Color.Green);


            // Fill the background of the chart rect and pane
            myPane.Fill = new Fill(Color.WhiteSmoke);

            zgc.AxisChange();
            zgc.Invalidate();
        }
        /// <summary>
        /// Renders the demo graph with one call.
        /// </summary>
        /// <param name="g">A <see cref="Graphics"/> object for which the drawing will be done.</param>
        /// <param name="pane">A reference to the <see cref="GraphPane"/></param>
        public static void RenderDemo(IGraphics g, GraphPane pane)
        {
            // Set the titles and axis labels
            pane.Title.Text = "Wacky Widget Company\nProduction Report";
            pane.XAxis.Title.Text = "Time, Days\n(Since Plant Construction Startup)";
            pane.YAxis.Title.Text = "Widget Production\n(units/hour)";

            LineItem curve;

            // Set up curve "Larry"
            double[] x = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
            double[] y = {20, 10, 50, 25, 35, 75, 90, 40, 33, 50};
            // Use green, with circle symbols
            curve = pane.AddCurve("Larry", x, y, Color.Green, SymbolType.Circle);
            curve.Line.Width = 1.5F;
            // Fill the area under the curve with a white-green gradient
            curve.Line.Fill = new Fill(Color.White, Color.FromArgb(60, 190, 50), 90F);
            // Make it a smooth line
            curve.Line.IsSmooth = true;
            curve.Line.SmoothTension = 0.6F;
            // Fill the symbols with white
            curve.Symbol.Fill = new Fill(Color.White);
            curve.Symbol.Size = 10;

            // Second curve is "moe"
            double[] x3 = {150, 250, 400, 520, 780, 940};
            double[] y3 = {5.2, 49.0, 33.8, 88.57, 99.9, 36.8};
            // Use a red color with triangle symbols
            curve = pane.AddCurve("Moe", x3, y3, Color.FromArgb(200, 55, 135), SymbolType.Triangle);
            curve.Line.Width = 1.5F;
            // Fill the area under the curve with semi-transparent pink using the alpha value
            curve.Line.Fill = new Fill(Color.White, Color.FromArgb(160, 230, 145, 205), 90F);
            // Fill the symbols with white
            curve.Symbol.Fill = new Fill(Color.White);
            curve.Symbol.Size = 10;

            // Third Curve is a bar, called "Wheezy"
            double[] x4 = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
            double[] y4 = {30, 45, 53, 60, 75, 83, 84, 79, 71, 57};
            BarItem bar = pane.AddBar("Wheezy", x4, y4, Color.SteelBlue);
            // Fill the bars with a RosyBrown-White-RosyBrown gradient
            bar.Bar.Fill = new Fill(Color.RosyBrown, Color.White, Color.RosyBrown);

            // Fourth curve is a bar
            double[] x2 = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
            double[] y2 = {10, 15, 17, 20, 25, 27, 29, 26, 24, 18};
            bar = pane.AddBar("Curly", x2, y2, Color.RoyalBlue);
            // Fill the bars with a RoyalBlue-White-RoyalBlue gradient
            bar.Bar.Fill = new Fill(Color.RoyalBlue, Color.White, Color.RoyalBlue);

            // Fill the pane background with a gradient
            pane.Fill = new Fill(Color.WhiteSmoke, Color.Lavender, 0F);
            // Fill the axis background with a gradient
            pane.Chart.Fill = new Fill(Color.FromArgb(255, 255, 245),
                                       Color.FromArgb(255, 255, 190), 90F);

            // Make each cluster 100 user scale units wide.  This is needed because the X Axis
            // type is Linear rather than Text or Ordinal
            pane.BarSettings.ClusterScaleWidth = 100;
            // Bars are stacked
            pane.BarSettings.Type = BarType.Stack;

            // Enable the X and Y axis grids
            pane.XAxis.MajorGrid.IsVisible = true;
            pane.YAxis.MajorGrid.IsVisible = true;

            // Manually set the scale maximums according to user preference
            pane.XAxis.Scale.Max = 1200;
            pane.YAxis.Scale.Max = 120;

            // Add a text item to decorate the graph
            var text = new TextObj("First Prod\n21-Oct-93", 175F, 80.0F);
            // Align the text such that the Bottom-Center is at (175, 80) in user scale coordinates
            text.Location.AlignH = AlignH.Center;
            text.Location.AlignV = AlignV.Bottom;
            text.FontSpec.Fill = new Fill(Color.White, Color.PowderBlue, 45F);
            text.FontSpec.StringAlignment = StringAlignment.Near;
            pane.GraphObjList.Add(text);

            // Add an arrow pointer for the above text item
            var arrow = new ArrowObj(Color.Black, 12F, 175F, 77F, 100F, 45F);
            arrow.Location.CoordinateFrame = CoordType.AxisXYScale;
            pane.GraphObjList.Add(arrow);

            // Add a another text item to to point out a graph feature
            text = new TextObj("Upgrade", 700F, 50.0F);
            // rotate the text 90 degrees
            text.FontSpec.Angle = 90;
            // Align the text such that the Right-Center is at (700, 50) in user scale coordinates
            text.Location.AlignH = AlignH.Right;
            text.Location.AlignV = AlignV.Center;
            // Disable the border and background fill options for the text
            text.FontSpec.Fill.IsVisible = false;
            text.FontSpec.Border.IsVisible = false;
            pane.GraphObjList.Add(text);

            // Add an arrow pointer for the above text item
            arrow = new ArrowObj(Color.Black, 15, 700, 53, 700, 80);
            arrow.Location.CoordinateFrame = CoordType.AxisXYScale;
            arrow.Line.Width = 2.0F;
            pane.GraphObjList.Add(arrow);

            // Add a text "Confidential" stamp to the graph
            text = new TextObj("Confidential", 0.85F, -0.03F);
            // use ChartFraction coordinates so the text is placed relative to the ChartRect
            text.Location.CoordinateFrame = CoordType.ChartFraction;
            // rotate the text 15 degrees
            text.FontSpec.Angle = 15.0F;
            // Text will be red, bold, and 16 point
            text.FontSpec.FontColor = Color.Red;
            text.FontSpec.IsBold = true;
            text.FontSpec.Size = 16;
            // Disable the border and background fill options for the text
            text.FontSpec.Border.IsVisible = false;
            text.FontSpec.Fill.IsVisible = false;
            // Align the text such the the Left-Bottom corner is at the specified coordinates
            text.Location.AlignH = AlignH.Left;
            text.Location.AlignV = AlignV.Bottom;
            pane.GraphObjList.Add(text);

            // Add a BoxObj to show a colored band behind the graph data
            var box = new BoxObj(0, 110, 1200, 10,
                                 Color.Empty, Color.FromArgb(225, 245, 225));
            box.Location.CoordinateFrame = CoordType.AxisXYScale;
            // Align the left-top of the box to (0, 110)
            box.Location.AlignH = AlignH.Left;
            box.Location.AlignV = AlignV.Top;
            // place the box behind the axis items, so the grid is drawn on top of it
            box.ZOrder = ZOrder.D_BehindAxis;
            pane.GraphObjList.Add(box);

            // Add some text inside the above box to indicate "Peak Range"
            var myText = new TextObj("Peak Range", 1170, 105);
            myText.Location.CoordinateFrame = CoordType.AxisXYScale;
            myText.Location.AlignH = AlignH.Right;
            myText.Location.AlignV = AlignV.Center;
            myText.FontSpec.IsItalic = true;
            myText.FontSpec.IsBold = false;
            myText.FontSpec.Fill.IsVisible = false;
            myText.FontSpec.Border.IsVisible = false;
            pane.GraphObjList.Add(myText);

            pane.AxisChange(g);
        }