bool SegmentIntersectsPolygon(PointPair segment)
        {
            if (Math.GetIntersections(Polygon, segment).Count != 0)
            {
                return true;
            }

            if (Math.IsPointInPolygon(Polygon, Math.Midpoint(segment.P1, segment.P2)))
            {
                return true;
            }

            for (int k = 0; k < Polygon.Count; k++)
            {
                var projection = Math.GetProjection(Polygon[k], segment);
                if (projection.Ratio > 0
                    && projection.Ratio < 1
                    && projection.DistanceToLine < 1)
                {
                    var point1 = Math.Midpoint(segment.P1, projection.Point);
                    var point2 = Math.Midpoint(segment.P2, projection.Point);
                    if (Math.IsPointInPolygon(Polygon, point1)
                        || Math.IsPointInPolygon(Polygon, point2))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
Exemplo n.º 2
0
 public override void Recalculate()
 {
     var p1 = Point(0);
     var p2 = Point(1);
     var line = (Flipped) ? new PointPair(p2, p1) : new PointPair(p1, p2);
     var midpoint = Math.Midpoint(p1, p2);
     var perpendicular = Math.GetPerpendicularLine(line, midpoint);
     coordinates = perpendicular;
 }
        /// <summary>
        /// Get the ordering of lines on station u with respect to the edge (u->v)
        /// </summary>
#if SHARPKIT //http://code.google.com/p/sharpkit/issues/detail?id=203
        //SharpKit/Colin - Interface implementations
        public IEnumerable<Metroline> GetOrder(Station u, Station v) {
#else
        IEnumerable<Metroline> IMetroMapOrderingAlgorithm.GetOrder(Station u, Station v) {
#endif
            var pointPair = new PointPair(u.Position, v.Position);
            var orderedMetrolineListForUv = bundles[pointPair].Metrolines;
            if (u.Position == pointPair.First) {
                foreach (var Metroline in orderedMetrolineListForUv) {
                    yield return Metroline;
                }
            }
            else {
                for (int i = orderedMetrolineListForUv.Count - 1; i >= 0; i--)
                    yield return orderedMetrolineListForUv[i];
            }
        }
 void AddEdges(Graph graph)
 {
     int n = graph.Nodes.Count;
     for (int i = 0; i < n - 1; i++)
     {
         for (int j = i + 1; j < n; j++)
         {
             if ((j == i + 1 && j < n - 2) || (i == 0 && j == n - 3))
             {
                 AddEdge(graph, i, j);
             }
             else
             {
                 var a = graph.Nodes[i].Point;
                 var b = graph.Nodes[j].Point;
                 PointPair segment = new PointPair(a, b);
                 if (!SegmentIntersectsPolygon(segment))
                 {
                     AddEdge(graph, i, j);
                 }
             }
         }
     }
 }
Exemplo n.º 5
0
        protected bool detectLabelCurveOverlap(GraphPane pane, IPointList points, int pointIndex, bool pointsAreSticks, RectangleF labelBounds)
        {
            double rL = labelBounds.Left;   // pane.XAxis.Scale.ReverseTransform( labelBounds.Left );
            //double rT = pane.YAxis.Scale.ReverseTransform( labelBounds.Top );
            double rR = labelBounds.Right;  //pane.XAxis.Scale.ReverseTransform( labelBounds.Right );
            double rB = labelBounds.Bottom; //pane.YAxis.Scale.ReverseTransform( labelBounds.Bottom );

            // labels cannot overlap the Y axis
            if (rL < pane.XAxis.Scale.Min)
            {
                return(true);
            }

            if (pointsAreSticks)
            {
                for (int k = 0; k < points.Count; ++k)
                {
                    PointPair p = points[k];

                    if (p.X > rR)
                    {
                        break;
                    }

                    if (p.X < rL)
                    {
                        continue;
                    }

                    if (p.Y > rB)
                    {
                        return(true);
                    }
                }
            }
            else
            {
                // find all points in the X range of the rectangle
                // also add the points immediately to the left and right
                // of these points, find the local maximum
                // an overlap happens if maximum > rB
                for (int k = pointIndex; k > 0; --k)
                {
                    PointPair p = points[k];

                    if (k + 1 < points.Count && points[k + 1].X < rL)
                    {
                        break;
                    }
                    if (p.Y > rB)
                    {
                        return(true);
                    }
                }

                // accessing points.Count in the loop condition showed up in a profiler
                for (int k = pointIndex + 1, len = points.Count; k < len; ++k)
                {
                    PointPair p = points[k];

                    if (points[k - 1].X > rR)
                    {
                        break;
                    }

                    if (p.Y > rB)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemplo n.º 6
0
        public override void UpdateGraph(bool selectionChanged)
        {
            SrmDocument document         = GraphSummary.DocumentUIContainer.DocumentUI;
            var         results          = document.Settings.MeasuredResults;
            bool        resultsAvailable = results != null;

            Clear();
            if (!resultsAvailable)
            {
                Title.Text = Resources.RTReplicateGraphPane_UpdateGraph_No_results_available;
                EmptyGraph(document);
                return;
            }

            var selectedTreeNode = GraphSummary.StateProvider.SelectedNode as SrmTreeNode ??
                                   GraphSummary.StateProvider.SelectedNodes.OfType <SrmTreeNode>().FirstOrDefault();

            if (selectedTreeNode == null || document.FindNode(selectedTreeNode.Path) == null)
            {
                EmptyGraph(document);
                return;
            }

            Title.Text = null;

            DisplayTypeChrom displayType  = GraphChromatogram.GetDisplayType(document, selectedTreeNode);
            DocNode          selectedNode = selectedTreeNode.Model;
            IdentityPath     selectedPath = selectedTreeNode.Path;
            DocNode          parentNode   = selectedNode;
            IdentityPath     parentPath   = selectedTreeNode.Path;

            // If the selected tree node is a transition, then its siblings are displayed.
            if (selectedTreeNode is TransitionTreeNode)
            {
                if (displayType != DisplayTypeChrom.single)
                {
                    SrmTreeNode parentTreeNode = selectedTreeNode.SrmParent;
                    parentNode   = parentTreeNode.Model;
                    selectedPath = parentTreeNode.Path;
                }
            }
            // If the selected node is a peptide with one child, then show the children,
            // unless chromatogram display type is total
            else if (selectedTreeNode is PeptideTreeNode)
            {
                var children = ((DocNodeParent)selectedNode).Children;
                if (children.Count == 1 && displayType != DisplayTypeChrom.total)
                {
                    selectedNode = parentNode = children[0];
                    selectedPath = new IdentityPath(parentPath, children[0].Id);
                }
            }
            else if (!(selectedTreeNode is PeptideGroupTreeNode) && !(selectedTreeNode is TransitionGroupTreeNode))
            {
                Title.Text      = Resources.RTReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_retention_time_graph;
                CanShowRTLegend = false;
                return;
            }

            // If a precursor is going to be displayed with display type single
            if (parentNode is TransitionGroupDocNode && displayType == DisplayTypeChrom.single)
            {
                // If no optimization data, then show all the transitions
                if (!results.Chromatograms.Contains(chrom => chrom.OptimizationFunction != null))
                {
                    displayType = DisplayTypeChrom.all;
                }
            }
            var rtTransformOp = GraphSummary.StateProvider.GetRetentionTimeTransformOperation();
            var rtValue       = RTPeptideGraphPane.RTValue;
            ReplicateGroupOp replicateGroupOp;

            if (rtValue == RTPeptideValue.All)
            {
                replicateGroupOp = ReplicateGroupOp.FromCurrentSettings(document.Settings, GraphValues.AggregateOp.MEAN);
            }
            else
            {
                replicateGroupOp = ReplicateGroupOp.FromCurrentSettings(document.Settings);
            }
            var retentionTimeValue = new GraphValues.RetentionTimeTransform(rtValue, rtTransformOp, replicateGroupOp.AggregateOp);

            YAxis.Title.Text = retentionTimeValue.GetAxisTitle();

            var peptidePaths = GetSelectedPeptides().GetUniquePeptidePaths().ToList();

            // if PeptideGroupTreeNode is selected but has only one child isMultiSelect should still be true
            IsMultiSelect = peptidePaths.Count > 1 ||
                            (peptidePaths.Count == 1 &&
                             GraphSummary.StateProvider.SelectedNodes.FirstOrDefault() is PeptideGroupTreeNode);

            GraphData graphData = new RTGraphData(document,
                                                  IsMultiSelect
                ? peptidePaths
                : new[] { selectedPath }.AsEnumerable(), displayType, retentionTimeValue, replicateGroupOp);

            CanShowRTLegend = graphData.DocNodes.Count != 0;
            InitFromData(graphData);

            int    selectedReplicateIndex = SelectedIndex;
            double minRetentionTime = double.MaxValue;
            double maxRetentionTime = -double.MaxValue;
            int    iColor = 0, iCharge = -1;
            var    charge = Adduct.EMPTY;
            int    countLabelTypes        = document.Settings.PeptideSettings.Modifications.CountLabelTypes;
            int    colorOffset            = 0;
            var    transitionGroupDocNode = parentNode as TransitionGroupDocNode;

            if (transitionGroupDocNode != null && displayType == DisplayTypeChrom.products)
            {
                // If we are only displaying product ions, we want to use an offset in the colors array
                // so that we do not re-use colors that would be used for any precursor ions.
                colorOffset =
                    GraphChromatogram.GetDisplayTransitions(transitionGroupDocNode, DisplayTypeChrom.precursors).Count();
            }
            for (int i = 0; i < graphData.DocNodes.Count; i++)
            {
                var docNode        = graphData.DocNodes[i];
                var identityPath   = graphData.DocNodePaths[i];
                var pointPairLists = graphData.PointPairLists[i];
                int numSteps       = pointPairLists.Count / 2;
                for (int iStep = 0; iStep < pointPairLists.Count; iStep++)
                {
                    int   step          = iStep - numSteps;
                    var   pointPairList = pointPairLists[iStep];
                    Color color;
                    var   isSelected = false;
                    var   nodeGroup  = docNode as TransitionGroupDocNode;
                    if (IsMultiSelect)
                    {
                        var peptides = peptidePaths.Select(path => document.FindNode(path))
                                       .Cast <PeptideDocNode>().ToArray();
                        var peptideDocNode = peptides.FirstOrDefault(
                            peptide => 0 <= peptide.FindNodeIndex(docNode.Id));
                        if (peptideDocNode == null)
                        {
                            continue;
                        }
                        color = GraphSummary.StateProvider.GetPeptideGraphInfo(peptideDocNode).Color;
                        if (identityPath.Equals(selectedTreeNode.Path) && step == 0)
                        {
                            color      = ChromGraphItem.ColorSelected;
                            isSelected = true;
                        }
                    }
                    else if (parentNode is PeptideDocNode)
                    {
                        // Resharper code inspection v9.0 on TC gets this one wrong
                        // ReSharper disable ExpressionIsAlwaysNull
                        int iColorGroup = GetColorIndex(nodeGroup, countLabelTypes, ref charge, ref iCharge);
                        // ReSharper restore ExpressionIsAlwaysNull
                        color = COLORS_GROUPS[iColorGroup % COLORS_GROUPS.Count];
                    }
                    else if (displayType == DisplayTypeChrom.total)
                    {
                        color = COLORS_GROUPS[iColor % COLORS_GROUPS.Count];
                    }
                    else if (ReferenceEquals(docNode, selectedNode) && step == 0)
                    {
                        color      = ChromGraphItem.ColorSelected;
                        isSelected = true;
                    }
                    else
                    {
                        color = COLORS_TRANSITION[(iColor + colorOffset) % COLORS_TRANSITION.Count];
                    }
                    iColor++;

                    string label = graphData.DocNodeLabels[i];
                    if (step != 0)
                    {
                        label = string.Format(Resources.RTReplicateGraphPane_UpdateGraph_Step__0__, step);
                    }

                    CurveItem curveItem;
                    if (IsMultiSelect)
                    {
                        if (rtValue != RTPeptideValue.All)
                        {
                            curveItem = CreateLineItem(label, pointPairList, color);
                        }
                        else
                        {
                            curveItem = CreateMultiSelectBarItem(label, pointPairList, color);
                        }
                    }
                    else if (HiLowMiddleErrorBarItem.IsHiLoMiddleErrorList(pointPairList))
                    {
                        curveItem        = new HiLowMiddleErrorBarItem(label, pointPairList, color, Color.Black);
                        BarSettings.Type = BarType.Cluster;
                    }
                    else if (rtValue == RTPeptideValue.All)
                    {
                        curveItem        = new MeanErrorBarItem(label, pointPairList, color, Color.Black);
                        BarSettings.Type = BarType.Cluster;
                    }
                    else
                    {
                        curveItem = CreateLineItem(label, pointPairList, color);
                    }

                    if (curveItem != null)
                    {
                        curveItem.Tag = identityPath;

                        var barItem = curveItem as BarItem;
                        if (barItem != null)
                        {
                            barItem.Bar.Border.IsVisible = false;
                            barItem.Bar.Fill.Brush       = GetBrushForNode(document.Settings, docNode, color);
                            if (!isSelected)
                            {
                                barItem.SortedOverlayPriority = 1;
                            }
                        }
                        CurveList.Add(curveItem);

                        if (selectedReplicateIndex != -1 && selectedReplicateIndex < pointPairList.Count)
                        {
                            PointPair pointPair = pointPairList[selectedReplicateIndex];
                            if (!pointPair.IsInvalid)
                            {
                                minRetentionTime = Math.Min(minRetentionTime, pointPair.Z);
                                maxRetentionTime = Math.Max(maxRetentionTime, pointPair.Y);
                            }
                        }
                    }
                }
            }
            // Draw a box around the currently selected replicate
            if (ShowSelection && minRetentionTime != double.MaxValue)
            {
                AddSelection(selectedReplicateIndex, maxRetentionTime, minRetentionTime);
            }
            // Reset the scale when the parent node changes
            if (_parentNode == null || !ReferenceEquals(_parentNode.Id, parentNode.Id))
            {
                XAxis.Scale.MaxAuto = XAxis.Scale.MinAuto = true;
                YAxis.Scale.MaxAuto = YAxis.Scale.MinAuto = true;
            }
            _parentNode      = parentNode;
            Legend.IsVisible = !IsMultiSelect && Settings.Default.ShowRetentionTimesLegend;
            GraphSummary.GraphControl.Invalidate();
            AxisChange();
        }
Exemplo n.º 7
0
        public static double GetYMin(PointPair pointPair)
        {
            var yMin = pointPair.Y - ((ErrorTag)pointPair.Tag).Error;

            return((double.IsNaN(yMin) || yMin > 0) ? 0 : yMin);
        }
Exemplo n.º 8
0
        public override void UpdateGraph(bool selectionChanged)
        {
            CurveList.Clear();
            GraphObjList.Clear();
            SrmDocument document         = GraphSummary.DocumentUIContainer.DocumentUI;
            var         selectedTreeNode = GraphSummary.StateProvider.SelectedNode as SrmTreeNode;

            if (selectedTreeNode == null || document.FindNode(selectedTreeNode.Path) == null)
            {
                Title.Text = Helpers.PeptideToMoleculeTextMapper.Translate(Resources.MassErrorReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_mass_error_graph, document.DocumentType);
                EmptyGraph(document);
                return;
            }
            if (!document.Settings.HasResults)
            {
                Title.Text = Resources.AreaReplicateGraphPane_UpdateGraph_No_results_available;
                EmptyGraph(document);
                return;
            }
            DisplayTypeChrom displayType;

            if (Equals(PaneKey, PaneKey.PRECURSORS))
            {
                displayType = DisplayTypeChrom.precursors;
            }
            else if (Equals(PaneKey, PaneKey.PRODUCTS))
            {
                displayType = DisplayTypeChrom.products;
            }
            else
            {
                displayType = GraphChromatogram.GetDisplayType(document, selectedTreeNode);
            }
            Title.Text = null;
            var aggregateOp = GraphValues.AggregateOp.FromCurrentSettings();

            YAxis.Title.Text = aggregateOp.Cv
                ? aggregateOp.AnnotateTitle(Resources.MassErrorReplicateGraphPane_UpdateGraph_Mass_Error_No_Ppm)
                : Resources.MassErrorReplicateGraphPane_UpdateGraph_Mass_Error;
            DocNode      selectedNode = selectedTreeNode.Model;
            DocNode      parentNode   = selectedNode;
            IdentityPath identityPath = selectedTreeNode.Path;

            // If the selected tree node is a transition, then its siblings are displayed.
            if (selectedTreeNode is TransitionTreeNode)
            {
                if (displayType != DisplayTypeChrom.single)
                {
                    SrmTreeNode parentTreeNode = selectedTreeNode.SrmParent;
                    parentNode   = parentTreeNode.Model;
                    identityPath = parentTreeNode.Path;
                }
            }
            // If the selected node is a peptide with one child, then show the children,
            // unless chromatogram display type is total
            else if (selectedTreeNode is PeptideTreeNode)
            {
                var children = ((PeptideDocNode)selectedNode).TransitionGroups
                               .Where(PaneKey.IncludesTransitionGroup)
                               .ToArray();
                if (children.Length == 1 && displayType != DisplayTypeChrom.total)
                {
                    selectedNode = parentNode = children[0];
                    identityPath = new IdentityPath(identityPath, parentNode.Id);
                }
            }
            else if (!(selectedTreeNode is TransitionGroupTreeNode))
            {
                Title.Text = Helpers.PeptideToMoleculeTextMapper.Translate(Resources.MassErrorReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_mass_error_graph, document.DocumentType);
                EmptyGraph(document);
                CanShowMassErrorLegend = false;
                return;
            }
            // If a precursor is going to be displayed with display type single
            if (parentNode is TransitionGroupDocNode && displayType == DisplayTypeChrom.single)
            {
                // If no optimization data, then show all the transitions
                displayType = DisplayTypeChrom.all;
            }

            var       replicateGroupOp = ReplicateGroupOp.FromCurrentSettings(document.Settings);
            GraphData graphData        = new MassErrorGraphData(document,
                                                                identityPath,
                                                                displayType,
                                                                replicateGroupOp,
                                                                PaneKey);

            CanShowMassErrorLegend = graphData.DocNodes.Count != 0;
            InitFromData(graphData);

            int    selectedReplicateIndex = SelectedIndex;
            double minRetentionTime       = double.MaxValue;
            double maxRetentionTime       = double.MinValue;

            int iColor = 0, iCharge = -1;
            var charge                 = Adduct.EMPTY;
            int countLabelTypes        = document.Settings.PeptideSettings.Modifications.CountLabelTypes;
            int colorOffset            = 0;
            var transitionGroupDocNode = parentNode as TransitionGroupDocNode;

            if (transitionGroupDocNode != null && displayType == DisplayTypeChrom.products)
            {
                // If we are only displaying product ions, we want to use an offset in the colors array
                // so that we do not re-use colors that would be used for any precursor ions.
                colorOffset =
                    GraphChromatogram.GetDisplayTransitions(transitionGroupDocNode, DisplayTypeChrom.precursors).Count();
            }
            for (int i = 0; i < graphData.DocNodes.Count; i++)
            {
                var docNode        = graphData.DocNodes[i];
                var pointPairLists = graphData.PointPairLists[i];
                int numSteps       = pointPairLists.Count / 2;
                for (int iStep = 0; iStep < pointPairLists.Count; iStep++)
                {
                    int   step          = iStep - numSteps;
                    var   pointPairList = pointPairLists[iStep];
                    Color color;
                    // ReSharper disable ExpressionIsAlwaysNull
                    var nodeGroup = docNode as TransitionGroupDocNode;
                    if (parentNode is PeptideDocNode)
                    {
                        int iColorGroup = GetColorIndex(nodeGroup, countLabelTypes, ref charge, ref iCharge);
                        color = COLORS_GROUPS[iColorGroup % COLORS_GROUPS.Count];
                    }
                    else if (displayType == DisplayTypeChrom.total)
                    {
                        color = COLORS_GROUPS[iColor % COLORS_GROUPS.Count];
                    }
                    else if (docNode.Equals(selectedNode) && step == 0)
                    {
                        color = ChromGraphItem.ColorSelected;
                    }
                    else
                    {
                        color = COLORS_TRANSITION[(iColor + colorOffset) % COLORS_TRANSITION.Count];
                    }
                    // ReSharper restore ExpressionIsAlwaysNull
                    iColor++;

                    string label = graphData.DocNodeLabels[i];
                    if (step != 0)
                    {
                        label = string.Format(Resources.RTReplicateGraphPane_UpdateGraph_Step__0__, step);
                    }
                    BarItem curveItem = new MeanErrorBarItem(label, pointPairList, color, Color.Black);

                    if (selectedReplicateIndex != -1 && selectedReplicateIndex < pointPairList.Count)
                    {
                        PointPair pointPair = pointPairList[selectedReplicateIndex];
                        if (!pointPair.IsInvalid)
                        {
                            minRetentionTime = Math.Min(minRetentionTime, pointPair.Y);
                            maxRetentionTime = Math.Max(maxRetentionTime, pointPair.Y);
                        }
                    }

                    curveItem.Bar.Border.IsVisible = false;
                    curveItem.Bar.Fill.Brush       = new SolidBrush(color);
                    curveItem.Tag = new IdentityPath(identityPath, docNode.Id);
                    CurveList.Add(curveItem);
                }
            }

            // Draw a box around the currently selected replicate
            if (ShowSelection && minRetentionTime != double.MaxValue)
            {
                maxRetentionTime = Math.Max(maxRetentionTime, 0);
                minRetentionTime = Math.Min(minRetentionTime, 0);
                GraphObjList.Add(new BoxObj(selectedReplicateIndex + .5, maxRetentionTime, 1,
                                            maxRetentionTime - minRetentionTime, Color.Black, Color.Empty)
                {
                    IsClippedToChartRect = true,
                });
            }

            XAxis.Scale.MinAuto = XAxis.Scale.MaxAuto = selectionChanged;
            YAxis.Scale.MinAuto = YAxis.Scale.MaxAuto = true;
            if (Settings.Default.MinMassError != 0)
            {
                YAxis.Scale.Min = Settings.Default.MinMassError;
            }
            if (Settings.Default.MaxMassError != 0)
            {
                YAxis.Scale.Max = Settings.Default.MaxMassError;
            }
            Legend.IsVisible = Settings.Default.ShowMassErrorLegend;
            AxisChange();
        }
        void FindIntersections()
        {
            intersectionsCount = 0;
            int currentSign = 1;
            intersectionData.Clear();
            var segment = new PointPair(Start, End);

            for (int i = 0; i < N; i++)
            {
                var current = Polygon.GetSegment(i);
                Point intersection = Math.GetIntersectionOfSegments(
                    segment, current);
                if (intersection.Exists()
                    && Polygon[i] != Start
                    && Polygon[i] != End
                    && Polygon[i.RotateNext(N)] != Start
                    && Polygon[i.RotateNext(N)] != End)
                {
                    intersectionsCount++;
                    int orientation = Math.VectorProduct(Start, Polygon[i.RotateNext(N)], End).Sign();

                    intersectionData.Add(new IntersectionData()
                    {
                        Index = i,
                        IntersectionPoint = intersection,
                        DistanceToStart = intersection.Distance(Start),
                        Orientation = orientation
                    });

                    currentSign = -currentSign;
                }
            }

            intersectionData = new List<IntersectionData>(
                intersectionData.OrderBy(d => d.DistanceToStart));
        }
        private void RemakeTreatmentGraphWith2(Get2ValuesForTreatment FunctionForData, String Title)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                GraphPane Graph = plotTreatments.GraphPane;
                Graph.CurveList.Clear();
                Graph.Title.Text           = Title;
                Graph.XAxis.Title.Text     = "Treatments";
                Graph.YAxis.Title.Text     = "";
                Graph.Legend.Position      = LegendPos.InsideTopLeft;
                Graph.Legend.FontSpec.Size = 8f;
                Graph.Legend.IsHStack      = true;
                SymbolType SymboltoUse = SymbolType.Circle;

                Dictionary <string, GrowthCurve> curData = GetDictionaryOfGrowthRateData();
                for (int i = 1; i < SelectablePlateMap.MAX_GROUP_ASSIGNMENTS; i++)
                {
                    Color         groupColor;
                    List <double> xVals     = new List <double>();
                    var           curNames  = selectablePlateMap1.GetNamesOfWellsAssignedToGroup(i, out groupColor);
                    string        GroupName = "";
                    if (TreatmentTextBoxes[i] != null)
                    {
                        GroupName = TreatmentTextBoxes[i].Text;
                    }
                    if (GroupName == "")
                    {
                        GroupName = "Treatment: " + i.ToString();
                    }
                    PointPairList XY = new PointPairList();
                    foreach (string name in curNames)
                    {
                        if (curData.ContainsKey(name))
                        {
                            GrowthCurve GD = curData[name];
                            PointPair   xy = SafeGet(FunctionForData, GD);
                            if (xy != null)
                            {
                                XY.Add(xy);
                            }
                        }
                    }
                    if (XY.Count > 0)
                    {
                        LineItem li = Graph.AddCurve(GroupName, XY, groupColor, SymboltoUse);
                        li.Line.IsVisible = false;
                        li.Symbol.Fill    = new Fill(groupColor);
                    }
                }
                if (chkTreatLegend.Checked)
                {
                    Graph.Legend.IsVisible = true;
                }
                else
                {
                    Graph.Legend.IsVisible = false;
                }
                Graph.XAxis.Scale.MaxGrace = .05;
                plotTreatments.AxisChange();
                plotTreatments.Invalidate();
                this.Cursor = Cursors.Default;
            }
            catch (Exception thrown)
            { MessageBox.Show("Could not make graph, talk to nigel.\n\nError is:\n" + thrown.Message, "Graph Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
            finally { this.Cursor = Cursors.Default; }
        }
 static void RegisterInPortLocationsToEdges(Edge eg, Dictionary<PointPair, List<Edge>> portLocationPairsToEdges) {
     List<Edge> list;
     var pp = new PointPair(eg.SourcePort.Location, eg.TargetPort.Location);
     if (!portLocationPairsToEdges.TryGetValue(pp, out list))
         portLocationPairsToEdges[pp] = list = new List<Edge>();
     list.Add(eg);
 }
Exemplo n.º 12
0
 public PointAnnotation AnnotatePoint(PointPair point)
 {
     return(new PointAnnotation());
 }
Exemplo n.º 13
0
        private void drawLabels(Graphics g)
        {
            foreach (GraphObj pa in _pointAnnotations)
            {
                GraphObjList.Remove(pa);
            }
            _pointAnnotations.Clear();

            Axis xAxis = XAxis;
            Axis yAxis = YAxis;

            yAxis.Scale.MinAuto = false;
            yAxis.Scale.Min     = 0;

            // setup axes scales to enable the Transform method
            xAxis.Scale.SetupScaleData(this, xAxis);
            yAxis.Scale.SetupScaleData(this, yAxis);

            if (Chart.Rect.Width < 1 || Chart.Rect.Height < 1)
            {
                return;
            }

            Region textBoundsRegion;
            Region chartRegion = new Region(Chart.Rect);
            Region clipRegion  = new Region();

            clipRegion.MakeEmpty();
            g.SetClip(Rect, CombineMode.Replace);
            g.SetClip(chartRegion, CombineMode.Exclude);

            /*Bitmap clipBmp = new Bitmap(Convert.ToInt32(Chart.Rect.Width), Convert.ToInt32(Chart.Rect.Height));
             * Graphics clipG = Graphics.FromImage(clipBmp);
             * clipG.Clear(Color.White);
             * clipG.FillRegion(new SolidBrush(Color.Black), g.Clip);
             * clipBmp.Save("C:\\clip.bmp");*/


            // some dummy labels for very fast clipping
            string baseLabel = "0";

            foreach (CurveItem item in CurveList)
            {
                IMSGraphItemInfo info = item.Tag as IMSGraphItemInfo;
                if (info != null)
                {
                    PointAnnotation annotation = info.AnnotatePoint(new PointPair(0, 0));
                    if (annotation != null &&
                        annotation.Label != null &&
                        annotation.Label.Length > baseLabel.Length)
                    {
                        baseLabel = annotation.Label;
                    }
                }
            }

            TextObj baseTextObj = new TextObj(baseLabel, 0, 0);

            baseTextObj.FontSpec.Border.IsVisible = false;
            baseTextObj.FontSpec.Fill.IsVisible   = false;
            PointF[] pts = baseTextObj.FontSpec.GetBox(g, baseLabel, 0, 0,
                                                       AlignH.Center, AlignV.Bottom, 1.0f, new SizeF());
            float baseLabelWidth  = (float)Math.Round(pts[1].X - pts[0].X);
            float baseLabelHeight = (float)Math.Round(pts[2].Y - pts[0].Y);

            baseLabelWidth  = (float)xAxis.Scale.ReverseTransform(xAxis.Scale.Transform(0) + baseLabelWidth);
            baseLabelHeight = (float)yAxis.Scale.ReverseTransform(yAxis.Scale.Transform(0) - baseLabelHeight);
            float labelLengthToWidthRatio = baseLabelWidth / baseLabel.Length;

            float xAxisPixel = yAxis.Scale.Transform(0);

            double xMin = xAxis.Scale.Min;
            double xMax = xAxis.Scale.Max;
            double yMin = yAxis.Scale.Min;
            double yMax = yAxis.Scale.Max;

            // add automatic labels for MSGraphItems
            foreach (CurveItem item in CurveList)
            {
                IMSGraphItemInfo info   = item.Tag as IMSGraphItemInfo;
                MSPointList      points = item.Points as MSPointList;
                if (info == null || points == null)
                {
                    continue;
                }

                if (info.ToString().Length == 0)
                {
                    continue;
                }

                PointPairList fullList     = points.FullList;
                List <int>    maxIndexList = points.ScaledMaxIndexList;
                for (int i = 0; i < maxIndexList.Count; ++i)
                {
                    if (maxIndexList[i] < 0)
                    {
                        continue;
                    }
                    PointPair pt = fullList[maxIndexList[i]];

                    if (pt.X < xMin || pt.Y > yMax || pt.Y < yMin)
                    {
                        continue;
                    }
                    if (pt.X > xMax)
                    {
                        break;
                    }

                    float yPixel = yAxis.Scale.Transform(pt.Y);

                    // labelled points must be at least 3 pixels off the X axis
                    if (xAxisPixel - yPixel < 3)
                    {
                        continue;
                    }

                    PointAnnotation annotation = info.AnnotatePoint(pt);
                    if (annotation == null)
                    {
                        continue;
                    }

                    if (annotation.ExtraAnnotation != null)
                    {
                        GraphObjList.Add(annotation.ExtraAnnotation);
                        _pointAnnotations.Add(annotation.ExtraAnnotation);
                    }

                    if (string.IsNullOrEmpty(annotation.Label))
                    {
                        continue;
                    }

                    float pointLabelWidth = labelLengthToWidthRatio * annotation.Label.Length;

                    double labelY = yAxis.Scale.ReverseTransform(yPixel - 5);

                    if (!AllowCurveOverlap)
                    {
                        // do fast check for overlap against all MSGraphItems
                        bool overlap = false;
                        foreach (CurveItem item2 in CurveList)
                        {
                            MSPointList points2 = item2.Points as MSPointList;
                            if (points2 != null)
                            {
                                int nearestMaxIndex = points2.GetNearestMaxIndexToBin(i);
                                if (nearestMaxIndex < 0)
                                {
                                    continue;
                                }
                                RectangleF r = new RectangleF((float)pt.X - pointLabelWidth / 2,
                                                              (float)labelY - baseLabelHeight,
                                                              pointLabelWidth,
                                                              baseLabelHeight);
                                overlap = detectLabelCurveOverlap(this, points2.FullList, nearestMaxIndex, item2 is StickItem, r);
                                if (overlap)
                                {
                                    break;
                                }
                            }
                        }

                        if (overlap)
                        {
                            continue;
                        }
                    }

                    TextObj text = new TextObj(annotation.Label, pt.X, labelY,
                                               CoordType.AxisXYScale, AlignH.Center, AlignV.Bottom)
                    {
                        ZOrder   = ZOrder.A_InFront,
                        FontSpec = annotation.FontSpec
                    };
                    //text.IsClippedToChartRect = true;

                    if (!detectLabelOverlap(this, g, text, out textBoundsRegion, item.Points, maxIndexList[i], item is StickItem))
                    {
                        GraphObjList.Add(text);
                        _pointAnnotations.Add(text);


                        clipRegion.Union(textBoundsRegion);
                        g.SetClip(clipRegion, CombineMode.Replace);
                    }
                }
            }

            // add manual annotations
            foreach (CurveItem item in CurveList)
            {
                IMSGraphItemInfo info   = item.Tag as IMSGraphItemInfo;
                MSPointList      points = item.Points as MSPointList;
                if (info == null || points == null)
                {
                    continue;
                }

                info.AddAnnotations(this, g, points, _pointAnnotations);
                foreach (GraphObj obj in _pointAnnotations)
                {
                    if (!GraphObjList.Contains(obj))
                    {
                        TextObj text = obj as TextObj;
                        if (text != null)
                        {
                            if (detectLabelOverlap(this, g, text, out textBoundsRegion, item.Points, -1, item is StickItem))
                            {
                                continue;
                            }

                            clipRegion.Union(textBoundsRegion);
                            g.SetClip(clipRegion, CombineMode.Replace);
                        }

                        GraphObjList.Add(obj);
                    }
                }

                /*GraphObjList objsToRemove = new GraphObjList();
                 * foreach( GraphObj obj in GraphObjList )
                 *  if( !pointAnnotations_.Contains( obj ) )
                 *      objsToRemove.Add( obj );
                 * foreach( GraphObj obj in objsToRemove )
                 *  GraphObjList.Remove( obj );*/
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// Creates a new LinePlottable.
 /// </summary>
 /// <param name="line">the line</param>
 /// <param name="info">the line info</param>
 /// <returns>new LinePlottable instance</returns>
 public static LinePlottable NewInstance(PointPair line, LineInfo info)
 {
     ValidationUtil.RequireNonNull(line);
     ValidationUtil.RequireNonNull(info);
     return(new LinePlottable(line, info));
 }
Exemplo n.º 15
0
 /// <summary>
 /// Private constructor
 /// </summary>
 /// <param name="line">the line</param>
 /// <param name="info">the line info</param>
 private LinePlottable(PointPair line, LineInfo info)
 {
     Line = line;
     Info = info;
 }
Exemplo n.º 16
0
 public bool Touches(PointPair other)
 {
     return(A == other.A || A == other.B || B == other.A || B == other.B);
 }
Exemplo n.º 17
0
 private static double Dist(PointPair origin, PointPair point)
 {
     return(Math.Sqrt(Math.Pow((point.X - origin.X), 2) + Math.Pow((point.Y - origin.Y), 2)));
 }
Exemplo n.º 18
0
 void setZ(PointPair pp)
 {
     pp.Z = pp.X;
 }
Exemplo n.º 19
0
    /// <summary>
    /// Main program.
    /// </summary>
    static int Main(string[] args)
    {
        // Check input arguments.
        if (args.Length < 2)
        {
            Console.WriteLine("Expected at least two arguments:");
            Console.WriteLine("  Path to protobuf file containing model");
            Console.WriteLine("  Paths to one or more image files");
            return(-1);
        }

        // Create and initialize the mask finder.
        RulerMaskFinder mask_finder = new RulerMaskFinder();
        ErrorCode       status      = mask_finder.Init(args[0]);

        if (status != ErrorCode.kSuccess)
        {
            Console.WriteLine("Failed to initialize ruler mask finder!");
            return(-1);
        }

        // Load in images.
        VectorImage imgs = new VectorImage();

        for (int i = 1; i < args.Length; i++)
        {
            Image img = new Image();
            status = img.FromFile(args[i]);
            if (status != ErrorCode.kSuccess)
            {
                Console.WriteLine("Failed to load image {0}!", args[i]);
                return(-1);
            }
            imgs.Add(img);
        }

        // Add images to processing queue.
        foreach (var img in imgs)
        {
            status = mask_finder.AddImage(img);
            if (status != ErrorCode.kSuccess)
            {
                Console.WriteLine("Failed to add image for processing!");
                return(-1);
            }
        }

        // Process the loaded images.
        VectorImage masks = new VectorImage();

        status = mask_finder.Process(masks);
        if (status != ErrorCode.kSuccess)
        {
            Console.WriteLine("Failed to process images!");
            return(-1);
        }

        for (int i = 0; i < masks.Count; ++i)
        {
            // Resize the masks back into the same size as the images.
            masks[i].Resize(imgs[i].Width(), imgs[i].Height());

            // Check if the ruler is present.
            bool present = openem.RulerPresent(masks[i]);
            if (!present)
            {
                Console.WriteLine("Could not find ruler in image!  Skipping...");
                continue;
            }

            // Find orientation and region of interest based on the mask.
            PointPair endpoints = new PointPair();
            endpoints = openem.RulerEndpoints(masks[i]);
            Image r_mask = openem.Rectify(masks[i], endpoints);
            Rect  roi    = openem.FindRoi(r_mask);

            // Rectify, crop, and display the image.
            Image r_img = openem.Rectify(imgs[i], endpoints);
            Image c_img = openem.Crop(r_img, roi);
            c_img.Show();
        }

        return(0);
    }
Exemplo n.º 20
0
 void ToVoltage(PointPair pp)
 {
     setZ(pp);
     pp.X = collector.pointToVoltage((ushort)pp.Z);
 }
        bool AddVertexToSplittingList(PointPair a, Dictionary<PointPair, List<Point>> splittingPoints, Point intersectionPoint) {
#if DEBUG && TEST_MSAGL
            double t;
            System.Diagnostics.Debug.Assert(Point.DistToLineSegment(intersectionPoint, a.First, a.Second, out t) < ApproximateComparer.IntersectionEpsilon);
#endif
            if (!ApproximateComparer.CloseIntersections(intersectionPoint, a.First) &&
                !ApproximateComparer.CloseIntersections(intersectionPoint, a.Second)) {
                List<Point> list;
                if (!splittingPoints.TryGetValue(a, out list))
                    splittingPoints[a] = list = new List<Point>();
                if (!list.Contains(intersectionPoint)) {
                    list.Add(intersectionPoint);
                    return true;
                }
            }
            return false;
        }
Exemplo n.º 22
0
 void ToMass(PointPair pp)
 {
     pp.X = collector.pointToMass((ushort)pp.Z);
 }
 List<Point> CutOutLoops(List<Point> path)
 {
     List<Point> result = new List<Point>(path);
     for (int i = 3; i < path.Count; i++)
     {
         for (int j = 1; j < i - 1; j++)
         {
             var currentSegment = new PointPair(path[i - 1], path[i]);
             var previousSegment = new PointPair(path[j - 1], path[j]);
             if (Math.GetIntersectionOfSegments
                 (currentSegment, previousSegment)
                 .Exists())
             {
                 if (SegmentIntersectsSide(path[i - 1], path[j - 1]) == -1)
                 {
                     result.RemoveRange(j, i - j);
                     return CutOutLoops(result);
                 }
             }
         }
     }
     return result;
 }
Exemplo n.º 24
0
 public override string ToString() => PointPair.ToString();
        /// <summary>
        /// Unbundle unnecessary edges:
        ///  instead of one bundle (a->bcd) we get two bundles (a->b,a->cd) with smaller ink
        /// </summary>
        bool UnglueEdgesFromBundleToSaveInk(bool alwaysExecuteSA) {
            var segsToPolylines = new Dictionary<PointPair, Set<Metroline>>();
            ink = metroGraphData.Ink;
            polylineLength = new Dictionary<Metroline, double>();
            //create polylines
            foreach (var metroline in metroGraphData.Metrolines) {
                polylineLength[metroline] = metroline.Length;
                for (var pp = metroline.Polyline.StartPoint; pp.Next != null; pp = pp.Next) {
                    var segment = new PointPair(pp.Point, pp.Next.Point);
                    CollectionUtilities.AddToMap(segsToPolylines, segment, metroline);
                }
            }
            var affectedPoints = new HashSet<Point>();
            var progress = false;
            foreach (var metroline in metroGraphData.Metrolines) {
                var obstaclesAllowedToIntersect =
                    metroGraphData.PointToStations[metroline.Polyline.Start].EnterableLoosePolylines*
                    metroGraphData.PointToStations[metroline.Polyline.End].EnterableLoosePolylines;
                if (TrySeparateOnPolyline(metroline, segsToPolylines, affectedPoints, obstaclesAllowedToIntersect))
                    progress = true;
            }

            if (progress) //TimeMeasurer.DebugOutput("unbundling");
                metroGraphData.Initialize(false);

            if (alwaysExecuteSA || progress)
                SimulatedAnnealing.FixRouting(metroGraphData, bundlingSettings, alwaysExecuteSA ? null : affectedPoints);

            return progress;
        }
Exemplo n.º 26
0
 public bool ContainsPoint(MarkupPoint point) => PointPair.ContainPoint(point);
Exemplo n.º 27
0
        public static double GetYTotal(PointPair pointPair)
        {
            var yTotal = pointPair.Y + ((ErrorTag)pointPair.Tag).Error;

            return(double.IsNaN(yTotal) ? 0 : yTotal);
        }
Exemplo n.º 28
0
        /// <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="ZedGraph.IPointList"/> for each <see cref="ZedGraph.CurveItem"/> in the
        /// specified <see cref="ZedGraph.GraphPane"/>.
        /// </summary>
        /// <param name="g">The <see cref="Graphics"/> object to be used for rendering the data.</param>
        /// <param name="pane">The <see cref="ZedGraph.GraphPane"/> object which will receive the data.</param>
        protected void PopulateByDataSource(IGraphics g, GraphPane pane)
        {
            if (CurveList.Count == 0)
            {
                return;
            }

            //If the Datasource column names are available we can bind them
            // correctly to their corresponding DataMember.
            if (!string.IsNullOrEmpty(DataMember)
                && DataSource != null
                && DataSource is ITypedList
                && DataSource is IListSource)
            {
                var tlist = DataSource as ITypedList;
                var listSource = 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 = DataMember;
                PropertyDescriptor basePd = pdc.Find(baseDataMember, true);
                if (basePd == null)
                {
                    throw new Exception("Can't find DataMember '" + baseDataMember + "' in DataSource for the base axis.");
                }

                //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 (ZedGraphWebCurveItem curveItem in 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)
                    {
                        var valueTlist = curveItem.DataSource as ITypedList;
                        pdcValue = valueTlist.GetItemProperties(null);
                        var 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 Exception("Can't find DataMember '" + valueDataMember + "' in DataSource for the " + curveItem.Label + " axis.");
                    }
                    int indexValueColumn = pdcValue.IndexOf(pd);

                    //Add points
                    var points = new PointPairList();
                    var 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 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;
                            if (oColumnValue != null)
                            {
                                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 (XAxis.Type == AxisType.DateAsOrdinal
                                || 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 (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
                ZedGraphWebCurveItem curve;
                for (int i = 0; i < CurveList.Count; i++)
                {
                    curve = CurveList[i];

                    var points = new PointPairList();
                    var 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: ZedGraphWeb.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 (???)
        }
Exemplo n.º 29
0
        protected override void DrawSingleBar(Graphics g, GraphPane pane, CurveItem curve,
                                              int index, int pos, Axis baseAxis, Axis valueAxis, float barWidth, float scaleFactor)
        {
            base.DrawSingleBar(g, pane, curve, index, pos, baseAxis, valueAxis, barWidth, scaleFactor);
            PointPair pointPair = curve.Points[index];
            ErrorTag  errorTag  = pointPair.Tag as ErrorTag;

            if (pointPair.IsInvalid || errorTag == null)
            {
                return;
            }

            double       curBase, curLowVal, curHiVal;
            ValueHandler valueHandler = new ValueHandler(pane, false);

            valueHandler.GetValues(curve, index, out curBase, out curLowVal, out curHiVal);

            float  pixBase     = baseAxis.Scale.Transform(curve.IsOverrideOrdinal, index, curBase);
            double lowError    = curHiVal - errorTag.Error;
            float  pixLowError = valueAxis.Scale.Transform(lowError);
            float  pixHiError  = valueAxis.Scale.Transform(lowError + errorTag.Error * 2);

            float clusterWidth = pane.BarSettings.GetClusterWidth();
            //float barWidth = curve.GetBarWidth( pane );
            float clusterGap = pane.BarSettings.MinClusterGap * barWidth;
            float barGap     = barWidth * pane.BarSettings.MinBarGap;

            // Calculate the pixel location for the side of the bar (on the base axis)
            float pixSide = pixBase - clusterWidth / 2.0F + clusterGap / 2.0F +
                            pos * (barWidth + barGap);

            // Draw the bar
            if (pane.BarSettings.Base == BarBase.X)
            {
                if (barWidth >= 3 && errorTag.Error > 0)
                {
                    // Draw whiskers
                    float pixMidX = (float)Math.Round(pixSide + barWidth / 2);

                    // Line
                    g.DrawLine(ErrorPen, pixMidX, pixHiError, pixMidX, pixLowError);
                    if (barWidth >= PIX_TERM_WIDTH)
                    {
                        // Ends
                        float pixLeft  = pixMidX - (float)Math.Round(PIX_TERM_WIDTH / 2);
                        float pixRight = pixLeft + PIX_TERM_WIDTH - 1;
                        g.DrawLine(ErrorPen, pixLeft, pixHiError, pixRight, pixHiError);
                        g.DrawLine(ErrorPen, pixLeft, pixLowError, pixRight, pixLowError);
                    }
                }
            }
            else
            {
                if (barWidth >= 3 && errorTag.Error > 0)
                {
                    // Draw whiskers
                    float pixMidY = (float)Math.Round(pixSide + barWidth / 2) + 1;

                    // Line
                    g.DrawLine(ErrorPen, pixLowError, pixMidY, pixHiError, pixMidY);
                    if (barWidth >= PIX_TERM_WIDTH)
                    {
                        // Ends
                        float pixTop    = pixMidY - (float)Math.Round(PIX_TERM_WIDTH / 2);
                        float pixBottom = pixTop + PIX_TERM_WIDTH - 1;
                        g.DrawLine(ErrorPen, pixHiError, pixTop, pixHiError, pixBottom);
                        g.DrawLine(ErrorPen, pixLowError, pixTop, pixLowError, pixBottom);
                    }
                }
            }
        }
Exemplo n.º 30
0
 public void Add(PointPair p)
 {
     Add(p.X, p.Y);
 }
Exemplo n.º 31
0
        private void drawLabels(Graphics g)
        {
            foreach (GraphObj pa in _pointAnnotations)
            {
                GraphObjList.Remove(pa);
            }
            _pointAnnotations.Clear();
            _manualLabels.Clear();

            Axis xAxis = XAxis;
            Axis yAxis = YAxis;

            yAxis.Scale.MinAuto = false;
            if (LockYAxisAtZero)
            {
                yAxis.Scale.Min = 0;
            }

            // ensure that the chart rectangle is the right size
            AxisChange(g);
            // then setup axes scales to enable the Transform method
            xAxis.Scale.SetupScaleData(this, xAxis);
            yAxis.Scale.SetupScaleData(this, yAxis);

            if (Chart.Rect.Width < 1 || Chart.Rect.Height < 1)
            {
                return;
            }

            _overlapDetector = AllowLabelOverlap ? null : new OverlapDetector();
            Region chartRegion = new Region(Chart.Rect);
            Region clipRegion  = new Region();

            clipRegion.MakeEmpty();
            var previousClip = g.Clip.Clone();

            g.SetClip(Rect, CombineMode.Replace);
            g.SetClip(chartRegion, CombineMode.Exclude);

            /*Bitmap clipBmp = new Bitmap(Convert.ToInt32(Chart.Rect.Width), Convert.ToInt32(Chart.Rect.Height));
             * Graphics clipG = Graphics.FromImage(clipBmp);
             * clipG.Clear(Color.White);
             * clipG.FillRegion(new SolidBrush(Color.Black), g.Clip);
             * clipBmp.Save("C:\\clip.bmp");*/


            // some dummy labels for very fast clipping
            string baseLabel = @"0";

            foreach (CurveItem item in CurveList)
            {
                IMSGraphItemInfo info = item.Tag as IMSGraphItemInfo;
                if (info != null)
                {
                    PointAnnotation annotation = info.AnnotatePoint(new PointPair(0, 0));
                    if (annotation != null &&
                        annotation.Label != null &&
                        annotation.Label.Length > baseLabel.Length)
                    {
                        baseLabel = annotation.Label;
                    }
                }
            }

            TextObj baseTextObj = new TextObj(baseLabel, 0, 0);

            baseTextObj.FontSpec.Border.IsVisible = false;
            baseTextObj.FontSpec.Fill.IsVisible   = false;
            PointF[] pts = baseTextObj.FontSpec.GetBox(g, baseLabel, 0, 0,
                                                       AlignH.Center, AlignV.Bottom, 1.0f, new SizeF());
            float baseLabelWidth  = pts[1].X - pts[0].X;
            float baseLabelHeight = pts[2].Y - pts[0].Y;

            baseLabelWidth  = (float)xAxis.Scale.ReverseTransform(xAxis.Scale.Transform(0) + baseLabelWidth);
            baseLabelHeight = (float)yAxis.Scale.ReverseTransform(yAxis.Scale.Transform(0) - baseLabelHeight);
            float labelLengthToWidthRatio = baseLabelWidth / baseLabel.Length;

            float xAxisPixel = yAxis.Scale.Transform(0);

            double xMin = xAxis.Scale.Min;
            double xMax = xAxis.Scale.Max;
            double yMin = yAxis.Scale.Min;
            double yMax = yAxis.Scale.Max;

            // add manual annotations with TextObj priority over curve annotations
            foreach (CurveItem item in CurveList)
            {
                var         info   = item.Tag as IMSGraphItemExtended;
                MSPointList points = item.Points as MSPointList;
                if (info == null || points == null)
                {
                    continue;
                }

                info.AddPreCurveAnnotations(this, g, points, _pointAnnotations);
                AddAnnotations(g);
            }

            // add automatic labels for MSGraphItems
            foreach (CurveItem item in CurveList)
            {
                IMSGraphItemInfo info   = item.Tag as IMSGraphItemInfo;
                MSPointList      points = item.Points as MSPointList;
                if (info == null || points == null)
                {
                    continue;
                }

                if (info.ToString().Length == 0)
                {
                    continue;
                }

                PointPairList fullList               = points.FullList;
                List <int>    maxIndexList           = points.ScaledMaxIndexList;
                var           annotationsPrioritized = new Dictionary <PointAnnotation, int>();
                for (int i = 0; i < maxIndexList.Count; ++i)
                {
                    if (maxIndexList[i] < 0)
                    {
                        continue;
                    }
                    PointPair pt = fullList[maxIndexList[i]];

                    if (pt.X < xMin || pt.Y > yMax || pt.Y < yMin)
                    {
                        continue;
                    }
                    if (pt.X > xMax)
                    {
                        break;
                    }

                    float yPixel = yAxis.Scale.Transform(pt.Y);

                    // labelled points must be at least 3 pixels off the X axis
                    if (xAxisPixel - yPixel < 3)
                    {
                        continue;
                    }

                    PointAnnotation annotation = info.AnnotatePoint(pt);
                    if (annotation != null)
                    {
                        annotationsPrioritized.Add(annotation, i);
                    }
                }

                // Give the higher ranked point priority
                foreach (var annotation in annotationsPrioritized.Keys.OrderBy(a => a.ZOrder ?? int.MaxValue))
                {
                    if (annotation.ExtraAnnotation != null)
                    {
                        GraphObjList.Add(annotation.ExtraAnnotation);
                        _pointAnnotations.Add(annotation.ExtraAnnotation);
                    }

                    if (string.IsNullOrEmpty(annotation.Label))
                    {
                        continue;
                    }

                    float pointLabelWidth = labelLengthToWidthRatio * annotation.Label.Split('\n').Max(o => o.Length);

                    var       i      = annotationsPrioritized[annotation];
                    PointPair pt     = fullList[maxIndexList[i]];
                    float     yPixel = yAxis.Scale.Transform(pt.Y);
                    double    labelY = yAxis.Scale.ReverseTransform(yPixel - 5);

                    if (!AllowCurveOverlap)
                    {
                        // do fast check for overlap against all MSGraphItems
                        bool overlap = false;
                        foreach (CurveItem item2 in CurveList)
                        {
                            MSPointList points2 = item2.Points as MSPointList;
                            if (points2 != null)
                            {
                                int nearestMaxIndex = points2.GetNearestMaxIndexToBin(i);
                                if (nearestMaxIndex < 0)
                                {
                                    continue;
                                }
                                RectangleF r = new RectangleF((float)pt.X - pointLabelWidth / 2,
                                                              (float)labelY - baseLabelHeight,
                                                              pointLabelWidth,
                                                              baseLabelHeight);
                                overlap = detectLabelCurveOverlap(this, points2.FullList, nearestMaxIndex, item2 is StickItem, r);
                                if (overlap)
                                {
                                    break;
                                }
                            }
                        }

                        if (overlap)
                        {
                            continue;
                        }
                    }

                    TextObj text = new TextObj(annotation.Label, pt.X, labelY,
                                               CoordType.AxisXYScale, AlignH.Center, AlignV.Bottom)
                    {
                        ZOrder               = ZOrder.A_InFront,
                        FontSpec             = annotation.FontSpec,
                        IsClippedToChartRect = true
                    };

                    var  textRect = _labelBoundsCache.GetLabelBounds(text, this, g);
                    bool overlap2 = _overlapDetector != null && _overlapDetector.Overlaps(textRect);
                    _manualLabels[text] = textRect;
                    if (!overlap2)
                    {
                        _pointAnnotations.Add(text);
                        AddAnnotations(g);
                    }
                }
            }

            // add manual annotations
            foreach (CurveItem item in CurveList)
            {
                IMSGraphItemInfo info   = item.Tag as IMSGraphItemInfo;
                MSPointList      points = item.Points as MSPointList;
                if (info == null || points == null)
                {
                    continue;
                }

                info.AddAnnotations(this, g, points, _pointAnnotations);
                AddAnnotations(g);
            }

            autoScaleForManualLabels(g);
            g.Clip = previousClip;
        }
Exemplo n.º 32
0
 public PointPairRef(PointPair pointPair, int pointPairListIndex, int groupIndex)
 {
     PointPair          = pointPair;
     PointPairListIndex = pointPairListIndex;
     GroupIndex         = groupIndex;
 }
Exemplo n.º 33
0
        //This function runs once every second
        void ClockElapsed(object sender, ElapsedEventArgs e)
        {
            // Figure out elapsted time, t
            var t    = DateTime.Now.Subtract(_tStart).TotalSeconds;
            var tRem = _tEnd.Subtract(DateTime.Now).TotalSeconds;

            if (tRem > 0)
            {
                PointPair prev = PrevPoint(t);
                PointPair next = NextPoint(t);

                if (prev.X == next.X)
                {
                    return;
                }

                var slope = (next.Y - prev.Y) / (next.X - prev.X);

                var vol = slope * (t - prev.X) + prev.Y;

                _audDev.AudioEndpointVolume.MasterVolumeLevelScalar = (float)(vol / 100.0);

                // Show progress indicator at current point
                var theShit = new MethodInvoker(() =>
                {
                    zg1.GraphPane.CurveList[0].Points[0].X = t;
                    zg1.GraphPane.CurveList[0].Points[0].Y = vol;
                    zg1.Refresh();
                });
                if (InvokeRequired)
                {
                    BeginInvoke(theShit);
                }
                else
                {
                    theShit.Invoke();
                }
            }
            else
            {
                _clock.Stop();
                _audDev.AudioEndpointVolume.MasterVolumeLevelScalar = (float)(_endVol / 100.0);

                var theShit = new MethodInvoker(() =>
                {
                    //Set Audio to Mute
                    if (chkMuteWhenDone.Checked)
                    {
                        _audDev.AudioEndpointVolume.Mute = true;
                    }

                    zg1.GraphPane.CurveList[0].Points[0].X = t;
                    zg1.GraphPane.CurveList[0].Points[0].Y = _endVol;
                    zg1.Refresh();

                    //Set Volume Level
                    if (chkRestoreVol.Checked)
                    {
                        try
                        {
                            _audDev.AudioEndpointVolume.MasterVolumeLevelScalar =
                                Single.Parse(txtRestoreVol.Text) / 100.0f;
                        }
                        catch {}
                    }

                    //Standby
                    switch (comboAction.SelectedIndex)
                    {
                    case 1:
                        Application.SetSuspendState(PowerState.Suspend, true, true);
                        break;

                    case 2:
                        Application.SetSuspendState(PowerState.Hibernate, true, true);
                        break;

                    case 3:
                        CmdExec("shutdown /s /t 0");
                        break;

                    case 4:
                        CmdExec("shutdown /r /t 0");
                        break;

                    case 5:
                        Program.LockWorkStation();
                        break;

                    case 6:
                        Program.ExitWindowsEx((uint)Program.ExitVals.LogOff, 0);
                        break;

                    case 7:
                        CmdExec(txtRunCmd.Text);
                        break;
                    }

                    //Close App, this has to be last
                    if (chkExit.Checked)
                    {
                        Application.Exit();
                    }
                    else
                    {
                        _isRunning  = false;
                        btnGo.Image = Resources.startButton;
                        zg1.Enabled = true;
                    }
                });
                if (InvokeRequired)
                {
                    BeginInvoke(theShit);
                }
                else
                {
                    theShit.Invoke();
                }
            }
        }
Exemplo n.º 34
0
 private bool IsPointPairValid(PointPair pair)
 {
     return(pair.IsInvalid == pair.IsMissing);
 }
Exemplo n.º 35
0
        public override void UpdateGraph(bool selectionChanged)
        {
            if (!GraphSummary.DocumentUIContainer.DocumentUI.Settings.HasResults)
            {
                _areaCVGraphData = null;
                return;
            }

            _document = GraphSummary.DocumentUIContainer.DocumentUI;
            var settings = new AreaCVGraphData.AreaCVGraphSettings(_document.Settings, GraphSummary.Type);

            var factor = AreaGraphController.GetAreaCVFactorToDecimal();

            BarSettings.Type = BarType.SortedOverlay;
            BarSettings.ClusterScaleWidth = Settings.Default.AreaCVHistogramBinWidth;
            BarSettings.MinClusterGap     = 0.0f;

            _percentage = !Settings.Default.AreaCVShowDecimals;
            _decimals   = _percentage ? 1 : 3;

            GraphObjList.Clear();
            CurveList.Clear();
            _stickItems.Clear();

            var gotData = _cache.TryGet(_document, settings, DataCallback, out _areaCVGraphData);

            if (!gotData || !_areaCVGraphData.IsValid)
            {
                return;
            }

            var fontHeight = GraphSummary.CreateFontSpec(Color.Black).GetHeight(CalcScaleFactor());
            var height     = PaneHeightToYValue(fontHeight);

            var heightFactor = 1;

            if (Settings.Default.AreaCVShowMedianCV)
            {
                var stick = AddStickItem(_areaCVGraphData.MedianCV * factor, _areaCVGraphData.MedianCV * factor, 0.0, _areaCVGraphData.MaxFrequency + heightFactor++ *height, Color.Blue);
                CurveList.Add(stick);
                _stickItems.Add(stick);
            }

            if (Settings.Default.AreaCVShowCVCutoff)
            {
                var stick = AddStickItem(Settings.Default.AreaCVCVCutoff, Settings.Default.AreaCVCVCutoff, 0.0, _areaCVGraphData.MaxFrequency + heightFactor++ *height, Color.Red);
                CurveList.Add(stick);
                _stickItems.Add(stick);
            }

            var selected = HistogramHelper.GetSelectedPeptides(GraphSummary).NodePeps.OrderBy(p => p.Id.GlobalIndex).ToList();
            var comparer = Comparer <PeptideDocNode> .Create((a, b) => a.Id.GlobalIndex.CompareTo(b.Id.GlobalIndex));

            var selectedPoints  = new PointPairList();
            var selectedPoints2 = new PointPairList();
            var otherPoints     = new PointPairList();

            foreach (var d in _areaCVGraphData.Data)
            {
                int frequency;
                var x = d.CV * factor + Settings.Default.AreaCVHistogramBinWidth / 2.0f;

                var pt = new PointPair(x, d.Frequency)
                {
                    Tag = d
                };
                if (Settings.Default.ShowReplicateSelection &&
                    (frequency = d.PeptideAnnotationPairs.Count(pair => selected.BinarySearch(pair.Peptide, comparer) >= 0)) > 0)
                {
                    selectedPoints.Add(pt);
                    selectedPoints2.Add(new PointPair(x, frequency)
                    {
                        Tag = d
                    });
                }
                else
                {
                    otherPoints.Add(pt);
                }
            }

            CurveList.Insert(0, MakeBarItem(selectedPoints2, Color.Red));
            CurveList.Insert(1, MakeBarItem(selectedPoints, Color.FromArgb(Color.Red.ToArgb() & 0x7FFFFFFF)));
            CurveList.Insert(2, MakeBarItem(otherPoints, Color.FromArgb(180, 220, 255)));

            XAxis.Title.Text = Resources.AreaCVHistogramGraphPane_UpdateGraph_CV + (_percentage ? @" (%)" : string.Empty);
            YAxis.Title.Text = Resources.AreaCVHistogramGraphPane_UpdateGraph_Frequency;

            XAxis.Scale.Min     = YAxis.Scale.Min = 0;
            XAxis.Scale.MinAuto = XAxis.Scale.MaxAuto = YAxis.Scale.MinAuto = YAxis.Scale.MaxAuto = false;

            if (!double.IsNaN(Settings.Default.AreaCVMaxCV))
            {
                XAxis.Scale.Max = Settings.Default.AreaCVMaxCV;
            }
            else
            {
                XAxis.Scale.Max = _areaCVGraphData.MaxCV * factor + Settings.Default.AreaCVHistogramBinWidth;
            }

            if (!double.IsNaN(Settings.Default.AreaCVMaxFrequency))
            {
                YAxis.Scale.Max = Settings.Default.AreaCVMaxFrequency;
            }
            else
            {
                YAxis.Scale.Max = _areaCVGraphData.MaxFrequency + heightFactor * height;
            }

            AxisChange();
        }
Exemplo n.º 36
0
 public abstract PointAnnotation AnnotatePoint(PointPair point);
 void SortInsideSegment(PointPair edge, List <Point> list)
 {
     System.Diagnostics.Debug.Assert(list.Count > 0, "an edge should not be present with an empty list");
     list.Sort((a, b) => (a - edge.First).Length.CompareTo((b - edge.First).Length));
 }
Exemplo n.º 38
0
 private bool HasError(PointPair pointPair)
 {
     return(HasError(pointPair, null));
 }
 void IntersectTwoEdges(PointPair a, PointPair b, Dictionary<PointPair, List<Point>> splittingPoints, RTree<Point> tree) {
     Point x;
     if (LineSegment.Intersect(a.First, a.Second, b.First, b.Second, out x)) {
         Point vertex = FindExistingVertexOrCreateNew(tree, x);
         if (AddVertexToSplittingList(a, splittingPoints, vertex) |
         AddVertexToSplittingList(b, splittingPoints, vertex))
             foundCrossings.Insert(vertex);
     }
 }
Exemplo n.º 40
0
 public PointPair ToPhysical(PointPair logicalPointPair)
 {
     return new PointPair(ToPhysical(logicalPointPair.P1), ToPhysical(logicalPointPair.P2));
 }
 void SortInsideSegment(PointPair edge, List<Point> list) {
     System.Diagnostics.Debug.Assert(list.Count > 0, "an edge should not be present with an empty list");
     list.Sort((a, b) => (a - edge.First).Length.CompareTo((b - edge.First).Length));
 }
Exemplo n.º 42
0
 protected PointPair ToPhysical(PointPair pointPair)
 {
     return Drawing.CoordinateSystem.ToPhysical(pointPair);
 }
Exemplo n.º 43
0
 public PointPair ToLogical(PointPair pointPair)
 {
     var result = new PointPair(ToLogical(pointPair.P1), ToLogical(pointPair.P2));
     if (result.P1.X > result.P2.X)
     {
         result = result.Reverse;
     }
     if (result.P1.Y > result.P2.Y)
     {
         var temp = result.P2.Y;
         result.P2.Y = result.P1.Y;
         result.P1.Y = temp;
     }
     return result;
 }
 int SegmentIntersectsSide(Point a, Point b)
 {
     var segment = new PointPair(a, b);
     for (int i = 0; i < N; i++)
     {
         Point intersection = Math.GetIntersectionOfSegments(segment, Polygon.GetSegment(i));
         if (intersection.Exists()
             && Polygon[i] != Start
             && Polygon[i] != End
             && Polygon[i.RotateNext(N)] != Start
             && Polygon[i.RotateNext(N)] != End)
         {
             return i;
         }
     }
     return -1;
 }
Exemplo n.º 45
0
 /// <summary>
 /// Copy the properties of this <see cref="ZedGraphWebPointPair"/> to the specified
 /// <see cref="PointPair"/> object.
 /// </summary>
 /// <param name="item">The destination <see cref="PointPair"/> object</param>
 internal void CopyTo( PointPair item )
 {
     item.X = this.X;
     item.Y = this.Y;
     item.Z = this.Z;
 }
        /// <summary>
        /// Get the index of line on the edge (u->v) and node u
        /// </summary>
#if SHARPKIT //http://code.google.com/p/sharpkit/issues/detail?id=203
        //SharpKit/Colin - Interface implementations
        public int GetLineIndexInOrder(Station u, Station v, Metroline Metroline) {
#else
        int IMetroMapOrderingAlgorithm.GetLineIndexInOrder(Station u, Station v, Metroline Metroline) {
#endif
            var edge = new PointPair(u.Position, v.Position);
            var reversed = u.Position != edge.First;
            var d = bundles[edge].LineIndexInOrder;
            return !reversed ? d[Metroline] : d.Count - 1 - d[Metroline];
        }


        
        /// <summary>
        /// Do the main job
        /// </summary>
        void BuildOrder() {
            bundles = new Dictionary<PointPair, PointPairOrder>();
            
            //initialization
            foreach (var Metroline in Metrolines) {
                for (var p = Metroline.Polyline.StartPoint; p.Next != null; p = p.Next) {
                    var e = new PointPair(p.Point, p.Next.Point);
                    PointPairOrder li;
                    if (!bundles.TryGetValue(e, out li))
                        bundles[e] = li = new PointPairOrder();
                    li.Add(Metroline);
                }
            }

            foreach (var edge in bundles)
                BuildOrder(edge.Key, edge.Value);
        }

        /// <summary>
        /// Build order for edge (u->v)
        /// </summary>
        void BuildOrder(PointPair pair, PointPairOrder order) {
            if (order.orderFixed) return;
            order.Metrolines.Sort((line0, line1) => CompareLines(line0, line1, pair.First, pair.Second));

            //save order
            order.orderFixed = true;
            order.LineIndexInOrder = new Dictionary<Metroline, int>();
            for (int i = 0; i < order.Metrolines.Count; i++)
                order.LineIndexInOrder[order.Metrolines[i]] = i;
        }




        /// <summary>
        /// Compare two lines on station u with respect to edge (u->v)
        /// </summary>
        int CompareLines(Metroline ml0, Metroline ml1, Point u, Point v) {
            PolylinePoint polylinePoint0;
            Func<PolylinePoint, PolylinePoint> next0;
            Func<PolylinePoint, PolylinePoint> prev0;
            FindStationOnLine(u, v, ml0, out polylinePoint0, out next0, out prev0);
            PolylinePoint polylinePoint1;
            Func<PolylinePoint, PolylinePoint> next1;
            Func<PolylinePoint, PolylinePoint> prev1;
            FindStationOnLine(u, v, ml1, out polylinePoint1, out next1, out prev1);

            //go backward
            var p0 = polylinePoint0;
            var p1 = polylinePoint1;
            PolylinePoint p00, p11 = null;

            while ((p00 = prev0(p0)) != null && (p11 = prev1(p1)) != null && p00.Point == p11.Point) {
                var edge = new PointPair(p00.Point, p0.Point);
                if (bundles[edge].orderFixed) {
                    return CompareOnFixedOrder(edge, ml0, ml1, p00.Point !=edge.First);
                }
                p0 = p00;
                p1 = p11;
            }

            if (p00 != null && p11 != null) {   //we have a backward fork
                var forkBase = p0.Point;
                return IsLeft(next0(p0).Point - forkBase,
                              p00.Point - forkBase,
                              p11.Point - forkBase);
            }

            //go forward
            p0 = polylinePoint0;
            p1 = polylinePoint1;
            while ((p00 = next0(p0)) != null && (p11 = next1(p1)) != null && p00.Point == p11.Point) {
                var edge = new PointPair(p00.Point, p0.Point);

                if (bundles[edge].orderFixed)
                    return CompareOnFixedOrder(edge, ml0, ml1, p0.Point!=edge.First);
                p0 = p00;
                p1 = p11;
            }


            if (p00 != null && p11 != null) {//compare forward fork
                var forkBase = p0.Point;
                return -IsLeft(prev0(p0).Point - forkBase,
                              p00.Point - forkBase,
                              p11.Point - forkBase);
            }

            //these are multiple edges
            return ml0.Index.CompareTo(ml1.Index);
        }

        int CompareOnFixedOrder(PointPair edge, Metroline ml0, Metroline ml1, bool reverse) {
            var mlToIndex = bundles[edge].LineIndexInOrder;
            int r = reverse ? -1 : 1;
            return r * mlToIndex[ml0].CompareTo(mlToIndex[ml1]);
        }


        /// <summary>
        /// Reimplement it in more efficient way!!! (cache indexes)
        /// </summary>
        void FindStationOnLine(Point u, Point v, Metroline Metroline, out PolylinePoint polyPoint, out Func<PolylinePoint, PolylinePoint> next,
            out Func<PolylinePoint, PolylinePoint> prev) {

            for (var p = Metroline.Polyline.StartPoint; p.Next != null; p = p.Next) {
                if (p.Point == u && p.Next.Point == v) {
                    next = Next;
                    prev = Prev;
                    polyPoint = p;
                    return;
                }

                if (p.Point == v && p.Next.Point == u) {
                    prev = Next;
                    next = Prev;
                    polyPoint = p.Next;
                    return;
                }
            }
            throw new InvalidOperationException();
        }
Exemplo n.º 47
0
        private void HandleEditDrag(Point mousePt)
        {
            // get the scale values that correspond to the current point
            double curX, curY;
            _dragPane.ReverseTransform(mousePt, _dragCurve.IsX2Axis, _dragCurve.IsY2Axis,
                                       _dragCurve.YAxisIndex, out curX, out curY);
            double startX, startY;
            _dragPane.ReverseTransform(_dragStartPt, _dragCurve.IsX2Axis, _dragCurve.IsY2Axis,
                                       _dragCurve.YAxisIndex, out startX, out startY);

            // calculate the new scale values for the point
            PointPair newPt = new PointPair(_dragStartPair);

            Scale xScale = _dragCurve.GetXAxis(_dragPane)._scale;
            if (_isEnableHEdit)
                newPt.X = xScale.DeLinearize(xScale.Linearize(newPt.X) +
                                             xScale.Linearize(curX) - xScale.Linearize(startX));

            Scale yScale = _dragCurve.GetYAxis(_dragPane)._scale;
            if (_isEnableVEdit)
                newPt.Y = yScale.DeLinearize(yScale.Linearize(newPt.Y) +
                                             yScale.Linearize(curY) - yScale.Linearize(startY));

            // save the data back to the point list
            IPointListEdit list = _dragCurve.Points as IPointListEdit;
            if (list != null)
                list[_dragIndex] = newPt;

            // force a redraw
            Refresh();
        }
Exemplo n.º 48
0
 public override PointAnnotation AnnotatePoint(PointPair point)
 {
     return(null);
 }
Exemplo n.º 49
0
        public PointPair this[int index]
        {
            get
            {
                int count = IPointListCount;
                if (generatedPointPairs == null)
                {
                    generatedPointPairs = new PointPair[count];
                }
                if (generatedPointPairs.Length != count)
                {
                    Array.Resize(ref generatedPointPairs, count);
                }
                if (generatedPointPairs[index] == null)
                {
                    generatedPointPairs[index] = new PointPair();
                }
                PointPair generatedPointPair = generatedPointPairs[index];

                /*switch (XType)
                 * {
                 *  case SiriusAxisValueType.Date_t:
                 *      generatedPointPair.X = RunCore.run2[Date, index].ToOADate();
                 *      break;
                 *  case SiriusAxisValueType.DayLength:
                 *      generatedPointPair.X = (double)RunCore.run2[DayLength, index];
                 *      break;
                 *  case SiriusAxisValueType.DayLength_Delta:
                 *      generatedPointPair.X = (double)RunCore.run2[DayLength, index, Delta];
                 *      break;
                 *  case SiriusAxisValueType.GrowthPhase:
                 *      generatedPointPair.X = (double)((int)RunCore.run2[GrowthPhase, index, Crop]);
                 *      break;
                 *  case SiriusAxisValueType.t:
                 *      generatedPointPair.X = index;
                 *      break;
                 *  case SiriusAxisValueType.T_t_Air:
                 *      generatedPointPair.X = (double)RunCore.run2[T, index, Air, Mean];
                 *      break;
                 *  case SiriusAxisValueType.T_t_LeafLayer:
                 *      generatedPointPair.X = (double)RunCore.run2[T, index, Leaf, Mean];
                 *      break;
                 *  case SiriusAxisValueType.T_t_SoilLayer:
                 *      generatedPointPair.X = (double)RunCore.run2[T, index, Soil, Mean];
                 *      break;
                 *  case SiriusAxisValueType.TT_t_Air:
                 *      generatedPointPair.X = (double)RunCore.run2[TT, index, Air];
                 *      break;
                 *  case SiriusAxisValueType.TT_t_LeafLayer:
                 *      generatedPointPair.X = (double)RunCore.run2[TT, index, Leaf];
                 *      break;
                 *  case SiriusAxisValueType.TT_t_SoilLayer:
                 *      generatedPointPair.X = (double)RunCore.run2[TT, index, Soil];
                 *      break;
                 * }
                 * switch (YType)
                 * {
                 *  case SiriusAxisValueType.Date_t:
                 *      generatedPointPair.Y = RunCore.run2[Date, index].ToOADate();
                 *      break;
                 *  case SiriusAxisValueType.DayLength:
                 *      generatedPointPair.Y = (double)RunCore.run2[DayLength, index];
                 *      break;
                 *  case SiriusAxisValueType.DayLength_Delta:
                 *      generatedPointPair.Y = (double)RunCore.run2[DayLength, index, Delta];
                 *      break;
                 *  case SiriusAxisValueType.GrowthPhase:
                 *      generatedPointPair.Y = (double)((int)RunCore.run2[GrowthPhase, index, Crop]);
                 *      break;
                 *  case SiriusAxisValueType.t:
                 *      generatedPointPair.Y = index;
                 *      break;
                 *  case SiriusAxisValueType.T_t_Air:
                 *      generatedPointPair.Y = (double)RunCore.run2[T, index, Air, Mean];
                 *      break;
                 *  case SiriusAxisValueType.T_t_LeafLayer:
                 *      generatedPointPair.Y = (double)RunCore.run2[T, index, Leaf, Mean];
                 *      break;
                 *  case SiriusAxisValueType.T_t_SoilLayer:
                 *      generatedPointPair.Y = (double)RunCore.run2[T, index, Soil, Mean];
                 *      break;
                 *  case SiriusAxisValueType.TT_t_Air:
                 *      generatedPointPair.Y = (double)RunCore.run2[TT, index, Air];
                 *      break;
                 *  case SiriusAxisValueType.TT_t_LeafLayer:
                 *      generatedPointPair.Y = (double)RunCore.run2[TT, index, Leaf];
                 *      break;
                 *  case SiriusAxisValueType.TT_t_SoilLayer:
                 *      generatedPointPair.Y = (double)RunCore.run2[TT, index, Soil];
                 *      break;
                 * }*/
                return(generatedPointPair);
            }
        }
Exemplo n.º 50
0
        private PointPair[] update(string wsp = null, List<ArchiveInfo> schema = null)
        {
            wsp = wsp ?? db;
            schema = schema ?? new List<ArchiveInfo>() { new ArchiveInfo(1, 20) };

            var numDataPoints = schema[0].Points;

            Whipser.Create(wsp, schema);

            var tn = DateTime.UtcNow.ToUnixTime() - numDataPoints;
            var data = new PointPair[numDataPoints];
            for (int i = 0; i < numDataPoints; i++)
            {
                //data[i] = new PointPair(tn + 1 + i, i * 10);
                data[i] = new PointPair(tn + 1 + i, random.Next(1000) * 10);
            }

            //Whipser.Update(wsp, data[0].value, data[0].Timestamp);
            //Whipser.UpdateMany(wsp, data);
            foreach (var item in data)
            {
                Whipser.Update(wsp, item.value, item.Timestamp);
            }

            // add more fake data
            Thread.Sleep(1000);
            Whipser.Update(wsp, random.Next(1000) * 10);
            Thread.Sleep(1000);
            Whipser.Update(wsp, random.Next(1000) * 10);

            return data;
        }