private void Draw() { int[] x = { 1, 2, 3, 4, 5 }; int[] y = { 5, 4, 3, 2, 1 }; GraphPane pane = zgcHist.GraphPane; pane.CurveList.Clear(); PointPairList list = new PointPairList(); for (long j = 0; j < x.Length; j++) { if (x[j] != 0) { list.Add(x[j], y[j]); } } //BurlyWood Coral DarkMagenta LineItem myCurve = pane.AddCurve("Curve", list, Color.Coral, SymbolType.None); //Color color = Color.FromArgb(100, Color.Coral); //myCurve.Line.Fill = new ZedGraph.Fill(color); pane.YAxis.Scale.Min = 0; pane.YAxis.Scale.Max = 1.1 * y.Max(); zgcHist.AxisChange(); zgcHist.Invalidate(); }
private void Draw(int[] x, int[] y, int[] z) { GraphPane pane = zgcHist.GraphPane; pane.CurveList.Clear(); PointPairList list = new PointPairList(); PointPairList list2 = new PointPairList(); for (long j = 0; j < x.Length; j++) { if (x[j] != 0) { list.Add(x[j], y[j]); list2.Add(x[j], z[j]); } } //BurlyWood Coral DarkMagenta LineItem myCurve = pane.AddCurve("Гистограмма", list, Color.Coral, SymbolType.None); //Color color = Color.FromArgb(100, Color.Coral); //myCurve.Line.Fill = new ZedGraph.Fill(color); pane.AddCurve("Ожидаемый результат", list2, Color.BurlyWood, SymbolType.None); pane.YAxis.Scale.Min = 0; pane.YAxis.Scale.Max = 1.1*y.Max(); pane.Title.Text = filename; zgcHist.AxisChange(); zgcHist.Invalidate(); }
private bool zedGraphControl_PreMouseMoveEvent(ZedGraphControl sender, MouseEventArgs e) { double newX, newY; if (e.Button == MouseButtons.Left && _drawCurve) { int textThreshold = textBoxThreshold.Text == "" ? (int)0 : Convert.ToInt16(textBoxThreshold.Text); // only add if we've actually clicked on the pane, so make sure the mouse is over it first if (zedGraphControl.MasterPane.FindPane(e.Location) != null) { PointPairList pointList = zedGraphControl.GraphPane.CurveList[0].Points as PointPairList; zedGraphControl.GraphPane.ReverseTransform(e.Location, out newX, out newY); if (pointList.Count == 0 && _tempX < newX - 1) { pointList.Insert(0, 0, newY); } //Verify the point is in the usable bounds. if (newX > 100) { newX = 100; } else if (newX < 0) { newX = 0; } if (newY > 100) { newY = 100; } else if (newY < 0) { newY = 0; } if (_tempX < newX - textThreshold) { if (newX >= 0) { pointList.Insert(0, newX, newY); } pointList.Sort(); zedGraphControl.Invalidate(); _tempX = newX; } } } if (zedGraphControl.IsEditing) { PointPairList pointList = zedGraphControl.GraphPane.CurveList[0].Points as PointPairList; pointList.Sort(); return(false); } //Used to move Curve higher or lower on the grid or when shift is pressed will flatten curve and then move higher or lower on the grid. if (e.Button == MouseButtons.Left && !_drawCurve) { zedGraphControl.GraphPane.ReverseTransform(e.Location, out newX, out newY); if (ModifierKeys.HasFlag(Keys.Shift)) { //Verify the point is in the usable bounds. only care about the Y axis. if (newY > 100) { newY = 100; } else if (newY < 0) { newY = 0; } var points = new PointPairList(new[] { 0.0, 100.0 }, new[] { newY, newY }); PointPairList pointList = zedGraphControl.GraphPane.CurveList[0].Points as PointPairList; pointList.Clear(); pointList.Add(points); zedGraphControl.Invalidate(); txtYValue.Text = newY.ToString("0.####"); txtXValue.Text = ""; } else { if (ModifierKeys == Keys.None) { //Move curve higher or lower on the Y axis. bool stopUpdating = false; PointPairList pointList = zedGraphControl.GraphPane.CurveList[0].Points as PointPairList; //Check if any curve point extends past the Y axis. foreach (var points in pointList) { if ((points.Y >= 100 && newY > _previousCurveYLocation) || (points.Y <= 0 && newY < _previousCurveYLocation)) { double adjustedPoint = 0; if (points.Y > 100) { adjustedPoint = points.Y - 100; } if (points.Y < 0) { adjustedPoint = points.Y; } //ensures the curve remains bound by the upper and lower limits. foreach (var updatePoints in pointList) { updatePoints.Y = updatePoints.Y - adjustedPoint; } stopUpdating = true; break; } } if (!stopUpdating) { //New curve location foreach (var points in pointList) { points.Y = points.Y + (newY - _previousCurveYLocation); } } _previousCurveYLocation = newY; zedGraphControl.Invalidate(); } } } return(false); }
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(); }
public Form4() { InitializeComponent(); double[] x = new double[] { 10, 20, 30, 40, 50, 60, 70, 80 }; double[] y = new double[] { 2.5, 3.2, 3.7, 4.0, 4.2, 4.4, 4.6, 4.75 }; double[] yy1 = new double[15]; double[] yy2 = new double[15]; double[] yy3 = new double[15]; double[] yy4 = new double[15]; int i; double a1, b1, c1; double a2, b2, c2; double a3, b3, c3; double a4, b4, c4; a1 = ((y[2] - y[0]) * (x[1] - x[0]) - (y[1] - y[0]) * (x[2] - x[0])) / ((Math.Pow(x[2], 2) - Math.Pow(x[0], 2)) * (x[1] - x[0]) - (Math.Pow(x[1], 2) - Math.Pow(x[0], 2)) * (x[2] - x[0])); b1 = (y[1] - y[0] - a1 * (Math.Pow(x[1], 2) - Math.Pow(x[0], 2))) / (x[1] - x[0]); c1 = y[0] - (a1 * Math.Pow(x[0], 2) + b1 * x[0]); a2 = ((y[4] - y[2]) * (x[3] - x[2]) - (y[3] - y[2]) * (x[4] - x[2])) / ((Math.Pow(x[4], 2) - Math.Pow(x[2], 2)) * (x[3] - x[2]) - (Math.Pow(x[3], 2) - Math.Pow(x[2], 2)) * (x[4] - x[2])); b2 = (y[3] - y[2] - a2 * (Math.Pow(x[3], 2) - Math.Pow(x[2], 2))) / (x[3] - x[2]); c2 = y[2] - (a2 * Math.Pow(x[2], 2) + b2 * x[2]); a3 = ((y[6] - y[4]) * (x[5] - x[4]) - (y[5] - y[4]) * (x[6] - x[4])) / ((Math.Pow(x[6], 2) - Math.Pow(x[4], 2)) * (x[5] - x[4]) - (Math.Pow(x[5], 2) - Math.Pow(x[4], 2)) * (x[6] - x[4])); b3 = (y[5] - y[4] - a3 * (Math.Pow(x[5], 2) - Math.Pow(x[4], 2))) / (x[5] - x[4]); c3 = y[4] - (a3 * Math.Pow(x[4], 2) + b3 * x[4]); a4 = ((y[7] - y[5]) * (x[6] - x[5]) - (y[6] - y[5]) * (x[7] - x[5])) / ((Math.Pow(x[7], 2) - Math.Pow(x[5], 2)) * (x[6] - x[5]) - (Math.Pow(x[6], 2) - Math.Pow(x[5], 2)) * (x[7] - x[5])); b4 = (y[6] - y[5] - a4 * (Math.Pow(x[6], 2) - Math.Pow(x[5], 2))) / (x[6] - x[5]); c4 = y[5] - (a4 * Math.Pow(x[5], 2) + b4 * x[5]); double[] xx1 = new double[] { 10, 15, 20, 25, 30 }; double[] xx2 = new double[] { 30, 35, 40, 45, 50 }; double[] xx3 = new double[] { 50, 55, 60, 65, 70 }; double[] xx4 = new double[] { 70, 75, 80 }; for (i = 0; i <= 4; i++) { yy1[i] = a1 * Math.Pow(xx1[i], 2) + b1 * xx1[i] + c1; } for (i = 0; i <= 4; i++) { yy2[i] = a2 * Math.Pow(xx2[i], 2) + b2 * xx2[i] + c2; } for (i = 0; i <= 4; i++) { yy3[i] = a3 * Math.Pow(xx3[i], 2) + b3 * xx3[i] + c3; } for (i = 0; i <= 2; i++) { yy4[i] = a4 * Math.Pow(xx4[i], 2) + b4 * xx4[i] + c4; } GraphPane pane = zed.GraphPane; pane.CurveList.Clear(); pane.XAxis.Title = "x"; pane.YAxis.Title = "y"; pane.Title = "Квадратичный сплайн"; PointPairList list1 = new PointPairList(); PointPairList list2 = new PointPairList(); PointPairList list3 = new PointPairList(); PointPairList list4 = new PointPairList(); for (i = 0; i <= 4; i++) { list1.Add(xx1[i], yy1[i]); } for (i = 0; i <= 4; i++) { list2.Add(xx2[i], yy2[i]); } for (i = 0; i <= 4; i++) { list3.Add(xx3[i], yy3[i]); } for (i = 0; i <= 2; i++) { list4.Add(xx4[i], yy4[i]); } LineItem myCurve1 = pane.AddCurve("", list1, Color.Blue, SymbolType.None); //линия LineItem myCurve2 = pane.AddCurve("", list2, Color.Blue, SymbolType.None); //линия LineItem myCurve3 = pane.AddCurve("", list3, Color.Blue, SymbolType.None); //линия LineItem myCurve4 = pane.AddCurve("", list4, Color.Blue, SymbolType.None); //линия PointPairList list5 = new PointPairList(); for (i = 0; i <= 7; i++) { list5.Add(x[i], y[i]); } LineItem myCurve5 = pane.AddCurve("", list5, Color.Red, SymbolType.Circle);//точки myCurve5.Line.IsVisible = false; myCurve5.Symbol.Size = 3; //размер точек myCurve5.Symbol.Fill.Color = Color.Red; //заливка точек myCurve5.Symbol.Fill.Type = FillType.Solid; //сплошная заливка zed.AxisChange(); zed.Invalidate(); //обновляем график }
public void CreateScatterplot(ZedGraphControl zgc, double[] x, double[] y, double[] slr, double[] rlr, double[] inliersX, double[] inliersY) { GraphPane myPane = zgc.GraphPane; myPane.CurveList.Clear(); // Set the titles myPane.Title.IsVisible = false; myPane.Chart.Border.IsVisible = false; myPane.XAxis.Title.Text = "X"; myPane.YAxis.Title.Text = "Y"; myPane.XAxis.IsAxisSegmentVisible = true; myPane.YAxis.IsAxisSegmentVisible = true; myPane.XAxis.MinorGrid.IsVisible = false; myPane.YAxis.MinorGrid.IsVisible = false; myPane.XAxis.MinorTic.IsOpposite = false; myPane.XAxis.MajorTic.IsOpposite = false; myPane.YAxis.MinorTic.IsOpposite = false; myPane.YAxis.MajorTic.IsOpposite = false; myPane.XAxis.Scale.MinGrace = 0; myPane.XAxis.Scale.MaxGrace = 0; myPane.YAxis.Scale.MinGrace = 0; myPane.YAxis.Scale.MaxGrace = 0; PointPairList list1 = new PointPairList(x, y); PointPairList list2 = null; PointPairList list3 = null; PointPairList list4 = new PointPairList(inliersX, inliersY); if (slr != null) { list2 = new PointPairList(x, slr); } if (rlr != null) { list3 = new PointPairList(x, rlr); } if (inliersX != null) { list4 = new PointPairList(inliersX, inliersY); } LineItem myCurve; // Add the curves myCurve = myPane.AddCurve("Inliers", list4, Color.Blue, SymbolType.Circle); myCurve.Line.IsVisible = false; myCurve.Symbol.Fill = new Fill(Color.Blue); myCurve = myPane.AddCurve("Points", list1, Color.Gray, SymbolType.Circle); myCurve.Line.IsVisible = false; myCurve.Symbol.Border.IsVisible = false; myCurve.Symbol.Fill = new Fill(Color.Gray); myCurve = myPane.AddCurve("Simple", list2, Color.Red, SymbolType.Circle); myCurve.Line.IsAntiAlias = true; myCurve.Line.IsVisible = true; myCurve.Symbol.IsVisible = false; myCurve = myPane.AddCurve("RANSAC", list3, Color.Blue, SymbolType.Circle); myCurve.Line.IsAntiAlias = true; myCurve.Line.IsVisible = true; myCurve.Symbol.IsVisible = false; zgc.AxisChange(); zgc.Invalidate(); }
// non deve prendere un array di double, ma meglio una lista di packet. altrimenti // devo richiareextract data ogni volta che premo un qualsiasi bottone, meglio // fare la chiamata allínterno di display data // ricevo un solo parametro, list<Packet> // all'interno del metodo richiamare la funzione extractData, // e passare i volire della funzione richiesta // pulire il grafico nel se non si devono visualizzare gli angoli di eulero private void DisplayData(List <Packet> sampwin) { // controllo se e' attivo lo smoothing!! if (smoothRange < 10) { checkBox3.Enabled = false; cutOff_value.Enabled = false; } samplewin = sampwin; smoothed = DataAnalysis.SmoothData(samplewin, smoothRange); filtered = smoothing_cb.Checked ? smoothed : samplewin; if (checkBox1.Checked) { selected = DataAnalysis.ComputeHighPass(filtered); } else { if (checkBox2.Checked) { selected = DataAnalysis.ComputeLowPass(filtered); } else { selected = filtered; } } smooth = smoothing_cb.Checked; double[,] data; myPane.CurveList.Clear(); zedGraphControl1.Invalidate(); //if (willClearPane) { myPane.CurveList.Clear(); } myPane.XAxis.Title.Text = "time (seconds)"; switch (selectedSensorType) { case 0: //acc //printToServerConsole("acc"); myPane.YAxis.Title.Text = "m/s²"; break; case 1: //gyr //printToServerConsole("gry"); myPane.YAxis.Title.Text = "Rad/s²"; break; case 2: //mag //printToServerConsole("mag"); myPane.YAxis.Title.Text = "Tesla"; break; case 3: //qua //printToServerConsole("qua"); myPane.YAxis.Title.Text = "y"; break; default: //bohh myPane.YAxis.Title.Text = "none"; break; } // ottengo i dati in base al sensore selezionato e posizione data = ExtractData(selectedSensorType, selectedSensor); double[] modules = DataAnalysis.ComputeModules(data); PointPairList plist = new PointPairList(); switch (selectedGraph) { case 0: // module //printToServerConsole("mod"); plist.Clear(); double t = 0; for (int i = 0; i < modules.Length; i++) { plist.Add(new PointPair(t, modules[i])); t += 1.0 / frequence; } // problemi con i titoli myPane.Title.Text = "Module"; if (!smooth) { myPane.AddCurve("Module", plist, Color.Blue, SymbolType.None); } else { myPane.AddCurve("Module Smoothed", plist, Color.Blue, SymbolType.None); } zedGraphControl1.AxisChange(); zedGraphControl1.Refresh(); break; case 1: // der //printToServerConsole("dev"); plist.Clear(); t = 0; double[] drv = DataAnalysis.ComputeDerivatives(modules, Int32.Parse(frequence_box.Text)); for (int i = 0; i < drv.Length; i++) { plist.Add(new PointPair(t, drv[i])); t += 1.0 / frequence; } myPane.Title.Text = "Derivated"; if (!smooth) { myPane.AddCurve("Derivated", plist, Color.Blue, SymbolType.None); } else { myPane.AddCurve("Derivated Smoothed", plist, Color.Blue, SymbolType.None); } zedGraphControl1.AxisChange(); zedGraphControl1.Refresh(); break; case 2: // std //printToServerConsole("std"); plist.Clear(); t = 0; double[] dst0 = DataAnalysis.ComputeStandardDeviations(modules, smoothRange); double epsilon = 0.4; // sotto i 10 non squadra nulla di corretto perche' e' troppo instabile, sopra il 25 tentenna. tra 10 e 25 ok /*if (smoothing_cb.Checked) { * if (smoothRange >= 10 && smoothRange < 20) { * cutOff = 0.53; * } * else if (smoothRange >= 20 && smoothRange < 30) { * cutOff = 0.33; * } * else { * cutOff = 0.21; * } * } * else { * cutOff = 1.5; * }*/ double[] dst = checkBox3.Checked ? DataAnalysis.ComputeSquare(dst0, frequence, cutOff, epsilon) : dst0; for (int i = 0; i < dst.Length; i++) { plist.Add(new PointPair(t, dst[i])); t += 1.0 / frequence; } myPane.Title.Text = "Module Standard Deviation"; if (!smooth) { myPane.AddCurve("Module Standard Deviation", plist, Color.Blue, SymbolType.None); } else { myPane.AddCurve("Smoothed Module Standard Deviation", plist, Color.Blue, SymbolType.None); } zedGraphControl1.AxisChange(); zedGraphControl1.Refresh(); break; case 3: // euler EulerGraph(); break; case 4: // dead int size = samplewin.Count; double[,] q0 = new double[size, 4]; for (int p = 0; p < size; p++) { for (int i = 0; i < 4; i++) { q0[p, i] = samplewin[p].Sensors[0].q[i]; } } double[,] acc = new double[size, 3]; for (int p = 0; p < size; p++) { for (int i = 0; i < 3; i++) { acc[p, i] = samplewin[p].Sensors[0].acc[i]; } } double[,] mag = new double[size, 3]; for (int p = 0; p < size; p++) { for (int i = 0; i < 3; i++) { mag[p, i] = samplewin[p].Sensors[0].mag[i]; } } PointPairList dead = DataAnalysis.ComputeDeadReckoning(q0, acc, mag, frequence, window); PointPairList start = new PointPairList(); start.Add(dead.First()); PointPairList end = new PointPairList(); end.Add(dead.Last()); dead.RemoveAt(0); dead.RemoveAt(dead.Count - 1); GraphPane pane = zedGraphControl1.GraphPane; pane.CurveList.Clear(); myPane.Title.Text = "Dead Reckoning"; myPane.YAxis.Title.Text = "m"; myPane.XAxis.Title.Text = "m"; pane.AddCurve("Start point", start, Color.Green, SymbolType.Square); pane.AddCurve("Path", dead, Color.Black, SymbolType.None); pane.AddCurve("End point", end, Color.Red, SymbolType.Circle); zedGraphControl1.AxisChange(); zedGraphControl1.Refresh(); break; case 5: // arc tan plist.Clear(); t = 0; mag = ExtractData(2, selectedSensor); size = mag.GetLength(0); double[] magY = new double[size]; double[] magZ = new double[size]; for (int i = 0; i < size; i++) { magY[i] = mag[i, 1]; magZ[i] = mag[i, 2]; } double[,] tan = DataAnalysis.FunzioneOrientamento(magY, magZ); double[,] smtan = DataAnalysis.RemoveDiscontinuities(tan); for (int i = 0; i < size; i++) { plist.Add(new PointPair(t, smtan[i, 0])); t += 1.0 / frequence; } myPane.Title.Text = "Arc Tan(MagY/MagZ)"; if (!smooth) { myPane.AddCurve("Arc Tan(MagY/MagZ)", plist, Color.Blue, SymbolType.None); } else { myPane.AddCurve("Arc Tan(MagY/MagZ) Smoothed", plist, Color.Blue, SymbolType.None); } zedGraphControl1.AxisChange(); zedGraphControl1.Refresh(); break; case 6: // acc x plist.Clear(); t = 0; acc = ExtractData(0, selectedSensor); size = acc.GetLength(0); double[] accX = new double[size]; for (int i = 0; i < size; i++) { accX[i] = acc[i, 0]; } double[] accX_opt = checkBox3.Checked ? DataAnalysis.ComputeSquare(accX, frequence, 7, 0.4) : accX; for (int i = 0; i < size; i++) { plist.Add(new PointPair(t, accX_opt[i])); t += 1.0 / frequence; } myPane.YAxis.Title.Text = "N/kg"; myPane.Title.Text = "Acc X"; if (!smooth) { myPane.AddCurve("Acc X", plist, Color.Blue, SymbolType.None); } else { myPane.AddCurve("Acc X Smoothed", plist, Color.Blue, SymbolType.None); } zedGraphControl1.AxisChange(); zedGraphControl1.Refresh(); // modulo acc x // point pair list break; } }
/// <summary> /// Add a <see c_ref="PointPair"/> object to the end of the points collection for this curve. /// </summary> /// <remarks> /// This method will only work if the <see c_ref="IPointList" /> instance reference /// at <see c_ref="Points" /> supports the <see c_ref="IPointListEdit" /> interface. /// Otherwise, it does nothing. /// </remarks> /// <param name="point">A reference to the <see c_ref="PointPair"/> object to /// be added</param> public void AddPoint( PointPair point ) { if ( _points == null ) Points = new PointPairList(); if ( _points is IPointListEdit ) ( _points as IPointListEdit ).Add( point ); else throw new NotImplementedException(); }
private List <double> getPeakStatistics() { IList <object[]> queryRows; lock (session) { var randomIds = session.CreateQuery("SELECT psm.Id " + viewFilter.GetFilteredQueryString(DataFilter.FromPeptideSpectrumMatch)) .List <long>() .Shuffle() .Take(1000) .OrderBy(o => o); string randomIdSet = String.Join(",", randomIds.Select(o => o.ToString()).ToArray()); queryRows = session.CreateQuery("SELECT psm.Spectrum.Source.Name, psm.Spectrum, psm, DISTINCT_GROUP_CONCAT(pm.Offset || ':' || mod.MonoMassDelta), psm.Peptide.Sequence " + "FROM PeptideSpectrumMatch psm " + "LEFT JOIN psm.Modifications pm " + "LEFT JOIN pm.Modification mod " + "WHERE psm.Id IN (" + randomIdSet + ") " + "GROUP BY psm.Spectrum.id ") .List <object[]>(); } var spectrumRows = queryRows.Select(o => new SpectrumRow(o)).OrderBy(o => o.SourceName); precursorScatterPlot.Clear(); chargeReducedScatterPlot.Clear(); int spectraCount = 0; string spectrumListFilters = String.Empty; Invoke(new MethodInvoker(() => { spectrumListFilters = spectrumFiltersTextBox.Text; zedGraphControl.MasterPane.AxisChange(); zedGraphControl.Refresh(); })); var points = new PointPairList(); string currentSourceName = null; string currentSourcePath = null; msdata.MSData msd = null; lock (owner) foreach (var row in spectrumRows) { if (row.SourceName != currentSourceName) { currentSourceName = row.SourceName; currentSourcePath = IDPickerForm.LocateSpectrumSource(currentSourceName, session.Connection.GetDataSource()); msd = new pwiz.CLI.msdata.MSDataFile(currentSourcePath); //var param = session.Query<AnalysisParameter>().Where(o => o.Name == "SpectrumListFilters").Min(o => o.Value); //string spectrumListFilters = String.IsNullOrEmpty(param) ? String.Empty : param; SpectrumListFactory.wrap(msd, spectrumListFilters.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)); } string label = String.Format("{0}/{1}\n{2}", row.SourceName, msdata.id.abbreviate(row.Spectrum.NativeID), row.ModifiedSequence); var spectrumList = msd.run.spectrumList; ++spectraCount; var pwizPeptide = new proteome.Peptide(row.ModifiedSequence, proteome.ModificationParsing.ModificationParsing_Auto, proteome.ModificationDelimiter.ModificationDelimiter_Brackets); var fragmentation = pwizPeptide.fragmentation(true, true); var pwizSpectrum = spectrumList.spectrum(spectrumList.find(row.Spectrum.NativeID), true); var pointMap = new seems.PointMap(new ZedGraph.PointPairList(pwizSpectrum.getMZArray().data, pwizSpectrum.getIntensityArray().data)); double tic = pointMap.Values.Sum(); double precursorMz = row.Spectrum.PrecursorMZ; double chargeReducedPrecursorMz = precursorMz * row.PeptideSpectrumMatch.Charge; bool plotMatchedPeaks = true; bool removeMatchedPeaks = false; double tolerance = 0.03; seems.PointMap.Enumerator itr; IonSeries[] ionSeries = Enum.GetValues(typeof(IonSeries)).Cast <IonSeries>().Where(o => o != IonSeries.Count).ToArray(); for (int z = 1; z <= 1; ++z) { for (int length = 1, end = pwizPeptide.sequence.Length; length <= end; ++length) { string NTermFragment = row.ModifiedSequence.Substring(0, length); string CTermFragment = row.ModifiedSequence.Substring(row.ModifiedSequence.Length - length); foreach (IonSeries series in ionSeries) { if ((series == IonSeries.c || series == IonSeries.cMinus1 || series == IonSeries.x) && length == pwizPeptide.sequence.Length) { continue; } itr = pointMap.FindNear(fragmentMass(fragmentation, series, length, z), tolerance); if (itr != null && itr.IsValid) { if (plotMatchedPeaks) { precursorScatterPlot.AddPoint(new PointPair(itr.Current.Key - precursorMz, itr.Current.Value / tic, (int)series, String.Format("{0} {1}\n{2} {3} {4} {5}", label, precursorMz, NTermFragment, itr.Current.Key, IonSeriesLabels[(int)series], length))); chargeReducedScatterPlot.AddPoint(new PointPair(itr.Current.Key - chargeReducedPrecursorMz, itr.Current.Value / tic, (int)series, String.Format("{0} {1}\n{2} {3} {4} {5}", label, chargeReducedPrecursorMz, NTermFragment, itr.Current.Key, IonSeriesLabels[(int)series], length))); } if (removeMatchedPeaks) { pointMap.Remove(itr); } } } } } foreach (var pair in pointMap) { precursorScatterPlot.AddPoint(new PointPair(pair.Key - precursorMz, pair.Value / tic, 0, label)); chargeReducedScatterPlot.AddPoint(new PointPair(pair.Key - chargeReducedPrecursorMz, pair.Value / tic, 0, label)); } if ((spectraCount % 100) == 0) { Invoke(new MethodInvoker(() => { zedGraphControl.MasterPane.AxisChange(); zedGraphControl.Refresh(); })); } } Invoke(new MethodInvoker(() => { if (!lockZoomCheckBox.Checked) { zedGraphControl.ZoomOutAll(zedGraphControl.GraphPane); } zedGraphControl.MasterPane.AxisChange(); zedGraphControl.Refresh(); })); return(new List <double>()); //percentTicBySpectrumByFragmentType[1]; }
private void buttonErase_Click(object sender, EventArgs e) { chart.GraphPane.CurveList.Clear(); chart.Invalidate(); list = null; }
/// <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_VAUES.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_VAUES.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_VAUES.GRID); // Устанавливаем интересующий нас интервал по оси Y pane.YAxis.Scale.Min = minimum_scale; pane.YAxis.Scale.Max = maximum_scale; AxisChange(); Invalidate(); }
public LagrangeInterpolation(PointPairList inputPoints) : base(inputPoints) { }
private void AddImpliedVolatilityPoints() { GraphPane pane = volatilityGraph.GraphPane; string NX = "N" + Comm.Server.DisplayAccuracy.ToString(); string filter = ""; if (optionsFilterForm.OptionsFilter == "()") { filter = " AND (Type = '')"; // empty list } else if (optionsFilterForm.OptionsFilter != "") { filter = " AND " + optionsFilterForm.OptionsFilter; } DataRow[] p_rows = core.OptionsTable.Select("(Type = 'Put')" + filter, ""); PointPairList p_list = new PointPairList(); foreach (DataRow row in p_rows) { TimeSpan ts = ((DateTime)row["Expiration"]) - DateTime.Now; double dy = (ts.Days % 7) + (ts.Days / 7) * 5; double iv = (double)row["ImpliedVolatility"]; if (!double.IsNaN(iv) && dy > 0) { PointPair p = new PointPair(dy, iv); p.Tag = "Put " + ((double)row["Strike"]).ToString(NX) + " @ " + ((DateTime)row["Expiration"]).ToString("dd-MMM-yy") + ", ImpVol = " + iv.ToString("N2") + " %"; p_list.Add(p); } } // remove existing symbols if (volatility_puts_symb != null) { pane.CurveList.Remove(volatility_puts_symb); } volatility_puts_symb = pane.AddCurve("Puts", p_list, Config.Color.PositionBackColor(0), SymbolType.Diamond); volatility_puts_symb.Symbol.Size = 10; volatility_puts_symb.Symbol.Fill = new Fill(Config.Color.PositionBackColor(0)); volatility_puts_symb.Symbol.IsAntiAlias = true; volatility_puts_symb.Line.IsVisible = false; DataRow[] c_rows = core.OptionsTable.Select("(Type = 'Call')" + filter, ""); PointPairList c_list = new PointPairList(); foreach (DataRow row in c_rows) { TimeSpan ts = ((DateTime)row["Expiration"]) - DateTime.Now; double dy = (ts.Days % 7) + (ts.Days / 7) * 5; double iv = (double)row["ImpliedVolatility"]; if (!double.IsNaN(iv) && dy > 0) { PointPair p = new PointPair(dy, iv); p.Tag = "Call " + ((double)row["Strike"]).ToString(NX) + " @ " + ((DateTime)row["Expiration"]).ToString("dd-MMM-yy") + ", ImpVol = " + iv.ToString("N2") + " %"; c_list.Add(p); } } // remove existing symbols if (volatility_calls_symb != null) { pane.CurveList.Remove(volatility_calls_symb); } volatility_calls_symb = pane.AddCurve("Calls", c_list, Config.Color.PositionBackColor(1), SymbolType.Diamond); volatility_calls_symb.Symbol.Size = 10; volatility_calls_symb.Symbol.Fill = new Fill(Config.Color.PositionBackColor(1)); volatility_calls_symb.Symbol.IsAntiAlias = true; volatility_calls_symb.Line.IsVisible = false; }
/// <summary> /// Experimental method to attempt to execute any type of effect. Unused at the moment and needs work. /// </summary> /// <param name="elementEffect"></param> /// <returns></returns> public static Status Effect(ElementEffect elementEffect) { if (elementEffect == null) { throw new ArgumentNullException("elementEffect"); } ElementNode node = VixenSystem.Nodes.GetElementNode(elementEffect.Id); if (node == null) { throw new ArgumentException(@"Invalid element id", @"elementEffect"); } var status = new Status(); IModuleDescriptor effectDescriptor = ApplicationServices.GetModuleDescriptors <IEffectModuleInstance>().Cast <IEffectModuleDescriptor>().FirstOrDefault(x => x.EffectName.Equals(elementEffect.EffectName)); if (effectDescriptor != null) { var effect = ApplicationServices.Get <IEffectModuleInstance>(effectDescriptor.TypeId); EffectNode effectNode = CreateEffectNode(effect, node, TimeSpan.FromMilliseconds(elementEffect.Duration)); Object[] newValues = effectNode.Effect.ParameterValues; int index = 0; foreach (var sig in effectNode.Effect.Parameters) { if (sig.Type == typeof(Color)) { newValues[index] = ColorTranslator.FromHtml(elementEffect.Color.First().Key); } else { if (sig.Type == typeof(ColorGradient)) { var cg = new ColorGradient(); cg.Colors.Clear(); foreach (var d in elementEffect.Color) { cg.Colors.Add(new ColorPoint(ColorTranslator.FromHtml(d.Key), d.Value)); } newValues[index] = cg; } else { if (sig.Type == typeof(Curve)) { var pointPairList = new PointPairList(); foreach (KeyValuePair <double, double> keyValuePair in elementEffect.LevelCurve) { pointPairList.Add(keyValuePair.Key, keyValuePair.Value); } var curve = new Curve(pointPairList); newValues[index] = curve; } } } index++; } effectNode.Effect.ParameterValues = newValues; ApplyOptionParameters(effectNode, elementEffect.Options); Module.LiveContext.Execute(effectNode); status.Message = string.Format("{0} element(s) turned effect {1} for {2} milliseconds.", VixenSystem.Nodes.GetElementNode(elementEffect.Id).Name, elementEffect.EffectName, elementEffect.Duration); } return(status); }
private void UpdateGraph() { zGraph.GraphPane.CurveList.Clear(); zGraph.RestoreScale(zGraph.GraphPane); PointPairList pointsH2 = new PointPairList(); PointPairList pointsO2 = new PointPairList(); PointPairList pointsCO = new PointPairList(); PointPairList pointsCO2 = new PointPairList(); PointPairList pointsN2 = new PointPairList(); PointPairList pointsAr = new PointPairList(); PointPairList pointsTemp = new PointPairList(); PointPairList pointsFlow = new PointPairList(); PointPairList pointsRealCO = new PointPairList(); PointPairList pointsRealCO2 = new PointPairList(); PointPairList pointsRealFlow = new PointPairList(); double time; foreach (OffGas og in CurrentListOfGas) { time = (og.Date - CurrentFussion.StartDate).TotalSeconds; pointsH2.Add(time, og.H2); pointsO2.Add(time, og.O2); pointsCO.Add(time, og.CO); pointsCO2.Add(time, og.CO2); pointsN2.Add(time, og.N2); pointsAr.Add(time, og.Ar); pointsTemp.Add(time, og.Temperature); pointsFlow.Add(time, og.Flow / 60); } foreach (OffGasAnalysisEvent ogaEvent in _heat.OffGasAnalysisHistory) { time = (ogaEvent.Time - CurrentFussion.StartDate).TotalSeconds; pointsRealCO.Add(time, ogaEvent.CO); pointsRealCO2.Add(time, ogaEvent.CO2); } foreach (OffGasEvent ogEvent in _heat.OffGasHistory) { time = (ogEvent.Time - CurrentFussion.StartDate).TotalSeconds; pointsRealFlow.Add(time, ogEvent.OffGasFlow / 60); } if (cbH2.Checked) { zGraph.GraphPane.AddCurve("H2", pointsH2, Color.Green, SymbolType.None); } if (cbO2.Checked) { zGraph.GraphPane.AddCurve("O2", pointsO2, Color.Blue, SymbolType.None); } if (cbCO.Checked) { zGraph.GraphPane.AddCurve("CO", pointsCO, Color.Red, SymbolType.None); } if (cbCO2.Checked) { zGraph.GraphPane.AddCurve("CO2", pointsCO2, Color.Orange, SymbolType.None); } if (cbN2.Checked) { zGraph.GraphPane.AddCurve("N2", pointsN2, Color.Black, SymbolType.None); } if (cbAr.Checked) { zGraph.GraphPane.AddCurve("Ar", pointsAr, Color.Turquoise, SymbolType.None); } if (cbFlow.Checked) { zGraph.GraphPane.AddCurve("Flow", pointsFlow, Color.SaddleBrown, SymbolType.None); } if (cbTemp.Checked) { zGraph.GraphPane.AddCurve("Temp", pointsTemp, Color.OliveDrab, SymbolType.None); } if (cbRealCO.Checked) { zGraph.GraphPane.AddCurve("RealCO", pointsRealCO, Color.DarkGray, SymbolType.None); } if (cbRealCO2.Checked) { zGraph.GraphPane.AddCurve("RealCO2", pointsRealCO2, Color.Fuchsia, SymbolType.None); } if (cbRealFlow.Checked) { zGraph.GraphPane.AddCurve("RealFlow", pointsRealFlow, Color.MidnightBlue, SymbolType.None); } PointPairList pointsLance = new PointPairList(); PointPairList pointsOFlow = new PointPairList(); List<Lance> lanceHeights = CurrentListLance;//m_Db.GetLance(CurrentFussion.Id); if (lanceHeights.Count > 0) { int lanceHeight = lanceHeights.First().Height; for (double second = (lanceHeights.First().Date - CurrentFussion.StartDate).TotalSeconds; second < (lanceHeights.Last().Date - CurrentFussion.StartDate).TotalSeconds; second++) { foreach (Lance lance in lanceHeights) { if (second > 0) { if ((int)(lance.Date - CurrentFussion.StartDate).TotalSeconds == (int)second) { pointsLance.Add(second, lance.Height * Zoom); pointsOFlow.Add(second, lance.O2Flow * Zoom); lanceHeight = lance.Height; continue; } pointsLance.Add(second, lanceHeight); } } } } if (cbLance.Checked) { zGraph.GraphPane.AddCurve("Фурма", pointsLance, Color.Lime, SymbolType.None); } if (cbOFlow.Checked) { zGraph.GraphPane.AddCurve("OFlow", pointsOFlow, Color.Magenta, SymbolType.None); } //PointPairList pointsAdditions = new PointPairList(); if (gbVars.Controls.Count > 0) { MathParser mathParser = new MathParser(); int varsCount = gbVars.Controls.Count / 3; for (int i = 0; i < varsCount; i++) { if ((gbVars.Controls.Find(string.Format("cb{0}", i), true)[0] as System.Windows.Forms.CheckBox).Checked) { PointPairList points = new PointPairList(); foreach (OffGas og in CurrentListOfGas) { mathParser.CreateVar("H2", og.H2, null); mathParser.CreateVar("O2", og.O2, null); mathParser.CreateVar("CO", og.CO, null); mathParser.CreateVar("CO2", og.CO2, null); mathParser.CreateVar("N2", og.N2, null); mathParser.CreateVar("Ar", og.Ar, null); mathParser.Expression = (gbVars.Controls.Find(string.Format("tb{0}", i), true)[0] as System.Windows.Forms.TextBox).Text; try { points.Add((og.Date - CurrentFussion.StartDate).TotalSeconds, mathParser.ValueAsDouble * Zoom); } catch (Exception) { MessageBox.Show(string.Format("Переменная {0} задана неверно, ошибка в формуле", (gbVars.Controls.Find(string.Format("lb{0}", i), true)[0] as System.Windows.Forms.Label).Text)); return; } } mathParser.CreateVar((gbVars.Controls.Find(string.Format("lb{0}", i), true)[0] as System.Windows.Forms.Label).Text, mathParser.ValueAsString, null); if ((gbVars.Controls.Find(string.Format("cb{0}", i), true)[0] as System.Windows.Forms.CheckBox).Checked) { zGraph.GraphPane.AddCurve((gbVars.Controls.Find(string.Format("lb{0}", i), true)[0] as System.Windows.Forms.Label).Text, points, Color.DeepPink, SymbolType.None); } } } } zGraph.GraphPane.Title.IsVisible = false; this.Text = string.Format("Плавка: {0} Марка: {1} Начало: {2}({3}) Бригада: {4} Конвертер:{5} Т зад={6} Т факт={7} С зад={8} С факт={9}", CurrentFussion.Number, CurrentFussion.Grade, ((HeatAttributes) CurrentFussion).StartDate, CurrentFussion.StartDate, CurrentFussion.TeamNumber, CurrentFussion.AggregateNumber, CurrentFussion.PlannedTemperature, CurrentFussion.FactTemperature, CurrentFussion.PlannedCarbon, CurrentFussion.FactCarbon); zGraph.AxisChange(); zGraph.Invalidate(); }
/// <summary> /// Provides binding between <see cref="DataSource"/> and the specified pane. Extracts the /// data from <see cref="DataSource"/> and copies it into the appropriate /// <see cref="IPointList"/> for each <see cref="CurveItem"/> in the /// specified <see cref="GraphPane"/>. /// </summary> /// <param name="g">The <see cref="Graphics"/> object to be used for rendering the data.</param> /// <param name="pane">The <see cref="GraphPane"/> object which will receive the data.</param> protected void PopulateByDataSource( Graphics g, GraphPane pane ) { if ( this.CurveList.Count == 0 ) return; //If the Datasource column names are available we can bind them // correctly to their corresponding DataMember. if ( this.DataMember != null && this.DataMember != String.Empty && this.DataSource != null && this.DataSource is ITypedList && this.DataSource is IListSource ) { ITypedList tlist = this.DataSource as ITypedList; IListSource listSource = this.DataSource as IListSource; IList list = listSource.GetList(); PropertyDescriptorCollection pdc = tlist.GetItemProperties( null ); bool bListContainsList = listSource.ContainsListCollection; //Get the DataMember and Type of the base axis in the DataSource string baseDataMember = this.DataMember; PropertyDescriptor basePd = pdc.Find( baseDataMember, true ); if ( basePd == null ) throw new System.Exception( "Can't find DataMember '" + baseDataMember + "' in DataSource for the base axis." ); baseDataMember = basePd.Name; Type baseDataType = basePd.PropertyType; int indexBaseColumn = pdc.IndexOf( basePd ); //Foreach bar/curve // Get its DataMember and Type in the DataSource // Add the curve to the pane // Add all corresponding points(baseAxis,valueAxis,0) //Note: Z axis is not supported foreach ( ZeeGraphWebCurveItem curveItem in this.CurveList ) { //Axis valueAxis = curveItem.ValueAxis; PropertyDescriptorCollection pdcValue = pdc; IList valueList = list; bool bValueListContainsList = bListContainsList; //If present, use DataSource of Curve instead of main DataSource if ( curveItem.DataSource != null && curveItem.DataSource is ITypedList && curveItem.DataSource is IListSource ) { ITypedList valueTlist = curveItem.DataSource as ITypedList; pdcValue = valueTlist.GetItemProperties( null ); IListSource valueListSource = curveItem.DataSource as IListSource; valueList = valueListSource.GetList(); bValueListContainsList = valueListSource.ContainsListCollection; } string valueDataMember = curveItem.DataMember; PropertyDescriptor pd = pdcValue.Find( valueDataMember, true ); if ( pd == null ) throw new System.Exception( "Can't find DataMember '" + valueDataMember + "' in DataSource for the " + curveItem.Label + " axis." ); valueDataMember = pd.Name; //Get the exact case-dependent name Type valueDataType = pd.PropertyType; int indexValueColumn = pdcValue.IndexOf( pd ); //Add points PointPairList points = new PointPairList(); PointPair pair = new PointPair(); object oColumnValue; try { int nRow = 0; foreach ( object row in list ) { // // Value axis binding (Y axis) // object valueRow = valueList[nRow]; //Get item value in 'row' if ( bValueListContainsList ) { if ( !( valueRow is IList ) ) throw new System.InvalidCastException( "The DataSource contains a list which declares its items as lists, but these don't support the IList interface." ); oColumnValue = ( valueRow as IList )[indexValueColumn]; } else { oColumnValue = pd.GetValue( valueRow ); } //Convert value to double (always double) double v = 0; switch ( oColumnValue.GetType().ToString() ) { case "System.DateTime": v = new XDate( Convert.ToDateTime( oColumnValue ) ).XLDate; break; default: try { v = Convert.ToDouble( oColumnValue ); } catch { throw new NotImplementedException( "Conversion from " + oColumnValue.GetType() + " to double not implemented." ); } break; } // // Base axis binding (X axis) // pair.Tag = oColumnValue; //Original typed value pair.Y = v; if ( this.XAxis.Type == AxisType.DateAsOrdinal || this.XAxis.Type == AxisType.Date ) { pair.X = new XDate( Convert.ToDateTime( basePd.GetValue( row ) ) ).XLDate; } else pair.X = Convert.ToDouble( basePd.GetValue( row ) ); points.Add( pair ); nRow++; } } catch ( System.ArgumentOutOfRangeException ) { //A local datasource was set on this curve but it has fewer rows than the axis datasource. //So we stop feeding this curve. } //Create curve in pane with its points curveItem.CreateInPane( pane, points ); } } else { //Add curves and values set in designer ZeeGraphWebCurveItem curve; for ( int i = 0; i < CurveList.Count; i++ ) { curve = CurveList[i]; PointPairList points = new PointPairList(); PointPair pair = new PointPair(); for ( int j = 0; j < curve.Points.Count; j++ ) { curve.Points[j].CopyTo( pair ); points.Add( pair ); } curve.CreateInPane( pane, points ); } } //NOTE: ZeeGraphWeb.DataMember = base axis //NOTE: ZedGraphCurveItem.DataMember = Y //NOTE: Z values are only supported via the callback (???) //TODO: cache the data-map table before processing rows (???) }
private void chartPoint_MouseClick(object sender, MouseEventArgs e) { GraphPane pane = zedGraphControl1.GraphPane; double x; double y; pane.Legend.IsVisible = false; pane.ReverseTransform(e.Location, out x, out y); if (x != null && y != null) { LineItem pointLineItem = null; switch (_selectedEnum) { case MenuEnum.Points: { Points.Add(new Point() { X = x, Y = y }); //Set up points PointPairList pointPairList = new PointPairList(); pointPairList.Add(x, y); pointLineItem = new LineItem(null, pointPairList, _baseColor, SymbolType.Default, 3.0f); } break; case MenuEnum.Clusters: { Random random = new Random(); var point = new Point() { X = x, Y = y }; var cluster = new Cluster() { Id = Clusters.Count, ClusterPoint = point, Points = new List <Point>(), Color = Color.FromArgb(random.Next(256), random.Next(256), random.Next(256)) }; Clusters.Add(cluster); //Set up points PointPairList pointPairList = new PointPairList(); pointPairList.Add(x, y); pointLineItem = new LineItem(null, pointPairList, cluster.Color, SymbolType.Circle, 3.0f); } break; case MenuEnum.None: break; default: throw new ArgumentOutOfRangeException(); } if (pointLineItem != null) { pointLineItem.Line.IsVisible = false; pointLineItem.Symbol.Fill.Type = FillType.Solid; pane.CurveList.Add(pointLineItem); zedGraphControl1.Refresh(); } } if (Points.Count > 0) { GenerateClustersToolStripMenuItem.Enabled = true; } }
/// <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 ) { PieItem x = pane.AddPieSlice( this.Value, this.Color, this.Displacement, this.Label ); this.CopyTo( x ); return x; }
// Call this method from the Form_Load method, passing your ZedGraphControl instance private void CreateMultiYChart(ZedGraphControl zgc) { // Get a reference to the GraphPane GraphPane myPane = zgc.GraphPane; // Set the titles and axis labels myPane.Title.Text = "Demonstration of Multi Y Graph"; myPane.XAxis.Title.Text = "Time, s"; myPane.YAxis.Title.Text = "Velocity, m/s"; myPane.Y2Axis.Title.Text = "Acceleration, m/s2"; // Make up some data points based on the Sine function PointPairList vList = new PointPairList(); PointPairList aList = new PointPairList(); PointPairList dList = new PointPairList(); PointPairList eList = new PointPairList(); double[] x4 = { 0, 1, 2, 3, 4, 5, 6, 7 }; /* * // Fabricate some data values * for (int i = 0; i < 7; i++) * { * double time = (double)i; * double acceleration = 2.0; * double velocity = acceleration * time; * double distance = acceleration * time * time / 2.0; * double energy = 100.0 * velocity * velocity / 2.0; * aList.Add(time, acceleration); * } * * * for (int i = 0; i < 5; i++) * { * double time = x4[i]; * double acceleration = 2.0; * double velocity = 13.0 + 7.0 * acceleration * time; * double distance = 10.0 + 3.0 * acceleration * time * velocity; * double energy = 8.0 + 6.0 * velocity * velocity / 2.0; * vList.Add(x4[i], velocity); * eList.Add(x4[i], energy); * dList.Add(x4[i], distance); * } */ // Generate a red curve with diamond symbols, and "Velocity" in the legend LineItem myCurve = myPane.AddCurve("Velocity", // dList, Color.Red, SymbolType.Diamond); DEPValueList, Color.Red, SymbolType.Diamond); // Fill the symbols with white //myCurve.Symbol.Size = 4.0F; myCurve.Symbol.Fill = new Fill(Color.White); myCurve.Line.Width = 4.0F; // Generate a green curve with square symbols, and "Distance" in the legend myCurve = myPane.AddCurve("Distance", // vList, Color.Green, SymbolType.Square); ANXValueList, Color.Green, SymbolType.Square); // Fill the symbols with white //myCurve.Symbol.Size = 4.0F; myCurve.Symbol.Fill = new Fill(Color.White); // Associate this curve with the second Y axis myCurve.YAxisIndex = 1; myCurve.Line.Width = 4.0F; // Generate a Black curve with triangle symbols, and "Energy" in the legend myCurve = myPane.AddCurve("Energy", // eList, Color.Black, SymbolType.Triangle); HMAValueList, Color.Black, SymbolType.Triangle); // Fill the symbols with white //myCurve.Symbol.Size = 4.0F; myCurve.Symbol.Fill = new Fill(Color.White); // Associate this curve with the Y2 axis myCurve.IsY2Axis = false; // Associate this curve with the second Y2 axis myCurve.YAxisIndex = 1; myCurve.Line.Width = 4.0F; //double[] x4 = { 0, 1, 2, 3, 4, 5, 6, 7 }; // double[] x5 = { 10,11,12,13,14,15,16,17}; double[] y4 = { 30, 45, 53, 60, 45, 53, 24 }; // normalize(y4, 7); BarItem bar = myPane.AddBar("PHI", x4, y5, Color.SteelBlue); // Fill the bars with a RosyBrown-White-RosyBrown gradient bar.Bar.Border.Width = 0F; bar.Bar.Fill = new Fill(Color.LightBlue, Color.White, Color.LightBlue); //// Generate a blue curve with circle symbols, and "Acceleration" in the legend //myCurve = myPane.AddCurve("Acceleration", // aList, Color.Blue, SymbolType.Circle); //// Fill the symbols with white //myCurve.Symbol.Fill = new Fill(Color.White); //// Associate this curve with the Y2 axis //myCurve.IsY2Axis = true; // Show the x axis grid myPane.XAxis.MajorGrid.IsVisible = false; myPane.Border.IsVisible = false; myPane.XAxis.IsVisible = false; myPane.XAxis.Scale.Min = -1; myPane.XAxis.Scale.Max = 7; myPane.Legend.IsVisible = false;//legend:图例、说明 myPane.Title.IsVisible = false; // 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 = false; // Align the Y axis labels so they are flush to the axis myPane.YAxis.Scale.Align = AlignP.Inside; myPane.YAxis.Scale.Max = 1.5;//我把这里的100改成了1.5 myPane.YAxis.IsVisible = false; // Enable the Y2 axis display myPane.Y2Axis.IsVisible = false; // Make the Y2 axis scale blue myPane.Y2Axis.Scale.FontSpec.FontColor = Color.Blue; myPane.Y2Axis.Title.FontSpec.FontColor = Color.Blue; // turn off the opposite tics so the Y2 tics don't show up on the Y axis myPane.Y2Axis.MajorTic.IsOpposite = false; myPane.Y2Axis.MinorTic.IsOpposite = false; // Display the Y2 axis grid lines myPane.Y2Axis.MajorGrid.IsVisible = false; // Align the Y2 axis labels so they are flush to the axis myPane.Y2Axis.Scale.Align = AlignP.Inside; myPane.Y2Axis.Scale.Min = 0; //我把1.5改成了0 myPane.Y2Axis.Scale.Max = 1.5; //我把3改成了1.5 // Create a second Y Axis, green YAxis yAxis3 = new YAxis("Distance, m"); myPane.YAxisList.Add(yAxis3); yAxis3.IsVisible = false; yAxis3.Scale.FontSpec.FontColor = Color.Green; yAxis3.Title.FontSpec.FontColor = Color.Green; yAxis3.Color = Color.Green; // 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.MinorTic.IsOpposite = false; // Align the Y2 axis labels so they are flush to the axis yAxis3.Scale.Align = AlignP.Inside; Y2Axis yAxis4 = new Y2Axis("Energy"); yAxis4.IsVisible = false; myPane.Y2AxisList.Add(yAxis4); // 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.MinorTic.IsOpposite = false; // Align the Y2 axis labels so they are flush to the axis yAxis4.Scale.Align = AlignP.Inside; yAxis4.Type = AxisType.Log; yAxis4.Scale.Min = 1.5;//我把100改成1.5 // Fill the axis background with a gradient myPane.Chart.Fill = new Fill(Color.White, Color.LightGoldenrodYellow, 45.0f); zgc.AxisChange(); }
//Loads the file and initializes all settings with the information of the file private void Button_Load_Click(object sender, RoutedEventArgs e) { try { OpenFileDialog Dialogo2 = new OpenFileDialog(); if (Dialogo2.ShowDialog() == true) { BinaryFormatter Bf = new BinaryFormatter(); FileStream r = File.OpenRead(Dialogo2.FileName); Guardado bac = (Guardado)Bf.Deserialize(r); r.Close(); Mirror = bac.getMirror(); variables = bac.getVariables(); cellGrid = bac.getGrid(); Tiempo = bac.getTiempo(); //Plots tempValues = bac.getTemp(); phaseValues = bac.getPhase(); Charts.CreateGraph(tempgraph, tempValues, "Temperature"); Charts.CreateGraph(phasegraph, phaseValues, "Phase"); ColumnSlider.Value = cellGrid.getceldas()[0].Length - 2; RowsSlider.Value = cellGrid.getceldas().Length - 2; //Restarting Grid grid.Children.Clear(); grid.ColumnDefinitions.Clear(); grid.RowDefinitions.Clear(); grid2.Children.Clear(); grid2.ColumnDefinitions.Clear(); grid2.RowDefinitions.Clear(); //Adding Columns for (int j = 0; j < ColumnSlider.Value; j++) { grid.ColumnDefinitions.Add(new ColumnDefinition()); grid2.ColumnDefinitions.Add(new ColumnDefinition()); } //We convert the stack to list in order to serach for the first cells Celda[][][] temp = cellGrid.getMemory().ToArray(); //Adding Rows Rectangle[][] rectanglesTemp = new Rectangle[cellGrid.getceldas().Length][]; Rectangle[][] rectanglesPhase = new Rectangle[cellGrid.getceldas().Length][]; for (int i = 1; i < RowsSlider.Value + 1; i++) { Rectangle[] CellRowTemp = new Rectangle[cellGrid.getceldas()[0].Length]; Rectangle[] CellRowPhase = new Rectangle[cellGrid.getceldas()[0].Length]; grid.RowDefinitions.Add(new RowDefinition()); grid2.RowDefinitions.Add(new RowDefinition()); //This for loop prints the grid for (int j = 1; j < ColumnSlider.Value + 1; j++) { Rectangle rectangle = new Rectangle(); Rectangle rectangle2 = new Rectangle(); SolidColorBrush BlackBrush = new SolidColorBrush(); BlackBrush.Color = Colors.Black; rectangle.Stroke = BlackBrush; rectangle2.Stroke = BlackBrush; if (temp[temp.Length - 1][i][j].getPhase() == 0) { rectangle.StrokeThickness = 3; rectangle2.StrokeThickness = 3; } else { rectangle.StrokeThickness = 1; rectangle2.StrokeThickness = 1; } rectangle.Fill = new SolidColorBrush(Colors.White); rectangle2.Fill = new SolidColorBrush(Colors.White); //Here we add the rectangles inside the grid Grid.SetRow(rectangle, i - 1); Grid.SetColumn(rectangle, j - 1); grid.Children.Add(rectangle); Grid.SetRow(rectangle2, i - 1); Grid.SetColumn(rectangle2, j - 1); grid2.Children.Add(rectangle2); CellRowTemp[j] = rectangle; CellRowPhase[j] = rectangle2; } rectanglesTemp[i] = CellRowTemp; rectanglesPhase[i] = CellRowPhase; } cellGrid.loadFixRectangles(rectanglesTemp, rectanglesPhase); cellGrid.Represent(); //Style SetGrid.IsEnabled = false; DiscardGrid.IsEnabled = false; ColumnSlider.IsEnabled = false; RowsSlider.IsEnabled = false; button_Demonstration.IsEnabled = false; button_Play.IsEnabled = true; button_Pause.IsEnabled = true; button_Atrás.IsEnabled = true; button_Adelante.IsEnabled = true; button_Stop.IsEnabled = true; Combobox_Condition.IsEnabled = false; Combobox_Variables.IsEnabled = false; Custom_Variables.IsEnabled = false; button_Save.Visibility = Visibility.Visible; button_Load.Visibility = Visibility.Hidden; Confirm_Button.Content = "Reset Configuration"; HelpLabel.Content = ""; //Style Confirm_Button.Background = new SolidColorBrush(Color.FromArgb(255, 255, 110, 110)); //ZedGRaph tempgraph.AxisChange(); phasegraph.AxisChange(); tempgraph.Invalidate(); phasegraph.Invalidate(); //Simulation started Started = true; } } catch { MessageBox.Show("There was a problem loading"); } }
private void Graphit_Click(object sender, EventArgs e) { if (dataGridView1.RowCount == 0 || dataGridView1.ColumnCount == 0) { CustomMessageBox.Show("Please load a valid file"); return; } if (dataGridView1.CurrentCell == null) { CustomMessageBox.Show("Please select a cell first"); return; } int col = dataGridView1.CurrentCell.ColumnIndex; int row = dataGridView1.CurrentCell.RowIndex; string type = dataGridView1[1, row].Value.ToString(); double a = 0; // row counter if (col == 0) { CustomMessageBox.Show("Please pick another column, Highlight the cell you wish to graph"); return; } int error = 0; PointPairList list1 = new PointPairList(); string header = "Value"; foreach (DataGridViewRow datarow in dataGridView1.Rows) { if (datarow.Cells[1].Value.ToString() == type) { try { double value = double.Parse(datarow.Cells[col].Value.ToString(), new System.Globalization.CultureInfo("en-US")); header = dataGridView1.Columns[col].HeaderText; list1.Add(a, value); } catch { error++; log.Info("Bad Data : " + type + " " + col + " " + a); if (error >= 500) { CustomMessageBox.Show("There is to much bad data - failing"); break; } } } a++; } LineItem myCurve; myCurve = zg1.GraphPane.AddCurve(header, list1, colours[zg1.GraphPane.CurveList.Count % colours.Length], SymbolType.None); leftorrightaxis(sender, myCurve); // Make sure the Y axis is rescaled to accommodate actual data try { zg1.AxisChange(); } catch { } // Zoom all zg1.ZoomOutAll(zg1.GraphPane); try { DrawModes(); DrawTime(); } catch { } // Force a redraw zg1.Invalidate(); }
protected static CurveItem CreateLineItem(string label, PointPairList pointPairList, Color color) { return(new LineErrorBarItem(label, pointPairList, color, Color.Black)); }
public TrendLogDisplay(BacnetClient comm, BacnetAddress adr, BacnetObjectId object_id) { InitializeComponent(); ToolTip ToolTip1 = new ToolTip(); ToolTip1.SetToolTip(m_progressBar, "Click here to stop download"); m_zedGraphCtl.GraphPane.XAxis.Type = AxisType.Date; m_zedGraphCtl.GraphPane.XAxis.Title.Text = "Date/Time"; m_zedGraphCtl.GraphPane.YAxis.Title.Text = "Values"; m_zedGraphCtl.GraphPane.XAxis.MajorGrid.IsVisible = true; m_zedGraphCtl.GraphPane.YAxis.MajorGrid.IsVisible = true; m_zedGraphCtl.GraphPane.XAxis.MajorGrid.Color = Color.Gray; m_zedGraphCtl.GraphPane.YAxis.MajorGrid.Color = Color.Gray; m_zedGraphCtl.IsAntiAlias = true; // Zedgraph patch made to use the false IsAntiAlias default value for textRendering : // antiaslias is clean for curves but not for the text // to set antialias for fonts ZedGraph.FontSpec.Default.IsAntiAlias=true can be used Logsize = ReadRangeSize(comm, adr, object_id); if (Logsize < 0) { Logsize = 0; } m_progresslabel.Text = "Downloads of " + Logsize + " records in progress (0%)"; m_progressBar.Maximum = Logsize; m_zedGraphCtl.GraphPane.Title.Text = ReadCurveName(comm, adr, object_id); // get the number of Trend in the Log, 1 for basic TrendLog if (object_id.type == BacnetObjectTypes.OBJECT_TREND_LOG_MULTIPLE) { CurvesNumber = ReadNumberofCurves(comm, adr, object_id); } m_zedGraphCtl.ContextMenuBuilder += new ZedGraphControl.ContextMenuBuilderEventHandler(m_zedGraphCtl_ContextMenuBuilder); m_zedGraphCtl.PointValueEvent += new ZedGraphControl.PointValueHandler(m_zedGraphCtl_PointValueEvent); if ((Logsize != 0) && (CurvesNumber != 0)) { Pointslists = new PointPairList[CurvesNumber]; for (int i = 0; i < CurvesNumber; i++) { Pointslists[i] = new PointPairList(); } NbRecordsByStep = NbRecordsByStep - 5 * CurvesNumber; this.UseWaitCursor = true; // Start downloads in thread this.comm = comm; this.adr = adr; this.object_id = object_id; Thread th = new Thread(DownloadFullTrendLog); th.IsBackground = true; th.Start(); } else { m_progressBar.Visible = false; m_progresslabel.Text = "The trendlog is empty, nothing to display"; } m_list.Visible = false; // to avoid flicker during download }
/// <summary> /// Create stick graph of a single scan. /// </summary> private void CreateSingleScan() { GraphPane.YAxis.Title.Text = Resources.AbstractMSGraphItem_CustomizeYAxis_Intensity; graphControl.IsEnableVZoom = graphControl.IsEnableVPan = false; // Create a point list for each transition, and a default point list for points not // associated with a transition. var pointLists = new PointPairList[_msDataFileScanHelper.ScanProvider.Transitions.Length]; for (int i = 0; i < pointLists.Length; i++) { pointLists[i] = new PointPairList(); } var defaultPointList = new PointPairList(); var allPointList = new PointPairList(); // Assign each point to a transition point list, or else the default point list. IList <double> mzs; IList <double> intensities; bool negativeScan; var spectra = _msDataFileScanHelper.MsDataSpectra; if (spectra.Length == 1 && spectra[0].IonMobilities == null) { mzs = spectra[0].Mzs; intensities = spectra[0].Intensities; negativeScan = spectra[0].NegativeCharge; } else { // Ion mobility being shown as 2-D spectrum mzs = new List <double>(); intensities = new List <double>(); var fullScans = _msDataFileScanHelper.GetFilteredScans(); negativeScan = fullScans.Any() && fullScans.First().NegativeCharge; double minMz; var indices = new int[fullScans.Length]; while ((minMz = FindMinMz(fullScans, indices)) < double.MaxValue) { mzs.Add(minMz); intensities.Add(SumIntensities(fullScans, minMz, indices)); } } for (int i = 0; i < mzs.Count; i++) { double mz = mzs[i]; double intensity = intensities[i]; allPointList.Add(mz, intensity); var assignedPointList = defaultPointList; for (int j = 0; j < _msDataFileScanHelper.ScanProvider.Transitions.Length; j++) { var transition = _msDataFileScanHelper.ScanProvider.Transitions[j]; // Polarity should match, because these are the spectra used for extraction Assume.IsTrue(transition.PrecursorMz.IsNegative == negativeScan); if (transition.Source != _msDataFileScanHelper.Source || mz <= transition.ProductMz.Value - transition.ExtractionWidth / 2 || mz > transition.ProductMz.Value + transition.ExtractionWidth / 2) { continue; } assignedPointList = pointLists[j]; break; } assignedPointList.Add(mz, intensity); } // Create a graph item for each point list with its own color. for (int i = 0; i < pointLists.Length; i++) { var transition = _msDataFileScanHelper.ScanProvider.Transitions[i]; if (transition.Source != _msDataFileScanHelper.Source) { continue; } var item = new SpectrumItem(pointLists[i], transition.Color, 2); var curveItem = _graphHelper.GraphControl.AddGraphItem(GraphPane, item, false); curveItem.Label.IsVisible = false; } // Add points that aren't associated with a transition. { var item = new SpectrumItem(defaultPointList, Color.Gray); var curveItem = _graphHelper.GraphControl.AddGraphItem(GraphPane, item, false); curveItem.Label.IsVisible = false; } // Create curve for all points to provide shading behind stick graph. if (_msDataFileScanHelper.MsDataSpectra.Length > 0 && !_msDataFileScanHelper.MsDataSpectra[0].Centroided) { var item = new SpectrumShadeItem(allPointList, Color.FromArgb(100, 225, 225, 150)); var curveItem = _graphHelper.GraphControl.AddGraphItem(GraphPane, item, false); curveItem.Label.IsVisible = false; } GraphPane.SetScale(CreateGraphics()); }
public void addDataLine(PointPairList _pointPairList) { // Set how many line will take one line: int line_multiplier = settings.AverageWindow; /////////////////////////////////////////////////////////////////////////////// MyDataFile current_data = new MyDataFile(); for (int i = 0; i < _pointPairList.Count; i++) { current_data.data_set[i] = _pointPairList[i].X; } current_data.myDataSize = _pointPairList.Count; // Here it save data to file: // current_data.SaveAdd("test.test"); ////////////////////////////////////////////////////////////////////////////// // Clear extra-line: if (current_line_counter == 0) { for (int y = 0; y < _pointPairList.Count; y++) { spec_data[GeneratedDataWidth][y] = 0; } } // Add data-line to extra-line: if (current_line_counter < settings.AveragingLineWindow) { for (int y = 0; y < _pointPairList.Count; y++) { spec_data[GeneratedDataWidth][y] = spec_data[GeneratedDataWidth][y] + _pointPairList[y].X; } current_line_counter++; } if (current_line_counter >= settings.AveragingLineWindow) { current_line_counter = 0; for (int y = 0; y < _pointPairList.Count; y++) { spec_data[GeneratedDataWidth - 1][y] = (spec_data[GeneratedDataWidth][y] / (double)settings.AveragingLineWindow); } for (int x = 0; x < GeneratedDataWidth - line_multiplier; x++) { for (int y = 0; y < GeneratedDataHeightDepth; y++) { spec_data[x][y] = spec_data[x + line_multiplier][y]; } } for (int i = 0; i < (line_multiplier - 1); i++) { for (int y = 0; y < _pointPairList.Count; y++) { spec_data[GeneratedDataWidth - 2 - i][y] = spec_data[GeneratedDataWidth - 1][y]; } } // Update bitmap picture: Update_bitmap_with_data(); } }
private void getFragmentationStatistics() { IList <object[]> queryRows; lock (session) { var randomIds = session.CreateQuery("SELECT psm.Id " + viewFilter.GetFilteredQueryString(DataFilter.FromPeptideSpectrumMatch)) .List <long>() .Shuffle() .Take(1000) .OrderBy(o => o); string randomIdSet = String.Join(",", randomIds.Select(o => o.ToString()).ToArray()); queryRows = session.CreateQuery("SELECT psm.Spectrum.Source.Name, psm.Spectrum, psm, DISTINCT_GROUP_CONCAT(pm.Offset || ':' || mod.MonoMassDelta), psm.Peptide.Sequence " + "FROM PeptideSpectrumMatch psm " + "LEFT JOIN psm.Modifications pm " + "LEFT JOIN pm.Modification mod " + "WHERE psm.Id IN (" + randomIdSet + ") " + "GROUP BY psm.Spectrum.id ") .List <object[]>(); } var spectrumRows = queryRows.Select(o => new SpectrumRow(o)).OrderBy(o => o.SourceName); var percentTicBySpectrumByFragmentType = new List <PointPairList>(); var percentPeakCountBySpectrumByFragmentType = new List <PointPairList>(); var meanMzErrorBySpectrumByFragmentType = new List <PointPairList>(); var percentTicListByFragmentType = new List <List <double> >(); var percentPeakCountListByFragmentType = new List <List <double> >(); var meanMzErrorListByFragmentType = new List <List <double> >(); foreach (var graphControl in graphControls) { graphControl.MasterPane.PaneList.ForEach(o => o.CurveList.ForEach(c => c.Clear())); } for (int i = 0; i < (int)IonSeries.Count; ++i) { percentTicBySpectrumByFragmentType.Add(percentTicGraphControl.MasterPane.PaneList[i + 1].CurveList[3].Points as PointPairList); percentPeakCountBySpectrumByFragmentType.Add(percentPeakCountGraphControl.MasterPane.PaneList[i + 1].CurveList[3].Points as PointPairList); meanMzErrorBySpectrumByFragmentType.Add(meanMzErrorGraphControl.MasterPane.PaneList[i + 1].CurveList[3].Points as PointPairList); percentTicListByFragmentType.Add(new List <double>()); percentPeakCountListByFragmentType.Add(new List <double>()); meanMzErrorListByFragmentType.Add(new List <double>()); } int spectraCount = 0; maxPercentTic = 10; maxPercentPeakCount = 10; maxMeanMzError = 0.1; var tolerance = fragmentTolerance; string spectrumListFilters = String.Empty; Invoke(new MethodInvoker(() => { tolerance.value = Convert.ToDouble(fragmentToleranceTextBox.Text); tolerance.units = (MZTolerance.Units)fragmentToleranceUnitsComboBox.SelectedIndex; meanMzErrorGraphControl.GraphPane.YAxis.Title.Text = "Mean m/z error (" + tolerance.units.ToString() + ")"; spectrumListFilters = spectrumFiltersTextBox.Text; setAutomaticScales(); })); var points = new PointPairList(); string currentSourceName = null; string currentSourcePath = null; msdata.MSData msd = null; lock (owner) foreach (var row in spectrumRows) { if (row.SourceName != currentSourceName) { currentSourceName = row.SourceName; currentSourcePath = IDPickerForm.LocateSpectrumSource(currentSourceName, session.Connection.GetDataSource()); if (String.IsNullOrEmpty(currentSourcePath)) { throw new FileNotFoundException("source file not found"); } msd = new pwiz.CLI.msdata.MSDataFile(currentSourcePath); //var param = session.Query<AnalysisParameter>().Where(o => o.Name == "SpectrumListFilters").Min(o => o.Value); //string spectrumListFilters = String.IsNullOrEmpty(param) ? String.Empty : param; SpectrumListFactory.wrap(msd, spectrumListFilters.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)); } string spectrumId = String.Format("{0}/{1}", row.SourceName, msdata.id.abbreviate(row.Spectrum.NativeID)); var spectrumList = msd.run.spectrumList; ++spectraCount; var pwizPeptide = new proteome.Peptide(row.ModifiedSequence, proteome.ModificationParsing.ModificationParsing_Auto, proteome.ModificationDelimiter.ModificationDelimiter_Brackets); var fragmentation = pwizPeptide.fragmentation(true, true); var pwizSpectrum = spectrumList.spectrum(spectrumList.find(row.Spectrum.NativeID), true); var pointMap = new seems.PointMap(new ZedGraph.PointPairList(pwizSpectrum.getMZArray().data, pwizSpectrum.getIntensityArray().data)); double tic = pointMap.Values.Sum(); var percentTicByFragmentType = new List <double>(Enumerable.Repeat(0.0, (int)IonSeries.Count)); var percentPeakCountByFragmentType = new List <double>(Enumerable.Repeat(0.0, (int)IonSeries.Count)); var matchCountByFragmentType = new List <int>(Enumerable.Repeat(0, (int)IonSeries.Count)); var meanMzErrorByFragmentType = new List <double>(Enumerable.Repeat(Double.NaN, (int)IonSeries.Count)); seems.PointMap.Enumerator itr; double expected; IonSeries[] ionSeries = Enum.GetValues(typeof(IonSeries)).Cast <IonSeries>().Where(o => o != IonSeries.Count).ToArray(); for (int z = 1; z <= 1; ++z) { for (int length = 1, end = pwizPeptide.sequence.Length; length <= end; ++length) { foreach (IonSeries series in ionSeries) { if ((series == IonSeries.c || series == IonSeries.x) && length == pwizPeptide.sequence.Length) { continue; } expected = fragmentMass(fragmentation, series, length, z); itr = pointMap.FindNear(expected, expected - (expected - tolerance)); if (itr != null && itr.IsValid) { percentTicByFragmentType[(int)series] += itr.Current.Value; ++percentPeakCountByFragmentType[(int)series]; ++matchCountByFragmentType[(int)series]; if (Double.IsNaN(meanMzErrorByFragmentType[(int)series])) { meanMzErrorByFragmentType[(int)series] = 0; } meanMzErrorByFragmentType[(int)series] += mzError(itr.Current.Key, expected); } } } } var rng = new Random(); for (int i = 0; i < percentTicBySpectrumByFragmentType.Count; ++i) { // convert sum to mean if (percentPeakCountByFragmentType[i] > 0) { meanMzErrorByFragmentType[i] /= matchCountByFragmentType[i]; } // convert to percentages percentTicByFragmentType[i] /= tic / 100; percentPeakCountByFragmentType[i] /= pointMap.Count / 100.0; maxPercentTic = Math.Max(maxPercentTic, percentTicByFragmentType[i]); maxPercentPeakCount = Math.Max(maxPercentPeakCount, percentPeakCountByFragmentType[i]); double jitter = (rng.NextDouble() - 0.5); percentTicBySpectrumByFragmentType[i].Add(jitter, percentTicByFragmentType[i], String.Format("{0}: {1:G4}% ({2} matches)", spectrumId, percentTicByFragmentType[i], matchCountByFragmentType[i])); percentPeakCountBySpectrumByFragmentType[i].Add(jitter, percentPeakCountByFragmentType[i], String.Format("{0}: {1:G4}% ({2} matches)", spectrumId, percentPeakCountByFragmentType[i], matchCountByFragmentType[i])); percentTicListByFragmentType[i].Add(percentTicByFragmentType[i]); percentPeakCountListByFragmentType[i].Add(percentPeakCountByFragmentType[i]); if (!Double.IsNaN(meanMzErrorByFragmentType[i])) { maxMeanMzError = Math.Max(maxMeanMzError, Math.Abs(meanMzErrorByFragmentType[i])); meanMzErrorBySpectrumByFragmentType[i].Add(jitter, meanMzErrorByFragmentType[i], String.Format("{0}: {1:G4}%", spectrumId, meanMzErrorByFragmentType[i])); meanMzErrorListByFragmentType[i].Add(meanMzErrorByFragmentType[i]); } } if ((spectraCount % 100) == 0) { setAutomaticScales(); } }// for each spectrum row Invoke(new MethodInvoker(() => { for (int i = 0; i < percentTicBySpectrumByFragmentType.Count; ++i) { if (percentTicListByFragmentType[i].Count < 5) { continue; } percentTicListByFragmentType[i].Sort(); percentPeakCountListByFragmentType[i].Sort(); addSixNumberSummary(percentTicGraphControl.MasterPane.PaneList[i + 1], percentTicListByFragmentType[i]); addSixNumberSummary(percentPeakCountGraphControl.MasterPane.PaneList[i + 1], percentPeakCountListByFragmentType[i]); if (meanMzErrorListByFragmentType[i].Count < 5) { continue; } meanMzErrorListByFragmentType[i].Sort(); addSixNumberSummary(meanMzErrorGraphControl.MasterPane.PaneList[i + 1], meanMzErrorListByFragmentType[i]); } })); }
private void fillChart() { //DataSet ds = new DataSet(); //ds.Tables[0].Rows[0][0]; //chart1.Series["Series1"].LegendText = "График XY"; NewOverallStats main = this.Owner as NewOverallStats; //Шняга для передачи данных между формами. Но нужно соответсвующуе элементы пабликами делать int machid = main.radDropDownList1.SelectedItem.Index; int measure = main.radDropDownList2.SelectedItem.Index; Machine dummy = Program.machineList[machid]; List <string> DataToDraw = new List <string>(); switch (measure) { case 0: DataToDraw = dummy.getTempLog(); break; case 1: DataToDraw = dummy.getVibrLog(); break; case 2: DataToDraw = dummy.getPowerLog(); break; case 3: DataToDraw = dummy.getLoadLog(); break; case 4: DataToDraw = dummy.getWorkTimeLog(); break; } GraphPane pane = zedGraphControl1.GraphPane; pane.CurveList.Clear(); //DateTime minDate = main.radDateTimePicker1.Value; //DateTime maxDate = main.radDateTimePicker2.Value; PointPairList list = new PointPairList(); //double[] xvalues = new double[DataToDraw.Count]; //double[] yvalues = new double[DataToDraw.Count]; for (int i = 0; i < DataToDraw.Count; i++) { string[] couple = DataToDraw[i].Split('\t'); string[] parsedDT = couple[0].Split(' '); string[] parsedD = parsedDT[0].Split('.'); string[] parsedT = parsedDT[1].Split(':'); XDate dt = new XDate(Convert.ToInt32(parsedD[2]), Convert.ToInt32(parsedD[1]), Convert.ToInt32(parsedD[0]), Convert.ToInt32(parsedT[0]), Convert.ToInt32(parsedT[1]), Convert.ToInt32(parsedT[2])); list.Add(dt, float.Parse(couple[1])); /* * if (i == 0) minDate = dt; * if (i == DataToDraw.Count - 1) maxDate = dt; */ //s.Points.AddXY(dt, float.Parse(couple[1])); } LineItem myCurve = pane.AddCurve(main.radDropDownList2.SelectedItem.Text + " машины " + (machid + 1).ToString(), list, Color.Blue, SymbolType.None); pane.XAxis.Type = AxisType.Date; pane.XAxis.Scale.Format = "dd.MM.yyyy HH:mm:ss"; pane.XAxis.Scale.Min = main.radDateTimePicker1.Value.ToOADate(); pane.XAxis.Scale.Max = main.radDateTimePicker2.Value.ToOADate(); pane.XAxis.Title.Text = "Время"; pane.YAxis.Title.Text = main.radDropDownList2.SelectedItem.Text; zedGraphControl1.AxisChange(); zedGraphControl1.Invalidate(); /* * chart1.Series.Clear(); * chart1.Series.Add(s); * * chart1.Series[0].XValueType = ChartValueType.DateTime; * chart1.ChartAreas[0].AxisX.LabelStyle.Format = "dd.mm.yyyy hh:mm:ss"; * chart1.ChartAreas[0].AxisX.Interval = 15; * chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Minutes; * //chart1.ChartAreas[0].AxisX.IntervalOffset = Auto; * chart1.ChartAreas[0].AxisX.Minimum = minDate.ToOADate(); * chart1.ChartAreas[0].AxisX.Maximum = maxDate.ToOADate(); */ }
public void CreateBarGraph(ZedGraphControl zgc, double[] discriminants) { GraphPane myPane = zgc.GraphPane; myPane.CurveList.Clear(); myPane.Title.IsVisible = false; myPane.Legend.IsVisible = false; myPane.Border.IsVisible = false; myPane.Border.IsVisible = false; myPane.Margin.Bottom = 20f; myPane.Margin.Right = 20f; myPane.Margin.Left = 20f; myPane.Margin.Top = 30f; myPane.YAxis.Title.IsVisible = true; myPane.YAxis.IsVisible = true; myPane.YAxis.MinorGrid.IsVisible = false; myPane.YAxis.MajorGrid.IsVisible = false; myPane.YAxis.IsAxisSegmentVisible = false; myPane.YAxis.Scale.Max = 9.5; myPane.YAxis.Scale.Min = -0.5; myPane.YAxis.MajorGrid.IsZeroLine = false; myPane.YAxis.Title.Text = "Classes"; myPane.YAxis.MinorTic.IsOpposite = false; myPane.YAxis.MajorTic.IsOpposite = false; myPane.YAxis.MinorTic.IsInside = false; myPane.YAxis.MajorTic.IsInside = false; myPane.YAxis.MinorTic.IsOutside = false; myPane.YAxis.MajorTic.IsOutside = false; myPane.XAxis.MinorTic.IsOpposite = false; myPane.XAxis.MajorTic.IsOpposite = false; myPane.XAxis.Title.IsVisible = true; myPane.XAxis.Title.Text = "Relative class response"; myPane.XAxis.IsVisible = true; myPane.XAxis.Scale.Min = 0; myPane.XAxis.Scale.Max = 100; myPane.XAxis.IsAxisSegmentVisible = false; myPane.XAxis.MajorGrid.IsVisible = false; myPane.XAxis.MajorGrid.IsZeroLine = false; myPane.XAxis.MinorTic.IsOpposite = false; myPane.XAxis.MinorTic.IsInside = false; myPane.XAxis.MinorTic.IsOutside = false; myPane.XAxis.Scale.Format = "0'%"; // Create data points for three BarItems using Random data PointPairList list = new PointPairList(); for (int i = 0; i < discriminants.Length; i++) { list.Add(discriminants[i] * 100, i); } BarItem myCurve = myPane.AddBar("b", list, Color.DarkBlue); // Set BarBase to the YAxis for horizontal bars myPane.BarSettings.Base = BarBase.Y; zgc.AxisChange(); zgc.Invalidate(); }
public void drawFunction(ZedGraphControl zgControl, ref FElem elem, Color lineColor, BackgroundWorker worker) { var pane = zgControl.GraphPane; var w = zgControl.Width; var h = zgControl.Height; PointPairList ppList = new PointPairList(); var step = (elem.xRight - elem.xLeft) / w; var yLeft = elem.function(elem.xLeft); var yRight = elem.function(elem.xRight); elem.yMin = yLeft > yRight ? yRight : yLeft; elem.yMax = yLeft > yRight ? yLeft : yRight; for (double i = elem.xLeft; i < elem.xRight; i += step) { var progress = (int)((i - elem.xLeft) / (elem.xRight - elem.xLeft) * 100); worker.ReportProgress(progress); if (worker.CancellationPending) { return; } var curY = elem.function(i); if (curY < elem.yMin) { elem.yMin = curY; } if (curY > elem.yMax) { elem.yMax = curY; } ppList.Add(new PointPair(i, curY)); } var curve = pane.AddCurve("", ppList, lineColor, ZedGraph.SymbolType.None); curve.Line.Width = 4.0f; var rX = elem.xRight - elem.xLeft; var rY = elem.yMax - elem.yMin; elem.xMin = elem.xLeft; elem.xMax = elem.xRight; pane.XAxis.Min = elem.xMin - rX * 0.1; pane.XAxis.Max = elem.xMax + rX * 0.1; pane.YAxis.Min = elem.yMin - rY * 0.1; pane.YAxis.Max = elem.yMax + rY * 0.1; //var line = new PointPairList(); //line.Add(new PointPair(elem.xMin, 2 * elem.yMin - elem.yMax)); //line.Add(new PointPair(elem.xMin, 2 * elem.yMax - elem.yMin)); //curve = pane.AddCurve("", line, Color.FromArgb(((int)(((byte)(253)))), ((int)(((byte)(239)))), ((int)(((byte)(249))))), ZedGraph.SymbolType.None); //curve.Line.Style = System.Drawing.Drawing2D.DashStyle.Dash; //curve.Line.Width = 0.01f; // //line.Clear(); //line.Add(new PointPair(elem.xMax, 2 * elem.yMin - elem.yMax)); //line.Add(new PointPair(elem.xMax, 2 * elem.yMax - elem.yMin)); //curve = pane.AddCurve("", line, Color.FromArgb(((int)(((byte)(253)))), ((int)(((byte)(239)))), ((int)(((byte)(249))))), ZedGraph.SymbolType.None); //curve.Line.Style = System.Drawing.Drawing2D.DashStyle.Dash; //curve.Line.Width = 0.01f; zgControl.AxisChange(); zgControl.Invalidate(); }
private bool zedGraphControl_MouseDownEvent(ZedGraphControl sender, MouseEventArgs e) { if (ReadonlyCurve) { return(false); } CurveItem curve; int dragPointIndex; // if CTRL is pressed, and we're not near a specific point, add a new point double newX, newY; if (Control.ModifierKeys.HasFlag(Keys.Control) && !zedGraphControl.GraphPane.FindNearestPoint(e.Location, out curve, out dragPointIndex)) { // only add if we've actually clicked on the pane, so make sure the mouse is over it first if (zedGraphControl.MasterPane.FindPane(e.Location) != null) { PointPairList pointList = zedGraphControl.GraphPane.CurveList[0].Points as PointPairList; zedGraphControl.GraphPane.ReverseTransform(e.Location, out newX, out newY); //Verify the point is in the usable bounds. if (newX > 100) { newX = 100; } else if (newX < 0) { newX = 0; } if (newY > 100) { newY = 100; } else if (newY < 0) { newY = 0; } pointList.Insert(0, newX, newY); pointList.Sort(); zedGraphControl.Invalidate(); } } // if the ALT key was pressed, and we're near a point, delete it -- but only if there would be at least two points left if (Control.ModifierKeys.HasFlag(Keys.Alt) && zedGraphControl.GraphPane.FindNearestPoint(e.Location, out curve, out dragPointIndex)) { PointPairList pointList = zedGraphControl.GraphPane.CurveList[0].Points as PointPairList; if (pointList.Count > 2) { pointList.RemoveAt(dragPointIndex); pointList.Sort(); zedGraphControl.Invalidate(); } } zedGraphControl.GraphPane.ReverseTransform(e.Location, out newX, out newY); _previousCurveYLocation = newY; if (!Curve.IsLibraryReference && e.Button == MouseButtons.Left && sender.DragEditingPair != null && !ModifierKeys.HasFlag(Keys.Shift)) { txtXValue.Text = sender.DragEditingPair.X.ToString("0.####"); txtYValue.Text = sender.DragEditingPair.Y.ToString("0.####"); txtXValue.Enabled = txtYValue.Enabled = btnUpdateCoordinates.Enabled = true; } return(false); }
public CurverIni(TabItem tabitem, ZedGraphControl zed) { _ppListOriginal = new PointPairList(); InitZed(zed, tabitem); tabitem.AttachedControl.Controls.Add(zed); }
public void Visualize( AlgoConfig algoConfig ) { _algoConfig = algoConfig; algoConfig.SortingAlgorithm.ItemsCompared += SortingAlgorithm_ItemsCompared; algoConfig.SortingAlgorithm.ItemsSwaped += SortingAlgorythm_ItemsSwaped; algoConfig.SortingAlgorithm.ItemCopied += SortingAlgorythm_ItemCopied; algoConfig.SortingAlgorithm.Finished += SortingAlgorithm_Finished; // Update the Ui this.Parent.Text = algoConfig.SortingAlgorithm.Name; this.HowItWorksTextBox.Text = algoConfig.SortingAlgorithm.HowItWorks; this.LabelN.Text = string.Format( "{0}", algoConfig.Array.Length ); // Show the initial array _values = algoConfig.Array; _compares = 0; _swaps = 0; _copies = 0; LabelCompares.Text = string.Empty; LabelSwaps.Text = string.Empty; LabelCopies.Text = string.Empty; LabelBigO.Text = string.Empty; LabelTotalOperations.Text = string.Empty; _isPause = false; _autoBlockAfterOneOperation = false; _manualResetEvent.Set(); if( _task != null ) { _task.Abort(); } this.BarChart.GraphPane.CurveList.Clear(); this.BarChart.GraphPane.GraphObjList.Clear(); PointPairList list = new PointPairList(); Random rand = new Random(); for( int i = 0; i < _values.Length; i++ ) { list.Add( i, _values[ i ], 0 ); } BarItem myCurve = this.BarChart.GraphPane.AddBar( string.Empty, list, Color.Black ); // 0 1 2 3 4 myCurve.Bar.Fill = new Fill( new Color[] { Color.Black, Color.Red, Color.Yellow, Color.Blue } );// , Color.Green myCurve.Bar.Fill.Type = FillType.GradientByZ; myCurve.Bar.Fill.RangeMin = 0; myCurve.Bar.Fill.RangeMax = 3; this.BarChart.GraphPane.AxisChange(); this.BarChart.Refresh(); // Start sorting _task = new Thread( () => algoConfig.SortingAlgorithm.Sort( algoConfig.Array ) ); _task.Start(); }
private void InitCurver(ZedGraphControl zed) { _ppListOriginal = new PointPairList(); zed.MasterPane.PaneList[0].AddCurve("原始数据", _ppListOriginal, Color.Red, SymbolType.None); }
private void InitializeTrackingGeneratorGraph() { #if CALLSTACK Console.WriteLine("CALLSTACK:InitializeTrackingGeneratorGraph"); #endif m_GraphTrackingGenerator.IsAutoScrollRange = true; m_GraphTrackingGenerator.EditButtons = System.Windows.Forms.MouseButtons.Left; m_GraphTrackingGenerator.IsAntiAlias = true; m_GraphTrackingGenerator.IsEnableSelection = true; m_GraphTrackingGenerator.Location = new System.Drawing.Point(8, 257); m_GraphTrackingGenerator.Name = "zedTracking"; m_GraphTrackingGenerator.PanModifierKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.None))); m_GraphTrackingGenerator.ScrollGrace = 0D; m_GraphTrackingGenerator.ScrollMaxX = 0D; m_GraphTrackingGenerator.ScrollMaxY = 0D; m_GraphTrackingGenerator.ScrollMaxY2 = 0D; m_GraphTrackingGenerator.ScrollMinX = 0D; m_GraphTrackingGenerator.ScrollMinY = 0D; m_GraphTrackingGenerator.ScrollMinY2 = 0D; m_GraphTrackingGenerator.Size = new System.Drawing.Size(123, 54); m_GraphTrackingGenerator.TabIndex = 49; m_GraphTrackingGenerator.TabStop = false; m_GraphTrackingGenerator.UseExtendedPrintDialog = true; m_GraphTrackingGenerator.Visible = true; m_GraphTrackingGenerator.ContextMenuBuilder += new ZedGraph.ZedGraphControl.ContextMenuBuilderEventHandler(this.objGraph_ContextMenuBuilder); //m_graphTrackingGenerator.ZoomEvent += new ZedGraph.ZedGraphControl.ZoomEventHandler(this.zedSpectrumAnalyzer_ZoomEvent); // Get a reference to the GraphPane instance in the ZedGraphControl GraphPane myPane = m_GraphTrackingGenerator.GraphPane; myPane.Fill = new Fill(Color.White, Color.LightBlue, 90.0f); myPane.Chart.Fill = new Fill(Color.White, Color.LightBlue, 90.0f); m_PointList_Tracking_Normal = new PointPairList(); m_GraphLine_Tracking_Normal = m_GraphTrackingGenerator.GraphPane.AddCurve("Realtime", m_PointList_Tracking_Normal, Color.Blue, SymbolType.None); m_GraphLine_Tracking_Normal.Line.Width = 1; m_GraphLine_Tracking_Normal.Line.SmoothTension = 0.2F; m_PointList_Tracking_Avg = new PointPairList(); m_GraphLine_Tracking_Avg = m_GraphTrackingGenerator.GraphPane.AddCurve("Average", m_PointList_Tracking_Avg, Color.DarkRed, SymbolType.None); m_GraphLine_Tracking_Avg.Line.Width = 4; m_GraphLine_Tracking_Avg.Line.SmoothTension = 0.3F; foreach (CurveItem objCurve in myPane.CurveList) { objCurve.IsVisible = false; objCurve.Label.IsVisible = false; } // Set the titles and axis labels //myPane.Title.FontSpec.Size = 10; myPane.XAxis.Title.IsVisible = true; myPane.XAxis.Title.Text = "Frequency (MHZ)"; myPane.XAxis.Scale.MajorStepAuto = true; myPane.XAxis.Scale.MinorStepAuto = true; myPane.XAxis.Type = AxisType.Linear; myPane.Margin.Left = 20; myPane.Margin.Right = -5; m_GraphTrackingGenerator.IsShowPointValues = true; // Show the x axis grid myPane.XAxis.MajorGrid.IsVisible = true; myPane.XAxis.Type = AxisType.Linear; myPane.YAxis.Title.IsVisible = true; // 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; 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; myPane.YAxis.Title.Text = "Insertion Loss (dB)"; myPane.Title.Text = _RFEGEN_TRACKING_TITLE; m_GraphTrackingGenerator.IsShowPointValues = true; m_GraphTrackingGenerator.PointValueEvent += new ZedGraphControl.PointValueHandler(GraphPointValueHandler); m_StatusGraphText_Tracking = new TextObj("Signal Generator DISCONNECTED", 0.01, 0.02, CoordType.ChartFraction); m_StatusGraphText_Tracking.IsClippedToChartRect = true; m_StatusGraphText_Tracking.FontSpec.FontColor = Color.DarkGray; m_StatusGraphText_Tracking.Location.AlignH = AlignH.Left; m_StatusGraphText_Tracking.Location.AlignV = AlignV.Top; m_StatusGraphText_Tracking.FontSpec.IsBold = false; m_StatusGraphText_Tracking.FontSpec.Size = 10f; m_StatusGraphText_Tracking.FontSpec.Border.IsVisible = false; m_StatusGraphText_Tracking.FontSpec.Fill.IsVisible = false; m_StatusGraphText_Tracking.FontSpec.StringAlignment = StringAlignment.Near; m_StatusGraphText_Tracking.FontSpec.IsDropShadow = true; m_StatusGraphText_Tracking.FontSpec.DropShadowOffset = 0.1f; m_StatusGraphText_Tracking.FontSpec.DropShadowColor = Color.LightBlue; m_StatusGraphText_Tracking.FontSpec.Family = "Tahoma"; myPane.GraphObjList.Add(m_StatusGraphText_Tracking); m_TrackingStatus = new TextObj("Tracking Normalization in Progress, \nplease wait...", 0.5, 0.5, CoordType.ChartFraction); m_TrackingStatus.Location.AlignH = AlignH.Center; m_TrackingStatus.Location.AlignV = AlignV.Center; m_TrackingStatus.FontSpec.Size = 20; m_TrackingStatus.FontSpec.FontColor = Color.DarkRed; m_TrackingStatus.FontSpec.IsDropShadow = true; m_TrackingStatus.FontSpec.DropShadowOffset = 0.05f; m_TrackingStatus.IsVisible = false; myPane.GraphObjList.Add(m_TrackingStatus); m_TrackingProgressText = new TextObj("Tracking step: 0/0 0%", 0.01, 0.08, CoordType.ChartFraction); m_TrackingProgressText.IsClippedToChartRect = true; m_TrackingProgressText.FontSpec.FontColor = Color.DarkBlue; m_TrackingProgressText.Location.AlignH = AlignH.Left; m_TrackingProgressText.Location.AlignV = AlignV.Top; m_TrackingProgressText.FontSpec.IsBold = false; m_TrackingProgressText.FontSpec.Size = 8f; m_TrackingProgressText.FontSpec.Border.IsVisible = false; m_TrackingProgressText.FontSpec.Fill.IsVisible = false; m_TrackingProgressText.FontSpec.StringAlignment = StringAlignment.Near; m_TrackingProgressText.FontSpec.IsDropShadow = true; m_TrackingProgressText.FontSpec.DropShadowColor = Color.LightBlue; m_TrackingProgressText.FontSpec.DropShadowOffset = 0.1f; m_TrackingProgressText.FontSpec.Family = "Tahoma"; m_TrackingProgressText.IsVisible = false; myPane.GraphObjList.Add(m_TrackingProgressText); //DefineGraphColors(); this.m_tabRFGen.ResumeLayout(false); this.m_tabRFGen.PerformLayout(); m_comboRFGenPowerCW.SelectedIndex = 0; }
private void plotGraph() { GraphPane altitudePane = zedGraphControlAltitude.GraphPane; GraphPane heartRatePane = zedGraphControlHeart.GraphPane; GraphPane cadencePane = zedGraphControlCadence.GraphPane; GraphPane powerPane = zedGraphControlPower.GraphPane; GraphPane speedPane = zedGraphControlSpeed.GraphPane; // Set the Titles speedPane.Title = "Overview"; speedPane.XAxis.Title = "Time in second"; speedPane.YAxis.Title = "Speed"; heartRatePane.Title = "Overview"; heartRatePane.XAxis.Title = "Time in second"; heartRatePane.YAxis.Title = "Heart Rate"; cadencePane.Title = "Overview"; cadencePane.XAxis.Title = "Time in second"; cadencePane.YAxis.Title = "Cadence"; powerPane.Title = "Overview"; powerPane.XAxis.Title = "Time in second"; powerPane.YAxis.Title = "Power"; altitudePane.Title = "Overview"; altitudePane.XAxis.Title = "Time in second"; altitudePane.YAxis.Title = "Altitude"; PointPairList cadencePairList = new PointPairList(); PointPairList altitudePairList = new PointPairList(); PointPairList heartPairList = new PointPairList(); PointPairList powerPairList = new PointPairList(); PointPairList speedPairList = new PointPairList(); for (int i = 0; i < _hrData["Cadence"].Count; i++) { cadencePairList.Add(i, Convert.ToInt16(_hrData["Cadence"][i])); } for (int i = 0; i < _hrData["Altitude"].Count; i++) { altitudePairList.Add(i, Convert.ToInt16(_hrData["Altitude"][i])); } for (int i = 0; i < _hrData["HeartRate"].Count; i++) { heartPairList.Add(i, Convert.ToInt16(_hrData["HeartRate"][i])); } for (int i = 0; i < _hrData["Watt"].Count; i++) { powerPairList.Add(i, Convert.ToInt16(_hrData["Watt"][i])); } for (int i = 0; i < _hrData["Speed"].Count; i++) { speedPairList.Add(i, Convert.ToDouble(_hrData["Speed"][i])); } LineItem cadence = cadencePane.AddCurve("Cadence", cadencePairList, Color.Red, SymbolType.None); LineItem altitude = altitudePane.AddCurve("Altitude", altitudePairList, Color.Blue, SymbolType.None); LineItem heart = heartRatePane.AddCurve("Heart", heartPairList, Color.Black, SymbolType.None); LineItem power = powerPane.AddCurve("Power", powerPairList, Color.Orange, SymbolType.None); LineItem speed = speedPane.AddCurve("Speed", speedPairList, Color.Blue, SymbolType.None); zedGraphControlAltitude.AxisChange(); zedGraphControlHeart.AxisChange(); zedGraphControlPower.AxisChange(); zedGraphControlCadence.AxisChange(); zedGraphControlSpeed.AxisChange(); }
/// <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 abstract CurveItem CreateInPane( GraphPane pane, PointPairList points );
public void ApplyWatershed() { var image = GetBitmap().ToImage <Bgr, byte>(); var bg = GetClone(); bg.GradeTrans(254); var msk = bg.GetClone(); msk.ApplyNegative(); bg.Erosion(3, 3); var bgImage = bg.GetBitmap().ToImage <Bgr, byte>().Convert <Gray, byte>(); bgImage.ToBitmap().Save("1-bgImage.jpg"); //Search for ~local minimums var localMinimums = GetClone(); localMinimums.MarkLocalMinimums(); localMinimums.Dilatation(3, 3); localMinimums.ApplyMask(msk); var minimums = localMinimums.GetBitmap().ToImage <Bgr, byte>().Convert <Gray, byte>(); minimums.ToBitmap().Save("2-minimums.jpg"); //Markers CvInvoke.ConnectedComponents(minimums, minimums); minimums.ToBitmap().Save("3-minimums.jpg"); var output = minimums.Convert <Gray, int>(); output.ToBitmap().Save("4-output.jpg"); var max = int.MinValue; for (var i = 0; i < image.Height; i++) { for (var j = 0; j < image.Width; j++) { max = Math.Max(output.Data[i, j, 0] + 1, max); } } for (var i = 0; i < image.Height; i++) { for (var j = 0; j < image.Width; j++) { if (bgImage.Data[i, j, 0] == 255) { output.Data[i, j, 0] = max; } } } output.ToBitmap().Save("5-output.jpg"); //Do watershed CvInvoke.Watershed(image, output); //Load image var newData = new List <PointPairList>(); var height = output.Data.GetLength(0); var width = output.Data.GetLength(1); for (var i = 0; i < height; i++) { var ppl = new PointPairList(); for (var j = 0; j < width; j++) { var color = output.Data[i, j, 0]; ppl.Add(0, (color == max || color == 0) ? -1 : output.Data[i, j, 0]); } newData.Add(ppl); } Data = newData; }
/// <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 ) { BarItem x = pane.AddBar( this.Label, points, this.Color ); this.CopyTo( x ); return x; }
private async void populateGraphControl() { // Get a reference to the GraphPane instance in the ZedGraphControl GraphPane myPane = zg1.GraphPane; if (stockDataGridView.SelectedRows.Count <= 0) { zg1.GraphPane.CurveList.Clear(); zg1.GraphPane.GraphObjList.Clear(); // Set the titles and axis labels myPane.Title.Text = "Historical Graph "; myPane.XAxis.Title.Text = "Time, Days"; myPane.YAxis.Title.Text = "Daily Close Value"; myPane.XAxis.MajorGrid.IsVisible = false; // Fill the axis background with a gradient myPane.Chart.Fill = new Fill(Color.LightYellow, Color.DeepSkyBlue, 45.0f); myPane.Fill = new Fill(Color.LightGreen); // Enable scrollbars if needed zg1.IsShowHScrollBar = true; zg1.IsShowVScrollBar = true; zg1.IsAutoScrollRange = true; zg1.IsScrollY2 = true; // OPTIONAL: Show tooltips when the mouse hovers over a point zg1.IsShowPointValues = true; // Tell ZedGraph to calculate the axis ranges // Note that you MUST call this after enabling IsAutoScrollRange, since AxisChange() sets // up the proper scrolling parameters zg1.AxisChange(); // Make sure the Graph gets redrawn zg1.Invalidate(); return; } String name = stockDataGridView.SelectedRows[0].Cells["Name"].Value.ToString(); String symbol = stockDataGridView.SelectedRows[0].Cells["Symbol"].Value.ToString(); zg1.GraphPane.CurveList.Clear(); zg1.GraphPane.GraphObjList.Clear(); // Set the titles and axis labels myPane.Title.Text = "Historical Graph of " + name; myPane.XAxis.Title.Text = "Time, Days"; myPane.YAxis.Title.Text = "Daily Close Value"; // Make up some data points based on the Sine function PointPairList list = new PointPairList(); this.mainFormLoadingCircle.Visible = true; //loadingCircle.Visible = true; List <HistoricalStock> data = await Task.Run(() => HistoricalStockDownloader.DownloadData(symbol, DateTime.Now.Year)); this.mainFormLoadingCircle.Visible = false; foreach (var i in data) { if (i.Date.Year >= (DateTime.Now.Year)) { double x = (double)new XDate(i.Date); double y = i.Close; list.Add(x, y); } } // loadingCircle.Visible = false; // Generate a red curve LineItem myCurve = myPane.AddCurve(symbol, list, Color.Red, SymbolType.None); // Fill the symbols with white myCurve.Symbol.Fill = new Fill(Color.White); // Show the x axis grid myPane.XAxis.MajorGrid.IsVisible = true; // Set the XAxis to date type myPane.XAxis.Type = AxisType.Date; // 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 // 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; // Fill the axis background with a gradient myPane.Chart.Fill = new Fill(Color.LightYellow, Color.DeepSkyBlue, 45.0f); myPane.Fill = new Fill(Color.LightGreen); // Enable scrollbars if needed zg1.IsShowHScrollBar = true; zg1.IsShowVScrollBar = true; zg1.IsAutoScrollRange = true; zg1.IsScrollY2 = true; // OPTIONAL: Show tooltips when the mouse hovers over a point zg1.IsShowPointValues = true; // Tell ZedGraph to calculate the axis ranges // Note that you MUST call this after enabling IsAutoScrollRange, since AxisChange() sets // up the proper scrolling parameters zg1.AxisChange(); // Make sure the Graph gets redrawn zg1.Invalidate(); }
public virtual void GetObjectData( SerializationInfo info, StreamingContext context ) { info.AddValue( "schema", schema ); info.AddValue( "label", _label ); info.AddValue( "isY2Axis", _isY2Axis ); info.AddValue( "isX2Axis", _isX2Axis ); info.AddValue( "isVisible", _isVisible ); info.AddValue( "isOverrideOrdinal", _isOverrideOrdinal ); // if points is already a PointPairList, use it // otherwise, create a new PointPairList so it can be serialized PointPairList list; if ( _points is PointPairList ) list = _points as PointPairList; else list = new PointPairList( _points ); info.AddValue( "points", list ); info.AddValue( "Tag", Tag ); info.AddValue( "yAxisIndex", _yAxisIndex ); info.AddValue( "link", _link ); }
/// <summary>The populate data.</summary> private void PopulateData() { Dictionary<string, object> travelPeriod = new Dictionary<string, object>(); Dictionary<string, object> dataDate = new Dictionary<string, object>(); foreach (var j in this._journeyData) { var travelDate = new DatePeriod(j.DepartureDate, j.ReturnDate); travelPeriod.Add(j.DepartureDate.ToString("ddd dd/MM/yyyy") + " - " + j.ReturnDate.ToString("ddd dd/MM/yyyy"), travelDate); var points = new PointPairList(); var sortedData = j.Data.OrderBy(d => d.DataDate); foreach (var d in sortedData) { var cheapestFlight = d.Flights.OrderBy(f => f.Price).FirstOrDefault(); if (cheapestFlight != null) { var str = d.DataDate.ToLongDateString(); if (!dataDate.ContainsKey(str)) { dataDate.Add(str, d.DataDate.Date); } var x = (double)new XDate(d.DataDate); var newPoint = new PointPair(x, cheapestFlight.Price) { Tag = cheapestFlight }; points.Add(newPoint); } } this._graphData.Add(j, points); } // Render listview this.PopulateListView(travelPeriod, this.lvTravelPeriod, false); this.PopulateListView(dataDate, this.lvDataDate, true); }