示例#1
0
        void ComputeTransformation()
        {
            // Generate a test signal,
            //  1 Vrms at 20,000 Hz
            //  Sampling Rate = 100,000 Hz
            //  DFT Length is 1000 Points
            double frequency    = double.Parse(Frequency, cultureUS);
            UInt32 lengthSample = UInt32.Parse(Lenght, cultureUS);
            UInt32 zeros        = UInt32.Parse(ZerosNumber, cultureUS);
            double samplingRate = double.Parse(SamplingFrequency);

            Argument timeArg, frequencyArg;

            org.mariuszgromada.math.mxparser.Expression expression;

            FttHelper.GetExpressionFromString(FunctionToFFT, out timeArg, out frequencyArg, out expression);

            double[] inputSignal = FttHelper.GetInputData(frequency, lengthSample, samplingRate, timeArg, frequencyArg, expression);


            // Apply window to the time series data
            double[] wc = DSP.Window.Coefficients((DSP.Window.Type)Enum.Parse(typeof(DSP.Window.Type), WindowFunction), lengthSample);

            double windowScaleFactor = DSP.Window.ScaleFactor.Signal(wc);

            double[] windowedTimeSeries = DSP.Math.Multiply(inputSignal, wc);


            _oldShiftValue = IsShift;
            if (IsFFT)
            {
                FFT fft = new();
                fft.Initialize(lengthSample, zeros, fullFrequencyData: IsShift);
                _cSpectrum = fft.Execute(windowedTimeSeries);
                _cSpectrum = fft.ShiftData(_cSpectrum, IsShift);

                _freqSpan = fft.FrequencySpan(samplingRate);
            }
            else
            {
                // Instantiate a new DFT
                DFT dft = new DFT();
                // Initialize the DFT
                // You only need to do this once or if you change any of the DFT parameters.

                dft.Initialize(lengthSample, zeros, fullFrequency: IsShift);
                // Call the DFT and get the scaled spectrum back
                _cSpectrum = dft.Execute(windowedTimeSeries);
                _cSpectrum = dft.ShiftData(_cSpectrum, IsShift);
                // For plotting on an XY Scatter plot, generate the X Axis frequency Span
                _freqSpan = dft.FrequencySpan(samplingRate);
            }



            // Note: At this point, lmSpectrum is a 501 byte array that
            // contains a properly scaled Spectrum from 0 - 50,000 Hz (1/2 the Sampling Frequency)


            // Convert the complex spectrum to magnitude

            double[] lmSpectrum = DSP.ConvertComplex.ToMagnitude(_cSpectrum);
            IsMagnitude = true;
            // double[] lmSpectrum = _cSpectrum.ToList().Select(a => a.Magnitude).ToArray();

            // At this point a XY Scatter plot can be generated from,
            // X axis => freqSpan
            // Y axis => lmSpectrum

            // In this example, the maximum value of 1 Vrms is located at bin 200 (20,000 Hz)


            // XAxe = ChartHelper.GetXAxisLabelForFrequencyCart(freqSpan);
            SeriesFrequency = ChartHelper.GetSeriesFrequency(lmSpectrum, _freqSpan, IsShift);

            // ((LineSeries<DataModel>)SeriesFrequency[0]).GeometryFill.StrokeThickness = 0.5f;


            SeriesTime = ChartHelper.GetSeriesTime(windowedTimeSeries, samplingRate);
        }
示例#2
0
 public Report GetReport(int projectID)
 {
     using (DataAccessLayer modelAccess = new DataAccessLayer())
     {
         Project p = modelAccess.GetProject(projectID);
         if (p == null)
         {
             return(null);
         }
         Report report = new Report();
         report.ProjectName = p.ProjectName;
         report.sprintNames.Add("Start");
         report.sprintNames.AddRange(p.Iterations.Select(i => i.SprintName).ToList());
         report.TotalEffort = p.ProductBacklogItems.Sum(pbi => pbi.EffortScore ?? 0);
         report.projectBurndownData.Add(report.TotalEffort);
         report.sprintVelocities.Add(0);
         foreach (Iteration i in p.Iterations)
         {
             List <ProductBacklogItem> pbis =
                 i.ProductBacklogItems.Where(pbi => pbi.DateFinished.HasValue)
                 .Where(
                     result =>
                     result.DateFinished.Value > i.SprintStartDate &&
                     result.DateFinished.Value < i.SprintEndDate)
                 .ToList();
             int sum = pbis.Where(item => item.EffortScore.HasValue).Sum(pbi => pbi.EffortScore.Value);
             report.projectBurndownData.Add((report.projectBurndownData.Last() - sum));
             report.sprintVelocities.Add(sum);
             report.TotalBacklogItemsFinished += pbis.Count;
             foreach (ProductBacklogItem pbi in pbis)
             {
                 foreach (BacklogItemTask t in pbi.Tasks)
                 {
                     if (t.CurrentUserID.HasValue)
                     {
                         User u = modelAccess.GetUser(t.CurrentUserID.Value);
                         if (report.TotalTasksFinishedByUser.Count(item => item.UserName == u.UserName) == 1)
                         {
                             UserTaskCount userTaskCount =
                                 report.TotalTasksFinishedByUser.First(utc => utc.UserName == u.UserName);
                             userTaskCount.TaskCount++;
                         }
                         else
                         {
                             report.TotalTasksFinishedByUser.Add(new UserTaskCount()
                             {
                                 TaskCount = 1,
                                 UserName  = u.UserName
                             });
                         }
                     }
                 }
             }
         }
         int sumOfVelocities   = report.sprintVelocities.Where(vel => vel != 0).Sum();
         int countOfVelocities = report.sprintVelocities.Count(vel => vel != 0);
         if (countOfVelocities == 0 || sumOfVelocities == 0)
         {
             report.CurrentAverageVelocity = 0;
         }
         else
         {
             report.CurrentAverageVelocity = sumOfVelocities / countOfVelocities;
         }
         report.VelocityChart = ChartHelper.BarChart(
             ChartHelper.ClearBlue("rgba"),
             ChartHelper.Black("rgba"),
             ChartHelper.ClearBlue("rgba"),
             ChartHelper.ClearWhite("rgba"),
             report.sprintNames,
             "Project Velocities",
             report.sprintVelocities
             );
         report.BurndownChart = ChartHelper.LineGraph(
             ChartHelper.ClearBlue("rgba"),
             ChartHelper.Black("rgba"),
             ChartHelper.ClearWhite("rgba"),
             ChartHelper.Black("hex"),
             ChartHelper.DarkGreen("hex"),
             ChartHelper.Black("rgba"),
             report.sprintNames,
             "Burndown Chart",
             report.projectBurndownData
             );
         return(report);
     }
 }
示例#3
0
 public static void Show(Form owner, ISelectionHolder selectionHolder, Core core, ChartHelper chart)
 {
     using (FrmPopoutPlot frm = new FrmPopoutPlot(selectionHolder, core, chart))
     {
         frm.ShowDialog(owner);
     }
 }
示例#4
0
        public void ProcessFiles(List <string> files)
        {
            WorkAsync(new WorkAsyncInfo
            {
                Message          = "Analyzing file(s)...",
                AsyncArgument    = files,
                Work             = (bw, e) => { e.Result = ChartHelper.AnalyzeFiles((List <string>)e.Argument, Service); },
                PostWorkCallBack = evt =>
                {
                    var results = (List <ChartDefinition>)evt.Result;
                    if (results.Any(r => r.Errors.Count > 0))
                    {
                        // Display errors
                        var elForm = new ErrorsListForm(results);
                        elForm.ShowDialog(ParentForm);
                    }
                    else
                    {
                        if (results.Any(r => r.Exists))
                        {
                            // Display overwrite confirmation
                            var ocDialog = new OverwriteConfirmationDialog(results);
                            var result   = ocDialog.ShowDialog(ParentForm);
                            if (result == DialogResult.Cancel)
                            {
                                return;
                            }
                        }

                        WorkAsync(new WorkAsyncInfo("Importing file(s)...", (w, evt2) =>
                        {
                            ChartHelper.ImportFiles((List <ChartDefinition>)evt2.Argument, Service);

                            w.ReportProgress(0, "Publishing entities...");

                            Service.Execute(new PublishXmlRequest
                            {
                                ParameterXml = string.Format("<importexportxml><entities>{0}</entities><nodes/><securityroles/><settings/><workflows/></importexportxml>", string.Join("", results.Select(r => string.Format("<entity>{0}</entity>", r.Entity.GetAttributeValue <string>("primaryentitytypecode")))))
                            });
                        })
                        {
                            AsyncArgument    = results,
                            PostWorkCallBack = evt2 =>
                            {
                                if (evt2.Error != null)
                                {
                                    MessageBox.Show(ParentForm, evt2.Error.Message, "Error",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                                else
                                {
                                    MessageBox.Show(ParentForm, "Chart(s) imported!", "Information",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    lvEntities_SelectedIndexChanged(null, null);
                                }
                            },
                            ProgressChanged = evt2 =>
                            {
                                SetWorkingMessage(evt2.UserState.ToString());
                            }
                        });
                    }
                }
            });
        }
示例#5
0
        private void sendReport(UserTable userModel, DateTime currentDate)
        {
            // Rapor taslağı oluştur
            // GEçen haftanın verileri gelir

            ChartHelper   chartHelper = new ChartHelper();
            StringBuilder sb          = new StringBuilder();
            var           lastMonday  = Convert.ToDateTime(currentDate.AddDays(-(int)currentDate.DayOfWeek - 6).ToShortDateString());

            currentDate = Convert.ToDateTime(currentDate.ToShortDateString());


            sb.AppendLine("Geçen Hafta Alınan Ve Kapatılan Hatalar Durumu");
            var openAndClosedErrorsCountList = chartHelper.getErrorCountThisMonthWithDate(lastMonday, currentDate); // geçen haftadan şuana kadar geçen 1 haftalık veriler

            foreach (var item in openAndClosedErrorsCountList)
            {
                sb.AppendLine(item.label + " :" + item.y.ToString());
            }
            sb.AppendLine("--------------------------------------");

            sb.AppendLine("Geçen Hafta Oluşturulan Hata Sayıları");
            var createdErrorCountList = chartHelper.getErrorCountDayByDayInOneMonthWithDate(lastMonday, currentDate); // geçen haftadan şuana kadar geçen 1 haftalık veriler

            foreach (var item in createdErrorCountList)
            {
                sb.AppendLine(item.label + " :" + item.y.ToString());
            }
            sb.AppendLine("--------------------------------------");

            sb.AppendLine("Geçen Hafta Günlük Kapatılan Hatalar");
            var closedErrorsDayByDayList = chartHelper.getClosedErrorDayByDayIMonthWithDate(lastMonday, currentDate); // geçen haftadan şuana kadar geçen 1 haftalık veriler

            foreach (var item in closedErrorsDayByDayList)
            {
                sb.AppendLine(item.label + " :" + item.y.ToString());
            }
            sb.AppendLine("--------------------------------------");

            sb.AppendLine("Geçen Haftanın Hata Kaynakları");
            var errorSourceList = chartHelper.getErrorResourceChartDataWithDate(lastMonday, currentDate); // geçen haftadan şuana kadar geçen 1 haftalık veriler

            foreach (var item in errorSourceList)
            {
                sb.AppendLine(item.label + " :" + item.y.ToString());
            }
            sb.AppendLine("--------------------------------------");

            sb.AppendLine("Geçen Hafta Hata Alınan Müşteriler");
            var companyNamesList = chartHelper.getCompanyNameAndCountPieChartWithDate(lastMonday, currentDate); // geçen haftadan şuana kadar geçen 1 haftalık veriler

            foreach (var item in companyNamesList)
            {
                sb.AppendLine(item.label + " :" + item.y.ToString());
            }
            sb.AppendLine("--------------------------------------");

            sb.AppendLine("Geçen Haftadaki Son Adımlar");
            var lastStepsList = chartHelper.getLastStepsInMonthWithDate(lastMonday, currentDate); // geçen haftadan şuana kadar geçen 1 haftalık veriler

            foreach (var item in lastStepsList)
            {
                sb.AppendLine(item.label + " :" + item.y.ToString());
            }
            sb.AppendLine("--------------------------------------");

            sb.AppendLine("Geçen Haftadaki Referans Numaraları");
            var errorReferenceList = chartHelper.getReferenceNumberCountThisMonthWithDate(lastMonday, currentDate); // geçen haftadan şuana kadar geçen 1 haftalık veriler

            foreach (var item in errorReferenceList)
            {
                sb.AppendLine(item.label + " :" + item.y.ToString());
            }
            sb.AppendLine("--------------------------------------");


            sb.AppendLine("Geçen Haftadaki Hata Tanımları");
            var errorDefineList = chartHelper.getThisMonthErrorDefinesWithDate(lastMonday, currentDate); // geçen haftadan şuana kadar geçen 1 haftalık veriler

            foreach (var item in errorDefineList)
            {
                sb.AppendLine(item.label + " :" + item.y.ToString());
            }
            sb.AppendLine("--------------------------------------");



            sb.AppendLine("Geçen Haftadaki En Çok Hatalı Parça");
            var mostWrong10PartList = chartHelper.getMostWrong10PartThisMonthWithDate(lastMonday, currentDate); // geçen haftadan şuana kadar geçen 1 haftalık veriler

            foreach (var item in mostWrong10PartList)
            {
                sb.AppendLine(item.label.Trim() + " :" + item.y.ToString());
            }
            sb.AppendLine("--------------------------------------");

            senMailForSuperUsers(sb, lastMonday, currentDate);
        }
 private void DailyActivities()
 {
     lblDailyActivities.Text = "DAILY ACTIVITIES (" + DateTime.Now.ToString("dd-MMM-yyyy") + ")";
     DataTable dt = new DataTable();
     string qry = "EXEC GetDailyActivities";
     dt = am.DataAccess.RecordSet(qry, new string[] { });
     ChartHelper ch = new ChartHelper("ProcessType21", 310, 200, Telerik.Web.UI.HtmlChart.ChartLegendPosition.Bottom);
     ch.CreateChart(HtmlChartHolderBarHorTopLeft, ChartHelper.ChartType.BarChartHorizontalDA, dt, new string[] { "Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red" });
 }
示例#7
0
 /// <summary>
 /// 突跳处理->删除法
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void  除法ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     this.label1.Text = "突跳处理->删除法";
     ChangeChart(ChartHelper.GetPointDeleteChart());
 }
示例#8
0
 private void 指数e拟合ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     this.label1.Text = "台阶处理→多点趋势平移法→指数e拟合";
     ChangeChart(ChartHelper.GetMultiPointExpProcessChart());
 }
示例#9
0
        private double GetCleanNumberValue(string toString)
        {
            var cleanString = toString.Replace("$", "").Replace("%", "");

            return(ChartHelper.ParseDouble(cleanString, providerEn, EpmChartAggregateType.GetByName(PropChartAggregationType)));
        }
示例#10
0
 /// <summary>
 /// 突跳处理->图解法
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void 图解法ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     this.label1.Text = "突跳→图解法";
     this.toolTip1.SetToolTip(this.label1, "直接拖动数据点即可显示数据点的值");
     ChangeChart(ChartHelper.GetPointMovingChart());
 }
示例#11
0
        private void Start_Click(object sender, EventArgs e)
        {
            //pictureBox2.Image = SandDiameterMeasuring.Properties.Resources.屏幕截图_1654_;
            // pictureBox2.Image.Dispose();
            // pictureBox2.Image = null;
            textBox1.Text = ("加载图片");
            OpenFileDialog file = new OpenFileDialog();

            file.InitialDirectory = ".";
            file.Filter           = "所有文件(*.*)|*.*";
            file.ShowDialog();
            if (file.FileName != string.Empty)
            {
                try
                {
                    pathname = file.FileName;   //获得文件的绝对路径
                    this.pictureBox1.Load(pathname);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            Stopwatch sw = new Stopwatch();

            sw.Start();
            string str1 = file.FileName;

            //str1 = "'" + str1 + "'";//加单引号为符合matlab输入规范
            textBox1.Text = (str1);

            linktocsharpV6.Class1 v5c1 = new linktocsharpV6.Class1();
            //MWArray DiameterArray = v3c1.linktocsharpV3(str1);
            MWArray[] resultlist = new MWArray[2];
            resultlist = v5c1.linktocsharpV6(5, str1);                     //重要!!!m函数有多个返回值时在第一个参数里写入返回值个数,第二个参数才是输入m函数的第一个输入参数
            MWNumericArray DiameterArray  = (MWNumericArray)resultlist[0]; //返回每一粒沙子的直径数组,为n行1列的二维数组
            MWNumericArray SandNumber     = (MWNumericArray)resultlist[1]; //沙尘个数
            MWNumericArray DiameterNumber = (MWNumericArray)resultlist[2]; //返回以50um为单位的粒径累加结果数组
            MWNumericArray xlength        = (MWNumericArray)resultlist[3]; //返回粒径累加结果数组长度
            MWNumericArray TypeNumber     = (MWNumericArray)resultlist[4]; //返回三种沙粒:石砾,粗沙粒,细沙粒个数数组

            textBox2.Text = SandNumber.ToString();
            double[,] DA  = new double[(int)SandNumber, 1]; //matlab函数返回值为二维数组,因此需要用二维数组接收
            DA            = (double[, ])DiameterArray.ToArray();
            double[,] DN  = new double[(int)xlength, 1];    //matlab函数返回值为二维数组,因此需要用二维数组接收
            DN            = (double[, ])DiameterNumber.ToArray();
            double[,] TN  = new double[3, 1];               //matlab函数返回值为二维数组,因此需要用二维数组接收
            TN            = (double[, ])TypeNumber.ToArray();
            //textBox3.Text = DA[(int)a2 - 1, 0].ToString();
            //textBox3.Text = DA[(int)SandNumber - 1, 0].ToString();

            chart1.Series.Clear();
            ChartHelper.AddSeries(chart1, "由小到大每一粒沙尘的粒径", SeriesChartType.Column, Color.Transparent, Color.Red, true);
            //   ChartHelper.AddSeries(chart1, "由小到大每一粒沙尘的粒径", SeriesChartType.Spline, Color.Red, Color.Red);
            //   ChartHelper.SetTitle(chart1, "由小到大每一粒沙尘的粒径", new Font("微软雅黑", 8), Docking.Top, Color.Black);
            ChartHelper.SetStyle(chart1, Color.Transparent, Color.Black);
            ChartHelper.SetLegend(chart1, Docking.Top, StringAlignment.Center, Color.Transparent, Color.Black);
            ChartHelper.SetXY(chart1, "", "粒径(*50um)", StringAlignment.Far, Color.Black, Color.Black, AxisArrowStyle.SharpTriangle, 0, 0);
            ChartHelper.SetMajorGrid(chart1, Color.Transparent, 20, 50);
            List <int> xData = new List <int>()
            {
            };
            int i, j;

            for (i = 1; i <= (int)SandNumber; i++)
            {
                xData.Add(i);
            }
            List <double> yData = new List <double>()
            {
            };

            for (j = 0; j <= (int)SandNumber - 1; j++)
            {
                yData.Add(DA[j, 0]);
            }
            chart1.Series[0].Points.DataBindXY(xData, yData);

            chart2.Series.Clear();
            ChartHelper.AddSeries(chart2, "该粒径范围内沙尘个数", SeriesChartType.Column, Color.Lime, Color.Blue, true);
            //      ChartHelper.AddSeries(chart2, "曲线图", SeriesChartType.Spline, Color.Red, Color.Red);
            //      ChartHelper.SetTitle(chart2, "柱状图与曲线图", new Font("微软雅黑", 12), Docking.Bottom, Color.Black);
            ChartHelper.SetStyle(chart2, Color.Transparent, Color.Black);
            ChartHelper.SetLegend(chart2, Docking.Top, StringAlignment.Center, Color.Transparent, Color.Black);
            ChartHelper.SetXY(chart2, "粒径(*50um)", "个数", StringAlignment.Far, Color.Black, Color.Black, AxisArrowStyle.SharpTriangle, 4, (int)(DN[0, 0] / 10));
            ChartHelper.SetMajorGrid(chart2, Color.Transparent, 20, 2);
            List <int> xData2 = new List <int>()
            {
            };
            int i2, j2;

            for (i2 = 1; i2 <= (int)xlength; i2++)
            {
                xData2.Add(i2);
            }
            List <double> yData2 = new List <double>()
            {
            };

            for (j2 = 0; j2 <= (int)xlength - 1; j2++)
            {
                yData2.Add(DN[j2, 0]);
            }
            chart2.Series[0].Points.DataBindXY(xData2, yData2);

            chart3.Series.Clear();
            ChartHelper.AddSeries(chart3, "饼状图", SeriesChartType.Pie, Color.Lime, Color.Black, true);
            ChartHelper.SetStyle(chart3, Color.Transparent, Color.Black);
            ChartHelper.SetLegend(chart3, Docking.Bottom, StringAlignment.Center, Color.Transparent, Color.Black);
            List <double> y1 = new List <double>()
            {
            };
            int j3;

            for (j3 = 0; j3 <= 2; j3++)
            {
                y1.Add(TN[j3, 0]);
            }
            string        t1    = String.Format("石砾(>1000㎛):         {0}个", TN[0, 0]);
            string        t2    = String.Format("粗沙粒(250-1000㎛):    {0}个", TN[1, 0]);
            string        t3    = String.Format("细沙粒(50-250㎛):      {0}个", TN[2, 0]);
            List <string> nameX = new List <string>()
            {
                t1, t2, t3
            };

            chart3.Series[0].Points.DataBindXY(nameX, y1);
            chart3.Series[0]["PieLabelStyle"] = "Outside"; //将文字移到外侧
            chart3.Series[0]["PieLineColor"]  = "Black";   //绘制黑色的连线。
            chart3.Series[0].Label            = "#PERCENT{P2}";

            sw.Stop();
            TimeSpan ts = sw.Elapsed;

            Console.WriteLine("DateTime costed for this function is: {0}ms", ts.TotalMilliseconds);
        }
示例#12
0
        private void HydrateChartSeriesList(DataTable originalChartData, EpmChartAggregateType aggregateType, SPField xAxisField, SPField yAxisField, SPField zAxisField, bool hasZAxis, bool hasZAxisColor, BubbleChartAxisToColumnMapping columnMappings)
        {
            var colorsAlreadyInLegend = new List <Color>();

            var chartData = originalChartData.Copy();

            RemoveUnusedChartDataColumns(chartData);

            var xAxisColumn = chartData.Columns[columnMappings.XaxisColumnIndex];
            var yAxisColumn = chartData.Columns[columnMappings.YaxisColumnIndex];
            var titleColumn = chartData.Columns[chartData.Columns.Count - 1];

            var zAxisColumn = new DataColumn();

            if (hasZAxis)
            {
                zAxisColumn = chartData.Columns[columnMappings.ZaxisColumnIndex];
            }

            var zAxisColorColumn = chartData.Columns[columnMappings.ZaxisColorColumnIndex];

            var zAxisColorMap = GetZAxisColorMap(chartData, zAxisColorColumn);


            //TODO: Update this to not hardcode the series.
            const string hardcodingBubblechartForNow = "BubbleChart";
            var          chartDataSeries             = new EpmChartDataSeries(hardcodingBubblechartForNow);

            foreach (DataRow row in chartData.Rows)
            {
                var zAxisColorFieldValue = "";
                if (hasZAxisColor)
                {
                    zAxisColorFieldValue = row[zAxisColorColumn].ToString();
                }

                var chartDataPoint = new EpmChartDataPoint(aggregateType);
                chartDataPoint.Title          = row[titleColumn].ToString();
                chartDataPoint.XAxisLabel     = ParseValue(xAxisColumn.ColumnName);
                chartDataPoint.XAxisValue     = ChartHelper.ParseDouble(ParseValue(row[xAxisColumn].ToString()), _englishNumberFormat, aggregateType, FieldIsPercentage(xAxisField));
                chartDataPoint.XAxisFieldName = xAxisField.InternalName;
                chartDataPoint.YAxisFieldName = yAxisField.InternalName;
                chartDataPoint.ZAxisFieldName = zAxisField.InternalName;
                chartDataPoint.LegendText     = zAxisColorFieldValue == "" ? "No Value" : zAxisColorFieldValue;
                chartDataPoint.ZAxisValue     = ChartHelper.ParseDouble(ParseValue(row[zAxisColumn].ToString()), _englishNumberFormat, aggregateType, FieldIsPercentage(zAxisField));
                chartDataPoint.AddYAxisValue(ChartHelper.ParseDouble(ParseValue(row[yAxisColumn].ToString()), _englishNumberFormat, aggregateType, FieldIsPercentage(yAxisField)));

                //Only show one of each color in the legend.
                if (hasZAxisColor)
                {
                    if (zAxisColorMap.ContainsKey(zAxisColorFieldValue))
                    {
                        chartDataPoint.DataPointColor = zAxisColorMap[zAxisColorFieldValue];

                        if (!colorsAlreadyInLegend.Contains(chartDataPoint.DataPointColor))
                        {
                            chartDataPoint.ShowInLegend = true;
                            colorsAlreadyInLegend.Add(chartDataPoint.DataPointColor);
                        }
                        else
                        {
                            chartDataPoint.ShowInLegend = false;
                        }
                    }
                }
                else
                {
                    chartDataPoint.DataPointColor = HtmlColorService.GetRandomHtmlColor();
                }

                chartDataSeries.AddDataPoint(chartDataPoint);
            }

            //NOTE: This is to set the zindex of the bubbles, but visifire doesnt support it on datapoints, only dataseries. So, we just need to order by ZAxis descending so smaller bubbles land on top.
            chartDataSeries.OrderDataPointsSoSmallerBubblesAreInFront();
            Add(chartDataSeries);
        }
示例#13
0
        public QX.Controllers.Base.FileResult GetChart(string id)
        {
            //Chart chart2 = new Chart();
            //chart2.Width = 412;
            //chart2.Height = 296;
            //chart2.RenderType = RenderType.ImageTag;
            //chart2.Palette = ChartColorPalette.BrightPastel;
            //Title T = new Title("测试图片");

            //chart2.Legends.Add("Legend1");
            //chart2.BackColor = System.Drawing.Color.AliceBlue;
            //chart2.BackGradientStyle = GradientStyle.TopBottom;


            //// Set Border Width
            //chart2.BorderWidth = 2;

            //// Chart Image Mode
            //chart2.BackImageWrapMode = ChartImageWrapMode.TileFlipX;


            //ChartArea cArea1 = new ChartArea("Area1");
            ////設定Area1的X,Y軸標題
            //cArea1.AxisX.Title = "時刻";
            //cArea1.AxisY.Title = "數量";
            ////X,Y軸刻度區間
            //cArea1.AxisX.Interval = 2;
            //cArea1.AxisY.Interval = 10;


            //#region Series1填入資料
            //List<string> lstX1 = new List<string>();
            //List<string> lstY1 = new List<string>();
            //Random r1 = new Random((int)DateTime.Now.Ticks);
            //for (int i = 1; i < 50; i++)
            //{
            //    lstX1.Add(i.ToString());
            //}
            //for (int i = 1; i < 50; i++)
            //{
            //    int x = r1.Next(0, 100);
            //    lstY1.Add(x.ToString());
            //}

            //#endregion


            //Series series1 = new Series("種類A");
            ////設定要顯示在哪一個ChartArea
            //series1.ChartArea = "Area1";
            ////設定圖表種類
            //series1.ChartType = SeriesChartType.Spline;
            ////是否將值show在value label上
            //series1.IsValueShownAsLabel = true;
            ////填入資料
            //series1.Points.DataBindXY(lstX1, lstY1);


            //chart2.ChartAreas.Add(cArea1);
            //chart2.Series.Add(series1);

            Chart chart2;

            var helper = ChartHelper.GetInstance();

            chart2 = helper.GenChart(id);

            Dictionary <string, object> paraVal = new Dictionary <string, object>();

            foreach (var r in Request.QueryString.AllKeys)
            {
                paraVal.Add(r, Request[r]);
            }

            if (chart2 != null)
            {
                helper.SetSerial(id, chart2, paraVal);
            }

            MemoryStream imageStream = new MemoryStream();

            chart2.SaveImage(imageStream, ChartImageFormat.Png);

            return(new QX.Controllers.Base.FileResult("Yo.png", "image/png", imageStream.ToArray()));
        }
		/// <summary>
		/// Paint FastPoint Chart.
		/// </summary>
		/// <param name="graph">The Chart Graphics object.</param>
		/// <param name="common">The Common elements object.</param>
		/// <param name="area">Chart area for this chart.</param>
		/// <param name="seriesToDraw">Chart series to draw.</param>
		virtual public void Paint( 
			ChartGraphics graph, 
			CommonElements common, 
			ChartArea area, 
			Series seriesToDraw )
		{	
			this.Common = common;
			this.Graph = graph;
			if(area.Area3DStyle.Enable3D)
			{
				// Initialize variables
				this.chartArea3DEnabled = true;
				matrix3D = area.matrix3D;
			}
			else
			{
				this.chartArea3DEnabled = false;
			}
			
			//************************************************************
			//** Loop through all series
			//************************************************************
			foreach( Series series in common.DataManager.Series )
			{
				// Process non empty series of the area with FastPoint chart type
				if( String.Compare( series.ChartTypeName, this.Name, true, System.Globalization.CultureInfo.CurrentCulture ) != 0 
					|| series.ChartArea != area.Name || 
					!series.IsVisible())
				{
					continue;
				}

				// Get 3D series depth and Z position
				if(this.chartArea3DEnabled)
				{
					float seriesDepth;
					area.GetSeriesZPositionAndDepth(series, out seriesDepth, out this.seriesZCoordinate);
					this.seriesZCoordinate += seriesDepth/2.0f;
				}

				// Set active horizontal/vertical axis
				Axis hAxis = area.GetAxis(AxisName.X, series.XAxisType, (area.Area3DStyle.Enable3D) ? string.Empty : series.XSubAxisName);
				Axis vAxis = area.GetAxis(AxisName.Y, series.YAxisType, (area.Area3DStyle.Enable3D) ? string.Empty : series.YSubAxisName);
				double hAxisMin = hAxis.ViewMinimum;
				double hAxisMax = hAxis.ViewMaximum;
				double vAxisMin = vAxis.ViewMinimum;
				double vAxisMax = vAxis.ViewMaximum;

				// Get "PermittedPixelError" attribute.
				// By default use 1/3 of the marker size.
				float	permittedPixelError = series.MarkerSize / 3f;
                if (series.IsCustomPropertySet(CustomPropertyName.PermittedPixelError))
				{
                    string attrValue = series[CustomPropertyName.PermittedPixelError];

                    float pixelError;
                    bool parseSucceed = float.TryParse(attrValue, NumberStyles.Any, CultureInfo.CurrentCulture, out pixelError);

                    if (parseSucceed)
                    {
                        permittedPixelError = pixelError;
                    }
                    else
                    {
                        throw (new InvalidOperationException(SR.ExceptionCustomAttributeValueInvalid2("PermittedPixelError")));
                    }

                    // "PermittedPixelError" attribute value should be in range from zero to 1
                    if (permittedPixelError < 0f || permittedPixelError > 1f)
                    {
                        throw (new InvalidOperationException(SR.ExceptionCustomAttributeIsNotInRange0to1("PermittedPixelError")));
                    }
				}

				// Get pixel size in axes coordinates
				SizeF pixelSize = graph.GetRelativeSize(new SizeF(permittedPixelError, permittedPixelError));
				SizeF axesMin = graph.GetRelativeSize(new SizeF((float)hAxisMin, (float)vAxisMin));
				double axesValuesPixelSizeX = Math.Abs(hAxis.PositionToValue(axesMin.Width + pixelSize.Width, false) - hAxis.PositionToValue(axesMin.Width, false));
				double axesValuesPixelSizeY = Math.Abs(vAxis.PositionToValue(axesMin.Height + pixelSize.Height, false) - vAxis.PositionToValue(axesMin.Height, false));

				// Create point marker brush
				SolidBrush	markerBrush = new SolidBrush( ((series.MarkerColor.IsEmpty) ? series.Color : series.MarkerColor) );
				SolidBrush	emptyMarkerBrush = new SolidBrush( ((series.EmptyPointStyle.MarkerColor.IsEmpty) ? series.EmptyPointStyle.Color : series.EmptyPointStyle.MarkerColor) );

				// Create point marker border pen
				Pen	borderPen = null;
				Pen	emptyBorderPen = null;
				if(!series.MarkerBorderColor.IsEmpty && series.MarkerBorderWidth > 0)
				{
					borderPen = new Pen(series.MarkerBorderColor, series.MarkerBorderWidth);
				}
				if(!series.EmptyPointStyle.MarkerBorderColor.IsEmpty && series.EmptyPointStyle.MarkerBorderWidth > 0)
				{
					emptyBorderPen = new Pen(series.EmptyPointStyle.MarkerBorderColor, series.EmptyPointStyle.MarkerBorderWidth);
				}

				// Check if series is indexed
				bool indexedSeries = ChartHelper.IndexedSeries(this.Common, series.Name );

                // Get marker size taking in consideration current DPIs
                int markerSize = series.MarkerSize;
                if (graph != null && graph.Graphics != null)
                {
                    // Marker size is in pixels and we do the mapping for higher DPIs
                    markerSize = (int)Math.Max(markerSize * graph.Graphics.DpiX / 96, markerSize * graph.Graphics.DpiY / 96);
                }

				// Loop through all ponts in the series
				int		index = 0;
				double	xValue = 0.0;
				double	yValue = 0.0;
				double	xValuePrev = 0.0;
				double	yValuePrev = 0.0;
				PointF	currentPoint = PointF.Empty;
				bool	currentPointIsEmpty = false;
				double	xPixelConverter = (graph.Common.ChartPicture.Width - 1.0) / 100.0;
				double	yPixelConverter = (graph.Common.ChartPicture.Height - 1.0) / 100.0;
				MarkerStyle	markerStyle = series.MarkerStyle;
				MarkerStyle	emptyMarkerStyle = series.EmptyPointStyle.MarkerStyle;
				foreach( DataPoint point in series.Points )
				{
					// Get point X and Y values
					xValue = (indexedSeries) ? index + 1 : point.XValue;
					xValue = hAxis.GetLogValue(xValue);
					yValue = vAxis.GetLogValue(point.YValues[0]);
					currentPointIsEmpty = point.IsEmpty;

					// Check if point is completly out of the data scaleView
					if( xValue < hAxisMin ||
						xValue > hAxisMax ||
						yValue < vAxisMin ||
						yValue > vAxisMax )
					{
						xValuePrev = xValue;
						yValuePrev = yValue;
						++index;
						continue;
					}

					// Check if point may be skipped
					if(index > 0)
					{
						// Check if current point location is in the specified distance from the 
						// preious data location.
						if(Math.Abs(xValue - xValuePrev) < axesValuesPixelSizeX &&
							Math.Abs(yValue - yValuePrev) < axesValuesPixelSizeY)
						{
							// Increase counter and proceed to the next data point
							++index;
							continue;
						}
					}

					// Get point pixel position
					currentPoint.X = (float)
						(hAxis.GetLinearPosition( xValue ) * xPixelConverter);
					currentPoint.Y = (float)
						(vAxis.GetLinearPosition( yValue ) * yPixelConverter);

					// Draw point marker
                    MarkerStyle	currentMarkerStyle = (currentPointIsEmpty) ? emptyMarkerStyle : markerStyle;
                    if(currentMarkerStyle != MarkerStyle.None)
                    {
					    this.DrawMarker(
						    graph,
						    point,
						    index,
						    currentPoint,
                            currentMarkerStyle,
						    markerSize,
						    (currentPointIsEmpty) ? emptyMarkerBrush : markerBrush,
						    (currentPointIsEmpty) ? emptyBorderPen : borderPen);
                    }

					// Remember last point coordinates
					xValuePrev = xValue;
					yValuePrev = yValue;
					++index;
				}

				// Dispose used brushes and pens
				markerBrush.Dispose();
				emptyMarkerBrush.Dispose();
				if(borderPen != null)
				{
					borderPen.Dispose();
				}
				if(emptyBorderPen != null)
				{
					emptyBorderPen.Dispose();
				}
			}
		}
示例#15
0
 /// <summary>
 /// 突跳处理→活动平均法
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void 活动平均法ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     this.label1.Text = "突跳处理→活动平均法";
     ChangeChart(ChartHelper.GetFlexAvgMethodChart());
 }
示例#16
0
        public void Render(IHasData data)
        {
            if (data is IHasKLineData kline)
            {
                var kLineData = kline.GetData();

                if ((kLineData.DataSources != null && kLineData.DataSources.Any()) && AllowRender)
                {
                    var ohlcs   = kLineData.DataSources;
                    var visuals = new List <Visual>();
                    for (int i = 0; i <= kLineData.VisualRangeEndIndex - kLineData.VisualRangeStartIndex; i++)
                    {
                        var ohlc   = ohlcs[i + kLineData.VisualRangeStartIndex];
                        var visual = new DrawingVisual();
                        using (var context = visual.RenderOpen())
                        {
                            var openCloseMaxPoint = new Point
                            {
                                X = i * (kLineData.DataWidth + kLineData.DataMargin * 2) + kLineData.Margin.Left + kLineData.DataMargin,
                                Y = ChartHelper.ComputeYCoordinate(kLineData.ActualHeight, kLineData.YAxisCoordinateMinValue, kLineData.YAxisCoordinateAndPixelProportion, kLineData.Margin.Top, Convert.ToDouble(Math.Max(ohlc.Open, ohlc.Close)))
                            };
                            var openCloseMinPoint = new Point
                            {
                                X = i * (kLineData.DataWidth + kLineData.DataMargin * 2) + kLineData.Margin.Left + kLineData.DataMargin + kLineData.DataWidth,
                                Y = ChartHelper.ComputeYCoordinate(kLineData.ActualHeight, kLineData.YAxisCoordinateMinValue, kLineData.YAxisCoordinateAndPixelProportion, kLineData.Margin.Top, Convert.ToDouble(Math.Min(ohlc.Open, ohlc.Close)))
                            };
                            var midLineHeightPoint = new Point
                            {
                                X = openCloseMaxPoint.X + kLineData.DataWidth / 2,
                                Y = ChartHelper.ComputeYCoordinate(kLineData.ActualHeight, kLineData.YAxisCoordinateMinValue, kLineData.YAxisCoordinateAndPixelProportion, kLineData.Margin.Top, Convert.ToDouble(ohlc.Height))
                            };
                            var midLineLowPoint = new Point
                            {
                                X = openCloseMaxPoint.X + kLineData.DataWidth / 2,
                                Y = ChartHelper.ComputeYCoordinate(kLineData.ActualHeight, kLineData.YAxisCoordinateMinValue, kLineData.YAxisCoordinateAndPixelProportion, kLineData.Margin.Top, Convert.ToDouble(ohlc.Low))
                            };

                            //设置最小蜡烛宽度
                            if ((openCloseMinPoint.Y - openCloseMaxPoint.Y) < 3)
                            {
                                openCloseMinPoint.Y = openCloseMaxPoint.Y + 3;
                            }

                            var brush = ohlc.Open < ohlc.Close ? kLineData.RiseBrush : kLineData.FallBrush;
                            context.DrawRectangle(brush, null, new Rect(openCloseMaxPoint, openCloseMinPoint));
                            context.DrawLine(new Pen {
                                Brush = brush, Thickness = kLineData.DataWidth / 8
                            }, midLineHeightPoint, midLineLowPoint);

                            visuals.Add(visual);
                            kLineData.Mapping.Add(visual, new Model.KlineMappingData {
                                OHLC = ohlc, MidLineHeightPoint = midLineHeightPoint, MidLineLowPoint = midLineLowPoint
                            });
                        }
                    }
                    kLineData.UpdateVisuals(nameof(KLineRenderer), visuals);
                }
                else
                {
                    kLineData.UpdateVisual(nameof(KLineRenderer), null);
                }
            }
        }
示例#17
0
 /// <summary>
 /// 突跳处理→拟合→线性拟合法
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void 线性拟合ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     this.label1.Text = "突跳处理→拟合法→线性拟合";
     this.toolTip1.SetToolTip(this.label1, "");
     ChangeChart(ChartHelper.GetLinearRegressionChart());
 }
示例#18
0
        private async Task PollValuesAsync()
        {
            await Task.Delay(500);

            List <Consume> cosumes = cosumeService.GetConsumes();
            var            entries = cosumes.Select(x => new Microcharts.Entry((float)x.Amount)
            {
                Label = ChartHelper.ToWord(x.DataType), ValueLabel = x.Amount.ToString(), Color = ChartHelper.GetRandomColor()
            });

            var _chart = new LineChart();

            _chart.Entries = entries;

            // customized
            _chart.LabelTextSize = 40;
            _chart.LineMode      = LineMode.Straight;
            _chart.LineSize      = 8;
            _chart.PointMode     = PointMode.Square;
            _chart.PointSize     = 18;


            this.Chart = _chart;



            OnPropertyChanged(nameof(Chart));
        }
示例#19
0
 /// <summary>
 /// 突跳处理→拟合→指数e拟合
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void 指数e拟合ToolStripMenuItem2_Click(object sender, EventArgs e)
 {
     this.label1.Text = "突跳处理→拟合→指数e拟合";
     ChangeChart(ChartHelper.GetExpRegressionChart());
 }
示例#20
0
文件: TvSerie.cs 项目: Grigann/PopWeb
        /// <summary>
        /// Initializes the chart information
        /// </summary>
        public virtual void InitializeChartInfos()
        {
            var chartHelper = new ChartHelper<TvWatchingSession>();

            var watchingSessions = this.Seasons.SelectMany(x => x.Episodes).SelectMany(x => x.WatchingSessions).ToList();
            this.ChartIntervalType = chartHelper.ComputeIntervalType(watchingSessions);

            var chartSessions = chartHelper.ExtractChartSessions(watchingSessions, this.ChartIntervalType);

            this.FirstChartDate = chartSessions.Count == 0 ? DateTime.Today : chartSessions.Keys.Min();
            this.WatchingSessionForCharts = chartHelper.ComputeSessionsChart(chartSessions);
            this.WatchingSessionXAxisTicks = chartHelper.ComputeXAxisTicks(chartSessions);
            this.WatchingSessionYAxisTicks = chartHelper.ComputeYAxisTicks(chartSessions);
        }
示例#21
0
 /// <summary>
 ///  突跳处理→数学模型法
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void 数学模型法ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     this.label1.Text = "突跳处理→数学模型法";
     ChangeChart(ChartHelper.GetMathModelChart());
 }
 private void ProcessTypePieChart()
 {
     lblProcessTypePerYear.Text = "SELECTION PROCESS (" + DateTime.Now.Year + ")";
     DataTable dt = new DataTable();
     string qry = "EXEC GetProcessTypePieChart";
     dt = am.DataAccess.RecordSet(qry, new string[] { });
     ChartHelper ch = new ChartHelper("ProcessType1", 300, 200, Telerik.Web.UI.HtmlChart.ChartLegendPosition.Right);
     ch.CreateChart(HtmlChartHolderPie, ChartHelper.ChartType.PieChart, dt, null);
 }
示例#23
0
 private void 平均值法插值ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     label1.Text = "缺数处理→平均法插值";
     ChangeChart(ChartHelper.GetAvgMethodChart_LoseValue_Process());
 }
示例#24
0
 public FrmPopoutPlot(ISelectionHolder selectionHolder, Core core, ChartHelper chart)
     : this()
 {
     this._chart = new ChartHelper(selectionHolder, core, this, true);
     this._chart.Chart.SetPlot(chart.Chart.CurrentPlot); // TODO: Not sure about using same plot on two graphs!
 }
示例#25
0
 private void 多项式法插值ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     label1.Text = "缺数处理→多项式法插值";
     ChangeChart(ChartHelper.GetPolyInterpolationChart());
 }
示例#26
0
文件: Game.cs 项目: Grigann/PopWeb
        /// <summary>
        /// Initializes the chart information
        /// </summary>
        public virtual void InitializeChartInfos()
        {
            var chartHelper = new ChartHelper<GamingSession>();

            this.ChartIntervalType = chartHelper.ComputeIntervalType(this.GamingSessions);

            var chartSessions = chartHelper.ExtractChartSessions(this.GamingSessions, this.ChartIntervalType);

            this.FirstChartDate = chartSessions.Count == 0 ? DateTime.Today : chartSessions.Keys.Min();
            this.GamingSessionForCharts = chartHelper.ComputeSessionsChart(chartSessions);
            this.GamingSessionXAxisTicks = chartHelper.ComputeXAxisTicks(chartSessions);
            this.GamingSessionYAxisTicks = chartHelper.ComputeYAxisTicks(chartSessions);
        }
示例#27
0
 private void 等间距插值ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     label1.Text = "缺数处理→等间距插值";
     ChangeChart(ChartHelper.GetEqualDistInterpolationChart());
 }
示例#28
0
        private async Task PollValuesAsync()
        {
            await Task.Delay(500);


            List <Consume> cosumes = cosumeService.GetConsumes();
            var            entries = cosumes.Select(x => new Microcharts.Entry((float)x.Amount)
            {
                Label = ChartHelper.ToWord(x.DataType), ValueLabel = x.Amount.ToString(), Color = ChartHelper.GetRandomColor()
            });

            var _chart = new RadarChart();

            _chart.Entries       = entries;
            _chart.LabelTextSize = 40;
            this.Chart           = _chart;
            OnPropertyChanged(nameof(Chart));
        }
示例#29
0
 private void 图解法ToolStripMenuItem1_Click(object sender, EventArgs e)
 {
     this.label1.Text = "台阶处理→图解法";
     ChangeChart(ChartHelper.GetStepMovingChart());
 }
 /// <summary>
 /// Translates a point from the chart dimension to the default drawing canvas pixel dimension.
 /// The default canvas is the text canvas.
 /// </summary>
 /// <param name="valuePoint"></param>
 /// <returns></returns>
 public Point ToPixel(Point valuePoint)
 {
     return(ChartHelper.ToPixel(TextCanvasInfo, valuePoint));
 }
示例#31
0
 private void 多点平均平移法ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     this.label1.Text = "多点平均平移法";
     ChangeChart(ChartHelper.GetMultiPointAvgSlideChart());
 }
示例#32
0
        /// <summary>
        /// Paint FastLine Chart.
        /// </summary>
        /// <param name="graph">The Chart Graphics object.</param>
        /// <param name="common">The Common elements object.</param>
        /// <param name="area">Chart area for this chart.</param>
        /// <param name="seriesToDraw">Chart series to draw.</param>
        virtual public void Paint(
            ChartGraphics graph,
            CommonElements common,
            ChartArea area,
            Series seriesToDraw)
        {
            this.Common = common;
            this.Graph  = graph;
            bool clipRegionSet = false;

            if (area.Area3DStyle.Enable3D)
            {
                // Initialize variables
                this.chartArea3DEnabled = true;
                matrix3D = area.matrix3D;
            }
            else
            {
                this.chartArea3DEnabled = false;
            }

            //************************************************************
            //** Loop through all series
            //************************************************************
            foreach (Series series in common.DataManager.Series)
            {
                // Process non empty series of the area with FastLine chart type
                if (String.Compare(series.ChartTypeName, this.Name, true, System.Globalization.CultureInfo.CurrentCulture) != 0 ||
                    series.ChartArea != area.Name ||
                    !series.IsVisible())
                {
                    continue;
                }

                // Get 3D series depth and Z position
                if (this.chartArea3DEnabled)
                {
                    float seriesDepth;
                    area.GetSeriesZPositionAndDepth(series, out seriesDepth, out seriesZCoordinate);
                    this.seriesZCoordinate += seriesDepth / 2.0f;
                }

                // Set active horizontal/vertical axis
                Axis   hAxis    = area.GetAxis(AxisName.X, series.XAxisType, (area.Area3DStyle.Enable3D) ? string.Empty : series.XSubAxisName);
                Axis   vAxis    = area.GetAxis(AxisName.Y, series.YAxisType, (area.Area3DStyle.Enable3D) ? string.Empty : series.YSubAxisName);
                double hAxisMin = hAxis.ViewMinimum;
                double hAxisMax = hAxis.ViewMaximum;
                double vAxisMin = vAxis.ViewMinimum;
                double vAxisMax = vAxis.ViewMaximum;

                // Get "PermittedPixelError" attribute
                float permittedPixelError = 1.0f;
                if (series.IsCustomPropertySet(CustomPropertyName.PermittedPixelError))
                {
                    string attrValue = series[CustomPropertyName.PermittedPixelError];

                    float pixelError;
                    bool  parseSucceed = float.TryParse(attrValue, NumberStyles.Any, CultureInfo.CurrentCulture, out pixelError);

                    if (parseSucceed)
                    {
                        permittedPixelError = pixelError;
                    }
                    else
                    {
                        throw (new InvalidOperationException(SR.ExceptionCustomAttributeValueInvalid2("PermittedPixelError")));
                    }

                    // "PermittedPixelError" attribute value should be in range from zero to 1
                    if (permittedPixelError < 0f || permittedPixelError > 1f)
                    {
                        throw (new InvalidOperationException(SR.ExceptionCustomAttributeIsNotInRange0to1("PermittedPixelError")));
                    }
                }

                // Get pixel size in axes coordinates
                SizeF  pixelSize            = graph.GetRelativeSize(new SizeF(permittedPixelError, permittedPixelError));
                SizeF  axesMin              = graph.GetRelativeSize(new SizeF((float)hAxisMin, (float)vAxisMin));
                double axesValuesPixelSizeX = Math.Abs(hAxis.PositionToValue(axesMin.Width + pixelSize.Width, false) - hAxis.PositionToValue(axesMin.Width, false));

                // Create line pen
                Pen linePen = new Pen(series.Color, series.BorderWidth);
                linePen.DashStyle = graph.GetPenStyle(series.BorderDashStyle);
                linePen.StartCap  = LineCap.Round;
                linePen.EndCap    = LineCap.Round;

                // Create empty line pen
                Pen emptyLinePen = new Pen(series.EmptyPointStyle.Color, series.EmptyPointStyle.BorderWidth);
                emptyLinePen.DashStyle = graph.GetPenStyle(series.EmptyPointStyle.BorderDashStyle);
                emptyLinePen.StartCap  = LineCap.Round;
                emptyLinePen.EndCap    = LineCap.Round;

                // Check if series is indexed
                bool indexedSeries = ChartHelper.IndexedSeries(this.Common, series.Name);

                // Loop through all ponts in the series
                int       index                      = 0;
                double    yValueRangeMin             = double.NaN;
                double    yValueRangeMax             = double.NaN;
                DataPoint pointRangeMin              = null;
                DataPoint pointRangeMax              = null;
                double    xValue                     = 0;
                double    yValue                     = 0;
                double    xValuePrev                 = 0;
                double    yValuePrev                 = 0;
                DataPoint prevDataPoint              = null;
                PointF    lastVerticalSegmentPoint   = PointF.Empty;
                PointF    prevPoint                  = PointF.Empty;
                PointF    currentPoint               = PointF.Empty;
                bool      prevPointInAxesCoordinates = false;
                bool      verticalLineDetected       = false;
                bool      prevPointIsEmpty           = false;
                bool      currentPointIsEmpty        = false;
                bool      firstNonEmptyPoint         = false;
                double    xPixelConverter            = (graph.Common.ChartPicture.Width - 1.0) / 100.0;
                double    yPixelConverter            = (graph.Common.ChartPicture.Height - 1.0) / 100.0;
                foreach (DataPoint point in series.Points)
                {
                    // Get point X and Y values
                    xValue = (indexedSeries) ? index + 1 : point.XValue;
                    xValue = hAxis.GetLogValue(xValue);
                    yValue = vAxis.GetLogValue(point.YValues[0]);
                    currentPointIsEmpty = point.IsEmpty;

                    // NOTE: Fixes issue #7094
                    // If current point is non-empty but the previous one was,
                    // use empty point style properties to draw it.
                    if (prevPointIsEmpty && !currentPointIsEmpty && !firstNonEmptyPoint)
                    {
                        firstNonEmptyPoint  = true;
                        currentPointIsEmpty = true;
                    }
                    else
                    {
                        firstNonEmptyPoint = false;
                    }

                    // Check if line is completly out of the data scaleView
                    if (!verticalLineDetected &&
                        ((xValue < hAxisMin && xValuePrev < hAxisMin) ||
                         (xValue > hAxisMax && xValuePrev > hAxisMax) ||
                         (yValue < vAxisMin && yValuePrev < vAxisMin) ||
                         (yValue > vAxisMax && yValuePrev > vAxisMax)))
                    {
                        xValuePrev = xValue;
                        yValuePrev = yValue;
                        prevPointInAxesCoordinates = true;
                        ++index;
                        continue;
                    }
                    else if (!clipRegionSet)
                    {
                        // Check if line is partialy in the data scaleView
                        if (xValuePrev < hAxisMin || xValuePrev > hAxisMax ||
                            xValue > hAxisMax || xValue < hAxisMin ||
                            yValuePrev < vAxisMin || yValuePrev > vAxisMax ||
                            yValue < vAxisMin || yValue > vAxisMax)
                        {
                            // Set clipping region for line drawing
                            graph.SetClip(area.PlotAreaPosition.ToRectangleF());
                            clipRegionSet = true;
                        }
                    }

                    // Check if point may be skipped
                    if (index > 0 &&
                        currentPointIsEmpty == prevPointIsEmpty)
                    {
                        // Check if points X value in acceptable error boundary
                        if (Math.Abs(xValue - xValuePrev) < axesValuesPixelSizeX)
                        {
                            if (!verticalLineDetected)
                            {
                                verticalLineDetected = true;
                                if (yValue > yValuePrev)
                                {
                                    yValueRangeMax = yValue;
                                    yValueRangeMin = yValuePrev;
                                    pointRangeMax  = point;
                                    pointRangeMin  = prevDataPoint;
                                }
                                else
                                {
                                    yValueRangeMax = yValuePrev;
                                    yValueRangeMin = yValue;
                                    pointRangeMax  = prevDataPoint;
                                    pointRangeMin  = point;
                                }

                                // NOTE: Prev. version code - A.G.
//								yValueRangeMin = Math.Min(yValue, yValuePrev);
//								yValueRangeMax = Math.Max(yValue, yValuePrev);
                            }
                            else
                            {
                                if (yValue > yValueRangeMax)
                                {
                                    yValueRangeMax = yValue;
                                    pointRangeMax  = point;
                                }

                                else if (yValue < yValueRangeMin)
                                {
                                    yValueRangeMin = yValue;
                                    pointRangeMin  = point;
                                }

                                // NOTE: Prev. version code - A.G.
//								yValueRangeMin = Math.Min(yValue, yValueRangeMin);
//								yValueRangeMax = Math.Max(yValue, yValueRangeMax);
                            }

                            // Remember last point
                            prevDataPoint = point;

                            // Remember last vertical range point
                            // Note! Point is in axes coordinate.
                            lastVerticalSegmentPoint.Y = (float)yValue;

                            // Increase counter and proceed to next data point
                            ++index;
                            continue;
                        }
                    }

                    // Get point pixel position
                    currentPoint.X = (float)
                                     (hAxis.GetLinearPosition(xValue) * xPixelConverter);
                    currentPoint.Y = (float)
                                     (vAxis.GetLinearPosition(yValue) * yPixelConverter);

                    // Check if previous point must be converted from axes values to pixels
                    if (prevPointInAxesCoordinates)
                    {
                        prevPoint.X = (float)
                                      (hAxis.GetLinearPosition(xValuePrev) * xPixelConverter);
                        prevPoint.Y = (float)
                                      (vAxis.GetLinearPosition(yValuePrev) * yPixelConverter);
                    }

                    // Draw accumulated vertical line (with minimal X values differences)
                    if (verticalLineDetected)
                    {
                        // Convert Y coordinates to pixels
                        yValueRangeMin = (vAxis.GetLinearPosition(yValueRangeMin) * yPixelConverter);
                        yValueRangeMax = (vAxis.GetLinearPosition(yValueRangeMax) * yPixelConverter);

                        // Draw accumulated vertical line
                        DrawLine(
                            series,
                            prevDataPoint,
                            pointRangeMin,
                            pointRangeMax,
                            index,
                            (prevPointIsEmpty) ? emptyLinePen : linePen,
                            prevPoint.X,
                            (float)yValueRangeMin,
                            prevPoint.X,
                            (float)yValueRangeMax);

                        // Reset vertical line detected flag
                        verticalLineDetected = false;

                        // Convert last point of the vertical line segment to pixel coordinates
                        prevPoint.Y = (float)
                                      (vAxis.GetLinearPosition(lastVerticalSegmentPoint.Y) * yPixelConverter);
                    }

                    // Draw line from previous to current point
                    if (index > 0)
                    {
                        DrawLine(
                            series,
                            point,
                            pointRangeMin,
                            pointRangeMax,
                            index,
                            (currentPointIsEmpty) ? emptyLinePen : linePen,
                            prevPoint.X,
                            prevPoint.Y,
                            currentPoint.X,
                            currentPoint.Y);
                    }

                    // Remember last point coordinates
                    xValuePrev    = xValue;
                    yValuePrev    = yValue;
                    prevDataPoint = point;
                    prevPoint     = currentPoint;
                    prevPointInAxesCoordinates = false;
                    prevPointIsEmpty           = currentPointIsEmpty;
                    ++index;
                }

                // Draw last accumulated line segment
                if (verticalLineDetected)
                {
                    // Check if previous point must be converted from axes values to pixels
                    if (prevPointInAxesCoordinates)
                    {
                        prevPoint.X = (float)
                                      (hAxis.GetLinearPosition(xValuePrev) * xPixelConverter);
                        prevPoint.Y = (float)
                                      (vAxis.GetLinearPosition(yValuePrev) * yPixelConverter);
                    }

                    // Convert Y coordinates to pixels
                    yValueRangeMin = (vAxis.GetLinearPosition(yValueRangeMin) * yPixelConverter);
                    yValueRangeMax = (vAxis.GetLinearPosition(yValueRangeMax) * yPixelConverter);

                    // Draw accumulated vertical line
                    DrawLine(
                        series,
                        prevDataPoint,
                        pointRangeMin,
                        pointRangeMax,
                        index - 1,
                        (prevPointIsEmpty) ? emptyLinePen : linePen,
                        prevPoint.X,
                        (float)yValueRangeMin,
                        prevPoint.X,
                        (float)yValueRangeMax);

                    verticalLineDetected = false;
                    yValueRangeMin       = double.NaN;
                    yValueRangeMax       = double.NaN;
                    pointRangeMin        = null;
                    pointRangeMax        = null;
                }
            }

            // Reset Clip Region
            if (clipRegionSet)
            {
                graph.ResetClip();
            }
        }
示例#33
0
        private void Start_Click(object sender, EventArgs e)
        {
            //pictureBox2.Image = SandDiameterMeasuring.Properties.Resources.屏幕截图_1654_;
            // pictureBox2.Image.Dispose();
            // pictureBox2.Image = null;
            textBox1.Text = ("加载图片");
            OpenFileDialog file = new OpenFileDialog();

            file.InitialDirectory = ".";
            file.Filter           = "所有文件(*.*)|*.*";
            file.ShowDialog();
            if (file.FileName != string.Empty)
            {
                try
                {
                    pathname = file.FileName;   //获得文件的绝对路径
                    this.pictureBox1.Load(pathname);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            string str1 = file.FileName;

            //str1 = "'" + str1 + "'";//加单引号为符合matlab输入规范
            textBox1.Text = (str1);
            //textBox1.Text = (file.FileName);
            DiameterCalculation.Class1 c1 = new DiameterCalculation.Class1();
            //Object sandNumber;
            MWArray        a1 = c1.linktocsharp(str1);
            MWNumericArray a2 = (MWNumericArray)a1;

            textBox2.Text = a2.ToString();

            linktocsharpV5.Class1 v5c1 = new linktocsharpV5.Class1();
            //MWArray DiameterArray = v3c1.linktocsharpV3(str1);
            MWArray[] resultlist = new MWArray[2];
            resultlist = v5c1.linktocsharpV5(4, str1);                     //重要!!!m函数有多个返回值时在第一个参数里写入返回值个数,第二个参数才是输入m函数的第一个输入参数
            MWNumericArray DiameterArray  = (MWNumericArray)resultlist[0]; //返回每一粒沙子的直径数组,为n行1列的二维数组
            MWNumericArray SandNumber     = (MWNumericArray)resultlist[1]; //沙尘个数
            MWNumericArray DiameterNumber = (MWNumericArray)resultlist[2]; //返回以50um为单位的粒径累加结果数组
            MWNumericArray xlength        = (MWNumericArray)resultlist[3]; //返回以50um为单位的粒径累加结果数组

            double[,] DA = new double[(int)SandNumber, 1];                 //matlab函数返回值为二维数组,因此需要用二维数组接收
            DA           = (double[, ])DiameterArray.ToArray();
            double[,] DN = new double[(int)xlength, 1];                    //matlab函数返回值为二维数组,因此需要用二维数组接收
            DN           = (double[, ])DiameterNumber.ToArray();
            //textBox3.Text = DA[(int)a2 - 1, 0].ToString();
            //textBox3.Text = DA[(int)SandNumber - 1, 0].ToString();

            chart1.Series.Clear();
            ChartHelper.AddSeries(chart1, "由小到大每一粒沙尘的粒径", SeriesChartType.Column, Color.Transparent, Color.Red, true);
            //   ChartHelper.AddSeries(chart1, "由小到大每一粒沙尘的粒径", SeriesChartType.Spline, Color.Red, Color.Red);
            //   ChartHelper.SetTitle(chart1, "由小到大每一粒沙尘的粒径", new Font("微软雅黑", 8), Docking.Top, Color.Black);
            ChartHelper.SetStyle(chart1, Color.Transparent, Color.Black);
            ChartHelper.SetLegend(chart1, Docking.Top, StringAlignment.Center, Color.Transparent, Color.Black);
            ChartHelper.SetXY(chart1, "", "粒径(*50um)", StringAlignment.Far, Color.Black, Color.Black, AxisArrowStyle.SharpTriangle, 0, 0);
            ChartHelper.SetMajorGrid(chart1, Color.Transparent, 20, 50);
            List <int> xData = new List <int>()
            {
            };
            int i, j;

            for (i = 1; i <= (int)SandNumber; i++)
            {
                xData.Add(i);
            }
            List <double> yData = new List <double>()
            {
            };

            for (j = 0; j <= (int)SandNumber - 1; j++)
            {
                yData.Add(DA[j, 0]);
            }
            chart1.Series[0].Points.DataBindXY(xData, yData);

            chart2.Series.Clear();
            ChartHelper.AddSeries(chart2, "该粒径范围内沙尘个数", SeriesChartType.Column, Color.Lime, Color.Blue, true);
            //      ChartHelper.AddSeries(chart2, "曲线图", SeriesChartType.Spline, Color.Red, Color.Red);
            //      ChartHelper.SetTitle(chart2, "柱状图与曲线图", new Font("微软雅黑", 12), Docking.Bottom, Color.Black);
            ChartHelper.SetStyle(chart2, Color.Transparent, Color.Black);
            ChartHelper.SetLegend(chart2, Docking.Top, StringAlignment.Center, Color.Transparent, Color.Black);
            ChartHelper.SetXY(chart2, "粒径(*50um)", "个数", StringAlignment.Far, Color.Black, Color.Black, AxisArrowStyle.SharpTriangle, 4, (int)(DN[0, 0] / 10));
            ChartHelper.SetMajorGrid(chart2, Color.Transparent, 20, 2);
            List <int> xData2 = new List <int>()
            {
            };
            int i2, j2;

            for (i2 = 1; i2 <= (int)xlength; i2++)
            {
                xData2.Add(i2);
            }
            List <double> yData2 = new List <double>()
            {
            };

            for (j2 = 0; j2 <= (int)xlength - 1; j2++)
            {
                yData2.Add(DN[j2, 0]);
            }
            chart2.Series[0].Points.DataBindXY(xData2, yData2);


            //textBox2.Text = (sandNumber.ToString);
            string pathname2;

            pathname2 = "D:\\op\\tempresult.png";  //获得文件的绝对路径
            //this.pictureBox2.Load(pathname2);//load貌似过时了?
            // this.pictureBox2.Image = Image.FromFile(pathname2);
            //    pictureBox2.Image.Dispose();
            FileStream pFileStream = new FileStream(pathname2, FileMode.Open, FileAccess.Read);

            pictureBox2.Image = Image.FromStream(pFileStream);
            pFileStream.Close();
            pFileStream.Dispose();
        }