public static Vertex Rung4(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "Rung4.html"; Edge e; string NextVertexName = "TraditionalCrises_Rung5"; e = new Edge(d); e.State.VertexName = NextVertexName; //e.State.Stakes += 5; e.HTML = "A public and irrevocable increase in the stakes"; v.Edges.Add(e); e = new Edge(d); e.State.VertexName = NextVertexName; //e.State.PublicAwareness += 20; e.HTML = "Officially inspire newspaper stories to the effect that the chief of state takes a serious view of the matter."; v.Edges.Add(e); return v; }
public static Vertex Intro(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "Intro.html"; Edge e; e = new Edge(d); e.State.VertexName = "SubcrisisManeuvering_Index"; e.State.Rank1.InHand += 1; e.State.Rank2_dipl.InHand += 2; e.State.Rank2_econ.InHand += 1; e.State.Rank2_poli.InHand += 1; e.HTML = "Assume political control over crisis. Communicate with allies' political leaders, confirm a firm leadership position in NATO and with non-NATO allies. Establish continuous high level lines of communication. Summon political advisors."; v.Edges.Add(e); e = new Edge(d); e.State.VertexName = "SubcrisisManeuvering_Index"; e.Disabled = true; e.State.Rank3.InHand += 1; e.HTML = "Summon military leadership. Confirm command and control links over allies military leadership. Immediately address the nation."; v.Edges.Add(e); return v; }
public void TestAddingEdgeFiresCollectionChangedEvent() { bool eventFired = false; NotifyCollectionChangedAction action = NotifyCollectionChangedAction.Reset; GraphData g = new GraphData("scope"); Node source = new Node("Source"); Node target = new Node("Target"); Edge edge = new Edge(source, target); // TODO: This test is invalid because added Node objects to the collection will fire the same event g.CollectionChanged += (sender, e) => { action = e.Action; eventFired = true; }; EnqueueCallback(() => g.AddNode(source)); EnqueueCallback(() => g.AddNode(target)); EnqueueCallback(() => g.AddEdge(edge)); EnqueueConditional(() => eventFired); EnqueueCallback(() => Assert.IsTrue(eventFired)); EnqueueCallback(() => Assert.AreEqual<NotifyCollectionChangedAction>(NotifyCollectionChangedAction.Add, action)); EnqueueTestComplete(); }
public GraphData Build(DotNetProjectGraphDiscoveryService service, ICollection<CsprojFileData> projects, ICollection<SolutionFileData> solutions) { var graphData = new GraphData(); // crete nodes from csproj data var projectsWithNode = projects.Select(fd => new { FileData = fd, Node = CreateNodeFromCsprojFileData(fd, NodeState.Normal) }).ToList(); var solutionsWithNode = solutions.Select(fd => new { FileData = fd, Node = CreateNodeFromSolutionFileData(fd, NodeState.Normal) }).ToList(); // references graphData.References = new List<ReferenceDefinition>(); foreach (var item in solutionsWithNode) { var directory = Path.GetDirectoryName(item.FileData.FileName); foreach (var reference in item.FileData.Projects) { // resolve path and find csproj file var referencedNode = projectsWithNode.FirstOrDefault(i => i.FileData != null && string.Equals(i.FileData.FileName, reference.FullPath, StringComparison.OrdinalIgnoreCase)); if (referencedNode == null) { // not found - create "not found" node bool outOfBound = PathHelper.IsDescendant(service.FolderPathFullPath, reference.FullPath); var missingReferenceData = new CsprojFileData() { FileName = reference.FullPath }; referencedNode = new { FileData = missingReferenceData, Node = CreateNodeFromCsprojFileData(missingReferenceData, outOfBound ? NodeState.OutOfBound : NodeState.NotFound) }; projectsWithNode.Add(referencedNode); } // create reference graphData.References.Add(new ReferenceDefinition() { NodeFromId = item.Node.Id, NodeToId = referencedNode.Node.Id }); } } // nodes graphData.Nodes = projectsWithNode.Select(d => d.Node) .Union(solutionsWithNode.Select(d => d.Node)) .ToDictionary(d => d.Id); return graphData; }
public static Vertex Index(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "Index.html"; Edge e; return v; }
private static Vertex GetVertex(string s, GraphData data) { init(); Vertex v = Vertexes[s](data); v.Name = s; for (int i = 0; i < v.Edges.Count; ++i) { v.Edges[i].Name = $"{v.Name}.{i}"; } return v; }
/// <summary> /// /// </summary> /// <param name="numberOfNodes"></param> /// <param name="numberOfEdges"></param> /// <returns></returns> public GraphData GenerateGraph(string scope, int numberOfNodes, int numberOfEdges) { generatedGraph = new GraphData(scope); List<Node> nodes = GenerateNodes(numberOfNodes); List<IEdge> edges = GenerateEdges(numberOfEdges, nodes); generatedGraph.AddNodes(nodes); generatedGraph.AddEdges(edges); return generatedGraph; }
public static Vertex Initial(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "Initial.html"; Edge e = new Edge(d); e = new Edge(d); e.State.VertexName = "Start_Settings"; e.HTML = "Okay!"; v.Edges.Add(e); return v; }
public void TestAddEdge() { GraphData g = new GraphData("scope"); Node source = new Node("Source"); Node target = new Node("Target"); Edge edge = new Edge(source, target); g.AddNode(source); g.AddNode(target); g.AddEdge(edge); Assert.IsTrue(g.ContainsEdge(edge)); }
public static Vertex Result(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "Result.html"; //soviets get to respond here. All possibilities will be listed, //What the soviets do is based on variables. They don't know whats in your hand but they do know what you have played. Edge e = new Edge(d); e.State.VertexName = "SubcrisisManeuvering_Index"; e.HTML = "Soviet Action!"; v.Edges.Add(e); return v; }
public static Vertex Settings(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "Settings.html"; Edge e; e = new Edge(d); e.State.VertexName = "Start_Settings"; if (!e.State.ShowDebug) { e.State.ShowDebug = true; e.HTML = "Turn Debug Mode on."; } else { e.State.ShowDebug = false; e.HTML = "Turn Debug Mode off."; } v.Edges.Add(e); e = new Edge(d); e.State.VertexName = "Start_Settings"; if (!e.State.ShowDelta) { e.State.ShowDelta = true; e.HTML = "Show Deltas Mode on."; } else { e.State.ShowDelta = false; e.HTML = "Show Deltas Mode off."; } v.Edges.Add(e); e = new Edge(d); e.State.VertexName = "Start_Scenarios"; e.HTML = "Okay. I'm done changing settings."; v.Edges.Add(e); return v; }
public ActionResult DataForGraph() { List<GraphData> GraphData_list = new List<GraphData>(); DateTime firstday = DateTime.Parse("2012-08-10 10:04:24").Subtract(new TimeSpan(50,0,0,0)); Random rand = new Random(); for (int j = 0; j < 50; j++) { GraphData new_graphdata = new GraphData(); new_graphdata.date = firstday.Year+","+firstday.Month+","+firstday.Day; new_graphdata.hits = rand.Next(1,150).ToString(); new_graphdata.Visits = rand.Next(1, 150).ToString(); new_graphdata.views = rand.Next(1, 150).ToString(); GraphData_list.Add(new_graphdata); firstday = firstday.AddDays(1); } return Json(GraphData_list, JsonRequestBehavior.AllowGet); }
public static Vertex Scenarios(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "Scenarios.html"; Edge e = new Edge(d); e.State.VertexName = "FlashpointBerlin_Intro"; e.State.Title = "Flashpoint Berlin, 1965"; e.State.Nation = "the United States of America"; e.State.EnemyNation = "the Soviet Union"; e.State.DateTime = new DateTime(1965, 5, 1); e.State.EnemyLeader = "Leonid Brezhnev"; e.HTML = "Flashpoint Berlin, 1965"; v.Edges.Add(e); return v; }
void ProcessGraphData(GraphData data) { float newHeight = float.NegativeInfinity; foreach(DataPoint dp in data.dataPoints) newHeight = Mathf.Max(newHeight, dp.value); f_graphHeight = newHeight; if(goa_bars.Length > 0) { Debug.Log("Setting values but not labels"); foreach(DataPoint dp in data.dataPoints) { for(int i = 0; i < goa_bars.Length; i++) { if(goa_bars[i].GetComponent<Bar>().label == dp.label) { goa_bars[i].GetComponent<Bar>().setValue(dp.value); break; } } } } else { goa_bars = new GameObject[data.dataPoints.Length]; for(int i = 0; i < goa_bars.Length; i++) { DataPoint dp = data.dataPoints[i]; GameObject temp = (GameObject)Instantiate(BarFab); temp.transform.position = new Vector3((Settings.BarWidth + Settings.BarSeperation) * i, 0, 0); temp.GetComponent<Bar>().label = dp.label; temp.GetComponent<Bar>().setValue(dp.value); temp.transform.parent = transform; temp.renderer.material.color = KSJSON.me.parentCatColors[dp.label]; goa_bars[i] = temp; } } }
void Awake() { GameObject lineObject = new GameObject("Raw Line"); vertexList = new List<float>(lineResolution); data = new GraphData(pointHistorySize); /** * Initialize the point lists */ for(int i = 0; i < lineResolution; i++) vertexList.Add(0.0f); line = lineObject.AddComponent(typeof(LineRenderer)) as LineRenderer; usedCamera = linkedCamera != null ? linkedCamera : Camera.main; InvokeRepeating("PushVertex", 0.0f, 0.015f); }
public void Verify_Edge_Added_To_Physical_Graph_Once_All_Corresponding_Target_Nodes_Added() { int actualSourceEdges; int actualTargetEdges; int expectedSourceEdges = 1; int expectedTargetEdges = 1; INode temp1 = new Node("temp1"); // Hack because an exception is thrown if you attempt to add an edge to a graph if the graph doesn't have at least one node INode source = PrepareNode("Node1", ghostNode: true); INode target = PrepareNode("Node2", ghostNode: true); IEdge orphan = new Edge(source, target); IEdge actualSource; IEdge actualTarget; GraphData graphData = new GraphData("scope"); // Hack (see temp1 comment above) graphData.AddNode(temp1); // Add an edge with ghost nodes to the graph graphData.AddEdge(orphan); // Add the missing node source = PrepareNode("Node1", ghostNode: false); target = PrepareNode("Node2", ghostNode: false); graphData.AddNode(source); graphData.AddNode(target); // Get the actual count for nodes actualSourceEdges = graphData.Edges(source).Count(); actualTargetEdges = graphData.Edges(target).Count(); actualSource = graphData.Edges(source).FirstOrDefault(); actualTarget = graphData.Edges(target).FirstOrDefault(); Assert.AreEqual(expectedSourceEdges, actualSourceEdges); Assert.AreEqual(expectedTargetEdges, actualTargetEdges); Assert.AreEqual(orphan, actualSource); Assert.AreEqual(orphan, actualTarget); }
//--------------------------------------------------------------------- //constructors //--------------------------------------------------------------------- /// <summary> /// Initializes a new instance of the GraphCanvas class. /// </summary> protected GraphCanvas(GraphData data, int width, int height, Color backgroundColor) { if (data == null) { return; } if (width <= 0) { width = 1; } if (height <= 0) { height = 1; } #if GRAPHDEBUG //debug switch debugMode = false; debugBrush = new SolidBrush(Color.LightGray); debugPen = new Pen(debugBrush, 1); //debug #endif _graphData = data; _bitmap = new Bitmap(width, height, PixelFormat.Format32bppPArgb); _graphics = Graphics.FromImage((Image) _bitmap); _graphics.SmoothingMode = SmoothingMode.AntiAlias; backgroundColor = Color.FromArgb(20, backgroundColor); _graphics.CompositingQuality = CompositingQuality.HighQuality; _graphics.CompositingMode = CompositingMode.SourceOver; _graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; _drawingElements = new ArrayList(); _titleFont = new Font(SystemFonts.DefaultFont.FontFamily, SystemFonts.DefaultFont.Size + 2, FontStyle.Bold); _legendFont = new Font(SystemFonts.DefaultFont.FontFamily, SystemFonts.DefaultFont.Size, FontStyle.Regular); }
/// <summary> /// event handler that is called when the loadbutton is clicked, which picks a certain part of the data that is loaded and displays it correctly /// </summary> private void LoadButton_Clicked(object sender, EventArgs e) { if (picker.SelectedIndex != -1 && isLoading == false) { isLoading = true; var entry = neighbourhoodList.ElementAt(picker.SelectedIndex); var neighbourhood = entry.Item1; var data = entry.Item2; var trommelBars = new BarSeries { Title = "Hoeveelheid trommels", StrokeColor = OxyColors.Orange, StrokeThickness = 1 }; var theftBars = new BarSeries { Title = "Hoeveelheid diefstallen", StrokeColor = OxyColors.Green, StrokeThickness = 1 }; var children = layout.Children.Take(layout.Children.Count - 1); IList <View> newChildren = new List <View>(); foreach (var item in children) { newChildren.Add(item); } var graphData = new GraphData <int>("diefstallen en fietstrommels per maand", "Trommels", "Buurt", new List <int>()); GraphFactory <int> graphFactory = new GraphFactory <int>(); var newBarModel = graphFactory.createGraph(GraphType.Bar, new GraphEffect(), graphData); var categoryAxis = new CategoryAxis { Position = AxisPosition.Left, AbsoluteMinimum = 0 }; var valueAxis = new LinearAxis { Position = AxisPosition.Bottom, MinimumPadding = 0, MaximumPadding = 0.06, AbsoluteMinimum = 0 }; foreach (var item in neighbourhoodList) { if (item.Item1 == neighbourhood) { var labelList = new List <string>(); for (int i = 48; i > 0; i--) { labelList.Add(((i + 5) % 12 + 1).ToString() + " - " + (((int)(Math.Floor((float)i + 5) / 12) + 2009).ToString())); } for (int i = 0; i < labelList.Count * 2; i++) { if (i % 2 == 0) { categoryAxis.Labels.Add(labelList.ElementAt((int)Math.Ceiling((float)i / 2))); } else { categoryAxis.Labels.Add(""); } } for (int i = 0; i < 48; i++) { if (item.Item2.Count() > i) { theftBars.Items.Add(new BarItem { Value = item.Item2.ElementAt(i).Item1, Color = OxyPlot.OxyColors.Green }); theftBars.Items.Add(new BarItem { Value = 0 }); } else { theftBars.Items.Add(new BarItem { Value = 0 }); theftBars.Items.Add(new BarItem { Value = 0 }); } if (item.Item2.Count() > i) { trommelBars.Items.Add(new BarItem { Value = 0 }); trommelBars.Items.Add(new BarItem { Value = item.Item2.ElementAt(i).Item2, Color = OxyPlot.OxyColors.Orange }); } else { trommelBars.Items.Add(new BarItem { Value = 0 }); trommelBars.Items.Add(new BarItem { Value = 0 }); } } newBarModel.Series.Add(theftBars); newBarModel.Series.Add(trommelBars); break; } } newBarModel.Axes.Add(categoryAxis); newBarModel.Axes.Add(valueAxis); var newLayout = new StackLayout { Padding = new Thickness(50, 50, 50, 50) }; foreach (var item in newChildren) { newLayout.Children.Add(item); } var contentPage = new ContentPage { Content = new PlotView { BackgroundColor = Color.White, Model = newBarModel, HeightRequest = 0.5, WidthRequest = 0.5, }, BackgroundColor = Color.White }; var selectPage = new StackLayout { Padding = new Thickness(50, 50, 50, 50) }; foreach (var item in newChildren) { selectPage.Children.Add(item); } Children.Clear(); Children.Add(new ContentPage { Content = selectPage }); Navigation.PushModalAsync(contentPage); isLoading = false; } }
/// <summary> /// calling this method loads the this.content of the page, showing the actual info /// </summary> private void ShowData() { neighbourhoodList = new List <Tuple <string, List <Tuple <int, int, int, int> > > >(); foreach (var neighbourhood in combinationList) { List <Tuple <int, int, int, int> > rows = new List <Tuple <int, int, int, int> >(); foreach (var item in neighbourhood.Rows) { rows.Add(new Tuple <int, int, int, int>(item.Thefts, item.Trommels, item.Month, item.Year)); } neighbourhoodList.Add(new Tuple <string, List <Tuple <int, int, int, int> > >(neighbourhood.Neighbourhood, rows)); } var graphData = new GraphData <int>("Fietstrommels en diefstallen per maand", "Trommels", "Buurt", new List <int>()); GraphFactory <int> graphFactory = new GraphFactory <int>(); var barModel = graphFactory.createGraph(GraphType.Bar, new GraphEffect(), graphData); var trommelBars = new BarSeries { Title = "Hoeveelheid trommels", StrokeColor = OxyColors.Orange, FillColor = OxyColors.Orange, StrokeThickness = 1 }; var theftBars = new BarSeries { Title = "Hoeveelheid diefstallen", StrokeColor = OxyColors.Green, FillColor = OxyColors.Green, StrokeThickness = 1 }; var categoryAxis = new CategoryAxis { Position = AxisPosition.Left }; var valueAxis = new LinearAxis { Position = AxisPosition.Bottom, AbsoluteMinimum = 0 }; for (int i = 0; i < neighbourhoodList.Count; i++) { neighbourhoodList.ElementAt(i).Item2.Sort(new TupleCompareClass().Compare); } barModel.Series.Add(trommelBars); barModel.Series.Add(theftBars); barModel.Axes.Add(categoryAxis); barModel.Axes.Add(valueAxis); barChart = new PlotView { BackgroundColor = Color.White, Model = barModel }; picker = new Picker { Title = "Buurten", VerticalOptions = LayoutOptions.Start }; foreach (var item in neighbourhoodList) { picker.Items.Add(item.Item1); } var getButton = new Button { Text = "Laad", VerticalOptions = LayoutOptions.Start }; getButton.Clicked += LoadButton_Clicked; layout = new StackLayout { Padding = new Thickness(50, 50, 50, 50), Children = { picker, getButton, barChart } }; Children.Clear(); var contentPage = new ContentPage { Content = layout }; Children.Add(contentPage); }
public void ShowGraph() { ClearGraph(); if (graphDataPlayer1.Count >= 1 && graphDataPlayer2.Count >= 1) { holder = Instantiate(HolderPrefb, Vector3.zero, Quaternion.identity) as GameObject; holder.name = "h2"; GraphData[] gd1 = new GraphData[graphDataPlayer1.Count]; GraphData[] gd2 = new GraphData[graphDataPlayer2.Count]; for (int i = 0; i < graphDataPlayer1.Count; i++) { GraphData gd = new GraphData(); gd.marbles = graphDataPlayer1[i].marbles; gd1[i] = gd; } for (int i = 0; i < graphDataPlayer2.Count; i++) { GraphData gd = new GraphData(); gd.marbles = graphDataPlayer2[i].marbles; gd2[i] = gd; } dataGap = GetDataGap(graphDataPlayer2.Count); int dataCount = 0; int gapLength = 1; float gap = 1.0f; bool flag = false; while (dataCount < graphDataPlayer2.Count) { if (dataGap > 1) { if ((dataCount + dataGap) == graphDataPlayer2.Count) { dataCount += dataGap - 1; flag = true; } else if ((dataCount + dataGap) > graphDataPlayer2.Count && !flag) { dataCount = graphDataPlayer2.Count - 1; flag = true; } else { dataCount += dataGap; if (dataCount == (graphDataPlayer2.Count - 1)) { flag = true; } } } else { dataCount += dataGap; } gapLength++; } if (graphDataPlayer2.Count > 13) { if (graphDataPlayer2.Count < 40) { gap = 13.0f / graphDataPlayer2.Count; } else if (graphDataPlayer2.Count >= 40) { gap = 13.0f / gapLength; } } ShowData(gd1, 1, gap); ShowData(gd2, 2, gap); } }
public void ToSubGraph() { var path = EditorUtility.SaveFilePanelInProject("Save Sub Graph", "New Shader Sub Graph", ShaderSubGraphImporter.Extension, ""); path = path.Replace(Application.dataPath, "Assets"); if (path.Length == 0) { return; } graphObject.RegisterCompleteObjectUndo("Convert To Subgraph"); var graphView = graphEditorView.graphView; var nodes = graphView.selection.OfType <MaterialNodeView>().Where(x => !(x.node is PropertyNode)).Select(x => x.node as AbstractMaterialNode).ToArray(); var bounds = Rect.MinMaxRect(float.PositiveInfinity, float.PositiveInfinity, float.NegativeInfinity, float.NegativeInfinity); foreach (var node in nodes) { var center = node.drawState.position.center; bounds = Rect.MinMaxRect( Mathf.Min(bounds.xMin, center.x), Mathf.Min(bounds.yMin, center.y), Mathf.Max(bounds.xMax, center.x), Mathf.Max(bounds.yMax, center.y)); } var middle = bounds.center; bounds.center = Vector2.zero; // Collect the property nodes and get the corresponding properties var propertyNodeGuids = graphView.selection.OfType <MaterialNodeView>().Where(x => (x.node is PropertyNode)).Select(x => ((PropertyNode)x.node).propertyGuid); var metaProperties = graphView.graph.properties.Where(x => propertyNodeGuids.Contains(x.guid)); var copyPasteGraph = new CopyPasteGraph( graphView.graph.assetGuid, graphView.selection.OfType <ShaderGroup>().Select(x => x.userData), graphView.selection.OfType <MaterialNodeView>().Where(x => !(x.node is PropertyNode)).Select(x => x.node as AbstractMaterialNode), graphView.selection.OfType <Edge>().Select(x => x.userData as IEdge), graphView.selection.OfType <BlackboardField>().Select(x => x.userData as AbstractShaderProperty), metaProperties); var deserialized = CopyPasteGraph.FromJson(JsonUtility.ToJson(copyPasteGraph, false)); if (deserialized == null) { return; } var subGraph = new GraphData { isSubGraph = true }; subGraph.path = "Sub Graphs"; var subGraphOutputNode = new SubGraphOutputNode(); { var drawState = subGraphOutputNode.drawState; drawState.position = new Rect(new Vector2(bounds.xMax + 200f, 0f), drawState.position.size); subGraphOutputNode.drawState = drawState; } subGraph.AddNode(subGraphOutputNode); var nodeGuidMap = new Dictionary <Guid, Guid>(); foreach (var node in deserialized.GetNodes <AbstractMaterialNode>()) { var oldGuid = node.guid; var newGuid = node.RewriteGuid(); nodeGuidMap[oldGuid] = newGuid; var drawState = node.drawState; drawState.position = new Rect(drawState.position.position - middle, drawState.position.size); node.drawState = drawState; subGraph.AddNode(node); } // figure out what needs remapping var externalOutputSlots = new List <IEdge>(); var externalInputSlots = new List <IEdge>(); foreach (var edge in deserialized.edges) { var outputSlot = edge.outputSlot; var inputSlot = edge.inputSlot; Guid remappedOutputNodeGuid; Guid remappedInputNodeGuid; var outputSlotExistsInSubgraph = nodeGuidMap.TryGetValue(outputSlot.nodeGuid, out remappedOutputNodeGuid); var inputSlotExistsInSubgraph = nodeGuidMap.TryGetValue(inputSlot.nodeGuid, out remappedInputNodeGuid); // pasting nice internal links! if (outputSlotExistsInSubgraph && inputSlotExistsInSubgraph) { var outputSlotRef = new SlotReference(remappedOutputNodeGuid, outputSlot.slotId); var inputSlotRef = new SlotReference(remappedInputNodeGuid, inputSlot.slotId); subGraph.Connect(outputSlotRef, inputSlotRef); } // one edge needs to go to outside world else if (outputSlotExistsInSubgraph) { externalInputSlots.Add(edge); } else if (inputSlotExistsInSubgraph) { externalOutputSlots.Add(edge); } } // Find the unique edges coming INTO the graph var uniqueIncomingEdges = externalOutputSlots.GroupBy( edge => edge.outputSlot, edge => edge, (key, edges) => new { slotRef = key, edges = edges.ToList() }); var externalInputNeedingConnection = new List <KeyValuePair <IEdge, AbstractShaderProperty> >(); foreach (var group in uniqueIncomingEdges) { var sr = group.slotRef; var fromNode = graphObject.graph.GetNodeFromGuid(sr.nodeGuid); var fromSlot = fromNode.FindOutputSlot <MaterialSlot>(sr.slotId); AbstractShaderProperty prop; switch (fromSlot.concreteValueType) { case ConcreteSlotValueType.Texture2D: prop = new TextureShaderProperty(); break; case ConcreteSlotValueType.Texture2DArray: prop = new Texture2DArrayShaderProperty(); break; case ConcreteSlotValueType.Texture3D: prop = new Texture3DShaderProperty(); break; case ConcreteSlotValueType.Cubemap: prop = new CubemapShaderProperty(); break; case ConcreteSlotValueType.Vector4: prop = new Vector4ShaderProperty(); break; case ConcreteSlotValueType.Vector3: prop = new Vector3ShaderProperty(); break; case ConcreteSlotValueType.Vector2: prop = new Vector2ShaderProperty(); break; case ConcreteSlotValueType.Vector1: prop = new Vector1ShaderProperty(); break; case ConcreteSlotValueType.Boolean: prop = new BooleanShaderProperty(); break; case ConcreteSlotValueType.Matrix2: prop = new Matrix2ShaderProperty(); break; case ConcreteSlotValueType.Matrix3: prop = new Matrix3ShaderProperty(); break; case ConcreteSlotValueType.Matrix4: prop = new Matrix4ShaderProperty(); break; case ConcreteSlotValueType.SamplerState: prop = new SamplerStateShaderProperty(); break; case ConcreteSlotValueType.Gradient: prop = new GradientShaderProperty(); break; default: throw new ArgumentOutOfRangeException(); } if (prop != null) { var materialGraph = (GraphData)graphObject.graph; var fromPropertyNode = fromNode as PropertyNode; var fromProperty = fromPropertyNode != null?materialGraph.properties.FirstOrDefault(p => p.guid == fromPropertyNode.propertyGuid) : null; prop.displayName = fromProperty != null ? fromProperty.displayName : fromSlot.concreteValueType.ToString(); subGraph.AddShaderProperty(prop); var propNode = new PropertyNode(); { var drawState = propNode.drawState; drawState.position = new Rect(new Vector2(bounds.xMin - 300f, 0f), drawState.position.size); propNode.drawState = drawState; } subGraph.AddNode(propNode); propNode.propertyGuid = prop.guid; foreach (var edge in group.edges) { subGraph.Connect( new SlotReference(propNode.guid, PropertyNode.OutputSlotId), new SlotReference(nodeGuidMap[edge.inputSlot.nodeGuid], edge.inputSlot.slotId)); externalInputNeedingConnection.Add(new KeyValuePair <IEdge, AbstractShaderProperty>(edge, prop)); } } } var uniqueOutgoingEdges = externalInputSlots.GroupBy( edge => edge.outputSlot, edge => edge, (key, edges) => new { slot = key, edges = edges.ToList() }); var externalOutputsNeedingConnection = new List <KeyValuePair <IEdge, IEdge> >(); foreach (var group in uniqueOutgoingEdges) { var outputNode = subGraph.outputNode as SubGraphOutputNode; AbstractMaterialNode node = graphView.graph.GetNodeFromGuid(group.edges[0].outputSlot.nodeGuid); MaterialSlot slot = node.FindSlot <MaterialSlot>(group.edges[0].outputSlot.slotId); var slotId = outputNode.AddSlot(slot.concreteValueType); var inputSlotRef = new SlotReference(outputNode.guid, slotId); foreach (var edge in group.edges) { var newEdge = subGraph.Connect(new SlotReference(nodeGuidMap[edge.outputSlot.nodeGuid], edge.outputSlot.slotId), inputSlotRef); externalOutputsNeedingConnection.Add(new KeyValuePair <IEdge, IEdge>(edge, newEdge)); } } File.WriteAllText(path, EditorJsonUtility.ToJson(subGraph)); AssetDatabase.ImportAsset(path); var loadedSubGraph = AssetDatabase.LoadAssetAtPath(path, typeof(SubGraphAsset)) as SubGraphAsset; if (loadedSubGraph == null) { return; } var subGraphNode = new SubGraphNode(); var ds = subGraphNode.drawState; ds.position = new Rect(middle - new Vector2(100f, 150f), Vector2.zero); subGraphNode.drawState = ds; graphObject.graph.AddNode(subGraphNode); subGraphNode.subGraphAsset = loadedSubGraph; foreach (var edgeMap in externalInputNeedingConnection) { graphObject.graph.Connect(edgeMap.Key.outputSlot, new SlotReference(subGraphNode.guid, edgeMap.Value.guid.GetHashCode())); } foreach (var edgeMap in externalOutputsNeedingConnection) { graphObject.graph.Connect(new SlotReference(subGraphNode.guid, edgeMap.Value.inputSlot.slotId), edgeMap.Key.inputSlot); } graphObject.graph.RemoveElements( graphView.selection.OfType <MaterialNodeView>().Select(x => x.node as AbstractMaterialNode), Enumerable.Empty <IEdge>(), Enumerable.Empty <GroupData>()); graphObject.graph.ValidateGraph(); }
public override void MouseLeftButtonUp(Point point, GraphData graphData) { isMoving = false; }
public void Verify_Edge_With_Two_Ghost_Nodes_Not_Added_To_Physical_Graph() { IEnumerable<IEdge> actualSourceEdges; IEnumerable<IEdge> actualTargetEdges; IEnumerable<IEdge> expectedSourceEdges = null; IEnumerable<IEdge> expectedTargetEdges = null; INode temp1 = new Node("temp1"); // Hack because an exception is thrown if you attempt to add an edge to a graph if the graph doesn't have at least one node INode source = PrepareNode("Node1", ghostNode: true); INode target = PrepareNode("Node2", ghostNode: true); IEdge orphan = new Edge(source, target); GraphData graphData = new GraphData("scope"); graphData.AddNode(temp1); // Hack (see temp1 comment above) // Add an edge with ghost nodes to the graph graphData.AddEdge(orphan); // Get the actual count for nodes actualSourceEdges = graphData.Edges(source); actualTargetEdges = graphData.Edges(target); Assert.AreEqual(expectedSourceEdges, actualSourceEdges); Assert.AreEqual(expectedTargetEdges, actualTargetEdges); }
public static Vertex Rung2_econ(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "Rung2_econ.html"; Edge e; string NextVertexName = "SubcrisisManeuvering_Result"; e = new Edge(d); e.State.VertexName = NextVertexName; e.State.PerceivedResolve += 5; e.State.PerceivedInflexibility += 5; e.HTML = "Make a moderate but unmistakable legal or economic reprisal"; v.Edges.Add(e); //Soviets respond by scuttling several in-progress trade deals. return v; }
public void ToSubGraph() { var graphView = graphEditorView.graphView; string path; string sessionStateResult = SessionState.GetString(k_PrevSubGraphPathKey, k_PrevSubGraphPathDefaultValue); string pathToOriginSG = Path.GetDirectoryName(AssetDatabase.GUIDToAssetPath(selectedGuid)); if (!sessionStateResult.Equals(k_PrevSubGraphPathDefaultValue)) { path = sessionStateResult; } else { path = pathToOriginSG; } path = EditorUtility.SaveFilePanelInProject("Save Sub Graph", "New Shader Sub Graph", ShaderSubGraphImporter.Extension, "", path); path = path.Replace(Application.dataPath, "Assets"); if (path.Length == 0) { return; } var nodes = graphView.selection.OfType <IShaderNodeView>().Where(x => !(x.node is PropertyNode || x.node is SubGraphOutputNode)).Select(x => x.node).Where(x => x.allowedInSubGraph).ToArray(); // Convert To Subgraph could create recursive reference loops if the target path already exists // Let's check for that here if (!string.IsNullOrEmpty(path)) { if (GraphUtil.CheckForRecursiveDependencyOnPendingSave(path, nodes.OfType <SubGraphNode>(), "Convert To SubGraph")) { return; } } graphObject.RegisterCompleteObjectUndo("Convert To Subgraph"); var bounds = Rect.MinMaxRect(float.PositiveInfinity, float.PositiveInfinity, float.NegativeInfinity, float.NegativeInfinity); foreach (var node in nodes) { var center = node.drawState.position.center; bounds = Rect.MinMaxRect( Mathf.Min(bounds.xMin, center.x), Mathf.Min(bounds.yMin, center.y), Mathf.Max(bounds.xMax, center.x), Mathf.Max(bounds.yMax, center.y)); } var middle = bounds.center; bounds.center = Vector2.zero; // Collect graph inputs var graphInputs = graphView.selection.OfType <BlackboardField>().Select(x => x.userData as ShaderInput); // Collect the property nodes and get the corresponding properties var propertyNodes = graphView.selection.OfType <IShaderNodeView>().Where(x => (x.node is PropertyNode)).Select(x => ((PropertyNode)x.node).property); var metaProperties = graphView.graph.properties.Where(x => propertyNodes.Contains(x)); // Collect the keyword nodes and get the corresponding keywords var keywordNodes = graphView.selection.OfType <IShaderNodeView>().Where(x => (x.node is KeywordNode)).Select(x => ((KeywordNode)x.node).keyword); var metaKeywords = graphView.graph.keywords.Where(x => keywordNodes.Contains(x)); var copyPasteGraph = new CopyPasteGraph(graphView.selection.OfType <ShaderGroup>().Select(x => x.userData), graphView.selection.OfType <IShaderNodeView>().Where(x => !(x.node is PropertyNode || x.node is SubGraphOutputNode)).Select(x => x.node).Where(x => x.allowedInSubGraph).ToArray(), graphView.selection.OfType <Edge>().Select(x => x.userData as Graphing.Edge), graphInputs, metaProperties, metaKeywords, graphView.selection.OfType <StickyNote>().Select(x => x.userData), true); // why do we serialize and deserialize only to make copies of everything in the steps below? // is this just to clear out all non-serialized data? var deserialized = CopyPasteGraph.FromJson(MultiJson.Serialize(copyPasteGraph), graphView.graph); if (deserialized == null) { return; } var subGraph = new GraphData { isSubGraph = true, path = "Sub Graphs" }; var subGraphOutputNode = new SubGraphOutputNode(); { var drawState = subGraphOutputNode.drawState; drawState.position = new Rect(new Vector2(bounds.xMax + 200f, 0f), drawState.position.size); subGraphOutputNode.drawState = drawState; } subGraph.AddNode(subGraphOutputNode); subGraph.outputNode = subGraphOutputNode; // Always copy deserialized keyword inputs foreach (ShaderKeyword keyword in deserialized.metaKeywords) { var copiedInput = (ShaderKeyword)keyword.Copy(); subGraph.SanitizeGraphInputName(copiedInput); subGraph.SanitizeGraphInputReferenceName(copiedInput, keyword.overrideReferenceName); subGraph.AddGraphInput(copiedInput); // Update the keyword nodes that depends on the copied keyword var dependentKeywordNodes = deserialized.GetNodes <KeywordNode>().Where(x => x.keyword == keyword); foreach (var node in dependentKeywordNodes) { node.owner = graphView.graph; node.keyword = copiedInput; } } foreach (GroupData groupData in deserialized.groups) { subGraph.CreateGroup(groupData); } foreach (var node in deserialized.GetNodes <AbstractMaterialNode>()) { var drawState = node.drawState; drawState.position = new Rect(drawState.position.position - middle, drawState.position.size); node.drawState = drawState; // Checking if the group guid is also being copied. // If not then nullify that guid if (node.group != null && !subGraph.groups.Contains(node.group)) { node.group = null; } subGraph.AddNode(node); } foreach (var note in deserialized.stickyNotes) { if (note.group != null && !subGraph.groups.Contains(note.group)) { note.group = null; } subGraph.AddStickyNote(note); } // figure out what needs remapping var externalOutputSlots = new List <Graphing.Edge>(); var externalInputSlots = new List <Graphing.Edge>(); foreach (var edge in deserialized.edges) { var outputSlot = edge.outputSlot; var inputSlot = edge.inputSlot; var outputSlotExistsInSubgraph = subGraph.ContainsNode(outputSlot.node); var inputSlotExistsInSubgraph = subGraph.ContainsNode(inputSlot.node); // pasting nice internal links! if (outputSlotExistsInSubgraph && inputSlotExistsInSubgraph) { subGraph.Connect(outputSlot, inputSlot); } // one edge needs to go to outside world else if (outputSlotExistsInSubgraph) { externalInputSlots.Add(edge); } else if (inputSlotExistsInSubgraph) { externalOutputSlots.Add(edge); } } // Find the unique edges coming INTO the graph var uniqueIncomingEdges = externalOutputSlots.GroupBy( edge => edge.outputSlot, edge => edge, (key, edges) => new { slotRef = key, edges = edges.ToList() }); var externalInputNeedingConnection = new List <KeyValuePair <IEdge, AbstractShaderProperty> >(); var amountOfProps = uniqueIncomingEdges.Count(); const int height = 40; const int subtractHeight = 20; var propPos = new Vector2(0, -((amountOfProps / 2) + height) - subtractHeight); foreach (var group in uniqueIncomingEdges) { var sr = group.slotRef; var fromNode = sr.node; var fromSlot = sr.slot; var materialGraph = graphObject.graph; var fromProperty = fromNode is PropertyNode fromPropertyNode ? materialGraph.properties.FirstOrDefault(p => p == fromPropertyNode.property) : null; AbstractShaderProperty prop; switch (fromSlot.concreteValueType) { case ConcreteSlotValueType.Texture2D: prop = new Texture2DShaderProperty(); break; case ConcreteSlotValueType.Texture2DArray: prop = new Texture2DArrayShaderProperty(); break; case ConcreteSlotValueType.Texture3D: prop = new Texture3DShaderProperty(); break; case ConcreteSlotValueType.Cubemap: prop = new CubemapShaderProperty(); break; case ConcreteSlotValueType.Vector4: prop = new Vector4ShaderProperty(); break; case ConcreteSlotValueType.Vector3: prop = new Vector3ShaderProperty(); break; case ConcreteSlotValueType.Vector2: prop = new Vector2ShaderProperty(); break; case ConcreteSlotValueType.Vector1: prop = new Vector1ShaderProperty(); break; case ConcreteSlotValueType.Boolean: prop = new BooleanShaderProperty(); break; case ConcreteSlotValueType.Matrix2: prop = new Matrix2ShaderProperty(); break; case ConcreteSlotValueType.Matrix3: prop = new Matrix3ShaderProperty(); break; case ConcreteSlotValueType.Matrix4: prop = new Matrix4ShaderProperty(); break; case ConcreteSlotValueType.SamplerState: prop = new SamplerStateShaderProperty(); break; case ConcreteSlotValueType.Gradient: prop = new GradientShaderProperty(); break; case ConcreteSlotValueType.VirtualTexture: prop = new VirtualTextureShaderProperty() { // also copy the VT settings over from the original property (if there is one) value = (fromProperty as VirtualTextureShaderProperty)?.value ?? new SerializableVirtualTexture() }; break; default: throw new ArgumentOutOfRangeException(); } prop.displayName = fromProperty != null ? fromProperty.displayName : fromSlot.concreteValueType.ToString(); prop.displayName = GraphUtil.SanitizeName(subGraph.addedInputs.Select(p => p.displayName), "{0} ({1})", prop.displayName); subGraph.AddGraphInput(prop); var propNode = new PropertyNode(); { var drawState = propNode.drawState; drawState.position = new Rect(new Vector2(bounds.xMin - 300f, 0f) + propPos, drawState.position.size); propPos += new Vector2(0, height); propNode.drawState = drawState; } subGraph.AddNode(propNode); propNode.property = prop; foreach (var edge in group.edges) { subGraph.Connect( new SlotReference(propNode, PropertyNode.OutputSlotId), edge.inputSlot); externalInputNeedingConnection.Add(new KeyValuePair <IEdge, AbstractShaderProperty>(edge, prop)); } } var uniqueOutgoingEdges = externalInputSlots.GroupBy( edge => edge.outputSlot, edge => edge, (key, edges) => new { slot = key, edges = edges.ToList() }); var externalOutputsNeedingConnection = new List <KeyValuePair <IEdge, IEdge> >(); foreach (var group in uniqueOutgoingEdges) { var outputNode = subGraph.outputNode as SubGraphOutputNode; AbstractMaterialNode node = group.edges[0].outputSlot.node; MaterialSlot slot = node.FindSlot <MaterialSlot>(group.edges[0].outputSlot.slotId); var slotId = outputNode.AddSlot(slot.concreteValueType); var inputSlotRef = new SlotReference(outputNode, slotId); foreach (var edge in group.edges) { var newEdge = subGraph.Connect(edge.outputSlot, inputSlotRef); externalOutputsNeedingConnection.Add(new KeyValuePair <IEdge, IEdge>(edge, newEdge)); } } if (FileUtilities.WriteShaderGraphToDisk(path, subGraph)) { AssetDatabase.ImportAsset(path); } // Store path for next time if (!pathToOriginSG.Equals(Path.GetDirectoryName(path))) { SessionState.SetString(k_PrevSubGraphPathKey, Path.GetDirectoryName(path)); } else { // Or continue to make it so that next time it will open up in the converted-from SG's directory SessionState.EraseString(k_PrevSubGraphPathKey); } var loadedSubGraph = AssetDatabase.LoadAssetAtPath(path, typeof(SubGraphAsset)) as SubGraphAsset; if (loadedSubGraph == null) { return; } var subGraphNode = new SubGraphNode(); var ds = subGraphNode.drawState; ds.position = new Rect(middle - new Vector2(100f, 150f), Vector2.zero); subGraphNode.drawState = ds; // Add the subgraph into the group if the nodes was all in the same group group var firstNode = copyPasteGraph.GetNodes <AbstractMaterialNode>().FirstOrDefault(); if (firstNode != null && copyPasteGraph.GetNodes <AbstractMaterialNode>().All(x => x.group == firstNode.group)) { subGraphNode.group = firstNode.group; } subGraphNode.asset = loadedSubGraph; graphObject.graph.AddNode(subGraphNode); foreach (var edgeMap in externalInputNeedingConnection) { graphObject.graph.Connect(edgeMap.Key.outputSlot, new SlotReference(subGraphNode, edgeMap.Value.guid.GetHashCode())); } foreach (var edgeMap in externalOutputsNeedingConnection) { graphObject.graph.Connect(new SlotReference(subGraphNode, edgeMap.Value.inputSlot.slotId), edgeMap.Key.inputSlot); } graphObject.graph.RemoveElements( graphView.selection.OfType <IShaderNodeView>().Select(x => x.node).Where(x => x.allowedInSubGraph).ToArray(), new IEdge[] {}, new GroupData[] {}, graphView.selection.OfType <StickyNote>().Select(x => x.userData).ToArray()); graphObject.graph.ValidateGraph(); }
void ChangeCategoryName(GraphData graphData) { AssertHelpers.IsNotNull(graphData, "GraphData is null while carrying out ChangeCategoryNameAction"); graphData.owner.RegisterCompleteObjectUndo("Change Category Name"); graphData.ChangeCategoryName(categoryGuid, newCategoryNameValue); }
// Called by GraphDataStore.Subscribe after the model has been changed protected override void ModelChanged(GraphData graphData, IGraphDataAction changeAction) { // If categoryData associated with this controller is removed by an operation, destroy controller and views associated if (graphData.ContainsCategory(Model) == false) { this.Destroy(); return; } switch (changeAction) { case AddShaderInputAction addBlackboardItemAction: if (addBlackboardItemAction.shaderInputReference != null && IsInputInCategory(addBlackboardItemAction.shaderInputReference)) { var blackboardRow = FindBlackboardRow(addBlackboardItemAction.shaderInputReference); if (blackboardRow == null) { blackboardRow = InsertBlackboardRow(addBlackboardItemAction.shaderInputReference); } // Rows should auto-expand when an input is first added // blackboardRow.expanded = true; var propertyView = blackboardRow.Q <SGBlackboardField>(); if (addBlackboardItemAction.addInputActionType == AddShaderInputAction.AddActionSource.AddMenu) { propertyView.OpenTextEditor(); } } break; case CopyShaderInputAction copyShaderInputAction: // In the specific case of only-one keywords like Material Quality and Raytracing, they can get copied, but because only one can exist, the output copied value is null if (copyShaderInputAction.copiedShaderInput != null && IsInputInCategory(copyShaderInputAction.copiedShaderInput)) { var blackboardRow = InsertBlackboardRow(copyShaderInputAction.copiedShaderInput, copyShaderInputAction.insertIndex); if (blackboardRow != null) { var graphView = ViewModel.parentView.GetFirstAncestorOfType <MaterialGraphView>(); var propertyView = blackboardRow.Q <SGBlackboardField>(); graphView?.AddToSelectionNoUndoRecord(propertyView); } } break; case AddItemToCategoryAction addItemToCategoryAction: // If item was added to category that this controller manages, then add blackboard row to represent that item if (addItemToCategoryAction.itemToAdd != null && addItemToCategoryAction.categoryGuid == ViewModel.associatedCategoryGuid) { InsertBlackboardRow(addItemToCategoryAction.itemToAdd, addItemToCategoryAction.indexToAddItemAt); } else { // If the added input has been added to a category other than this one, and it used to belong to this category, // Then cleanup the controller and view that used to represent that input foreach (var key in m_BlackboardItemControllers.Keys) { var blackboardItemController = m_BlackboardItemControllers[key]; if (blackboardItemController.Model == addItemToCategoryAction.itemToAdd) { RemoveBlackboardRow(addItemToCategoryAction.itemToAdd); break; } } } break; case DeleteCategoryAction deleteCategoryAction: if (deleteCategoryAction.categoriesToRemoveGuids.Contains(ViewModel.associatedCategoryGuid)) { this.Destroy(); return; } break; case ChangeCategoryIsExpandedAction changeIsExpandedAction: if (changeIsExpandedAction.categoryGuids.Contains(ViewModel.associatedCategoryGuid)) { ViewModel.isExpanded = changeIsExpandedAction.isExpanded; m_BlackboardCategoryView.TryDoFoldout(changeIsExpandedAction.isExpanded); } break; case ChangeCategoryNameAction changeCategoryNameAction: if (changeCategoryNameAction.categoryGuid == ViewModel.associatedCategoryGuid) { ViewModel.name = Model.name; m_BlackboardCategoryView.title = ViewModel.name; } break; } }
public static void Replace([NotNull] this PlotModel collection, [NotNull] string trackerKey, [CanBeNull] GraphData data) { collection.Replace(trackerKey, data?.Points.Select(x => new DataPoint(x.X, x.Y))); }
public ItemEdges(GraphData graphData, RawItemEdgeCollection rawItemEdges) { this._graphData = graphData; this.Edges = new List <Edge>(); FillItemEdges(rawItemEdges); }
public GraphData(SrmDocument document, GraphData dataPrevious, int resultIndex, double threshold, int? thresholdPrecision, bool refine, bool bestResult) { _document = document; _resultIndex = resultIndex; _bestResult = bestResult; _threshold = threshold; _thresholdPrecision = thresholdPrecision; _peptidesIndexes = new List<PeptideDocumentIndex>(); _peptidesTimes = new List<MeasuredRetentionTime>(); int index = -1; // CONSIDER: Retention time prediction for small molecules? foreach (var nodePeptide in document.Peptides) { index++; float? rt = null; if (!bestResult) rt = nodePeptide.GetSchedulingTime(resultIndex); else { int iBest = nodePeptide.BestResult; if (iBest != -1) rt = nodePeptide.GetSchedulingTime(iBest); } if (!rt.HasValue) rt = 0; _peptidesIndexes.Add(new PeptideDocumentIndex(nodePeptide, index)); string modSeq = _document.Settings.GetSourceTextId(nodePeptide); _peptidesTimes.Add(new MeasuredRetentionTime(modSeq, rt.Value)); } _calculatorName = Settings.Default.RTCalculatorName; RetentionScoreCalculatorSpec calc = !string.IsNullOrEmpty(_calculatorName) ? Settings.Default.GetCalculatorByName(Settings.Default.RTCalculatorName) : null; if (calc == null) { // Initialize all calculators Settings.Default.RTScoreCalculatorList.Initialize(null); //This call will pick the best calculator, disqualifying any iRT Calcs that do not have //connected databases _regressionAll = RetentionTimeRegression.CalcRegression(XmlNamedElement.NAME_INTERNAL, Settings.Default.RTScoreCalculatorList, _peptidesTimes, _scoreCache, true, out _statisticsAll, out _calculator); } else { // Initialize the one calculator calc = Settings.Default.RTScoreCalculatorList.Initialize(null, calc); _regressionAll = RetentionTimeRegression.CalcRegression(XmlNamedElement.NAME_INTERNAL, new[] {calc}, _peptidesTimes, _scoreCache, true, out _statisticsAll, out _calculator); //If _regressionAll is null, it is safe to assume that the calculator is an iRT Calc with //its database disconnected. if(_regressionAll == null) { var tryIrtCalc = calc as RCalcIrt; //Only show an error message if the user specifically chooses this calculator. if (dataPrevious != null && !ReferenceEquals(calc, dataPrevious.Calculator) && tryIrtCalc != null) { throw new DatabaseNotConnectedException(tryIrtCalc); } } } if (_regressionAll != null) { _scoreCache = new RetentionTimeScoreCache(new[] { _calculator }, _peptidesTimes, dataPrevious != null ? dataPrevious._scoreCache : null); if (dataPrevious != null && !ReferenceEquals(_calculator, dataPrevious._calculator)) _scoreCache.RecalculateCalcCache(_calculator); _scoresRefined = _statisticsAll.ListHydroScores.ToArray(); _timesRefined = _statisticsAll.ListRetentionTimes.ToArray(); } _regressionPredict = document.Settings.PeptideSettings.Prediction.RetentionTime; if (_regressionPredict != null) { if (!Equals(_calculator, _regressionPredict.Calculator)) _regressionPredict = null; else { IDictionary<string, double> scoreCache = null; if (_regressionAll != null && ReferenceEquals(_regressionAll.Calculator, _regressionPredict.Calculator)) scoreCache = _statisticsAll.ScoreCache; _statisticsPredict = _regressionPredict.CalcStatistics(_peptidesTimes, scoreCache); } } // Only refine, if not already exceeding the threshold _refine = refine && !IsRefined(); }
private void DelayedUpdate() { // Any change to the calculator list requires a full data update when in auto mode. if (string.IsNullOrEmpty(Settings.Default.RTCalculatorName)) Data = null; UpdateGraph(true); _pendingUpdate = false; }
public BlackboardFieldPropertyView(BlackboardField blackboardField, GraphData graph, ShaderInput input) : base(blackboardField, graph, input) { }
public static Vertex Rung2_poli(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "Rung2_poli.html"; Edge e; string NextVertexName = "SubcrisisManeuvering_Result"; e = new Edge(d); e.State.VertexName = NextVertexName; e.State.PerceivedInflexibility += 5; e.HTML = "Replace an official in a key spot by one who is known to be 'hard' or 'tough'"; v.Edges.Add(e); //Soviets do likewise. e = new Edge(d); e.State.VertexName = NextVertexName; e.State.PerceivedResolve += 5; e.HTML = "Start a violent publicity campaign, encourage mass meetings, 'spontaneous' public demonstrations"; v.Edges.Add(e); //With gusto, the Soviet propagandists eagerly match the demonstrations //with even more spectactular ones. return v; }
void ShowGraphData(string strToolName, int nRefValue) { // 여기 데이터 다 담겨있다 // 차트 데이터 편집 int nMinValue = GraphData.Min(); int nMaxValue = GraphData.Max(); int nStandValue = nRefValue; if (nMinValue == nMaxValue) { MessageBox.Show("Graph Show Fail"); return; } chart1.Series[0].Points.Clear(); chart1.ChartAreas[0].AxisY.Minimum = nMinValue; chart1.ChartAreas[0].AxisY.Maximum = nMaxValue; chart1.ChartAreas[0].AxisY.Interval = (nMaxValue - nMinValue) / 5; chart1.Series[0].LegendText = "RefValue: " + nStandValue.ToString(); foreach (int nData in GraphData) { chart1.Series[0].Points.Add(nData); } // 값 표시 double dPercentMin = (double)(nMinValue * 100) / (double)nStandValue; double dPercentMax = (double)(nMaxValue * 100) / (double)nStandValue; string strTemp; textBox_info.Clear(); StringBuilder sb = new StringBuilder(); strTemp = string.Format("Ref Value: {0}", nStandValue); sb.AppendLine(strTemp); strTemp = string.Format("Min: {0} {1: 0.00}%, Max: {2} {3: 0.00}%", nMinValue, dPercentMin, nMaxValue, dPercentMax); sb.AppendLine(strTemp); double dMaxGab = 0; if (Math.Abs(100 - dPercentMax) > Math.Abs(100 - dPercentMin)) { dMaxGab = dPercentMax; } else { dMaxGab = dPercentMin; } dMaxGab = Math.Abs(100 - dMaxGab); strTemp = string.Format("MaxGab: {0: 0.00}%", dMaxGab); sb.AppendLine(strTemp); textBox_info.Text = sb.ToString(); }
public static Vertex Rung3(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "Rung3.html"; Edge e; string NextVertexName = "TraditionalCrises_Index"; e = new Edge(d); e.State.VertexName = NextVertexName; //e.State.Pressure += 5; //e.State.PerceivedInflexibility += 5; e.HTML = "Make a solemn and formal declaration. Rock the boat."; v.Edges.Add(e); return v; }
void ShowToolInformation() { GraphData.Clear(); int nSelected = nSelectedCount; int nSelectedTool = nSelectedToolNo; int nCurrentPanelCnt = 0; int nCurrentToolCnt = -1; bool saved = false; string[] lines = File.ReadAllLines(OpenedFilePath); string strOldToolName = "empty"; string strToolName = null; int nRefValue = 0; foreach (string lead in lines) { if (lead.Contains("Project")) { saved = false; if (nSelected == nCurrentPanelCnt) { saved = true; } nCurrentPanelCnt++; continue; } if (lead.Contains("-> Value")) { continue; } if (saved) { string tooltag = lead.Split('\t')[0]; string toolname = tooltag.Split(' ')[tooltag.Split(' ').Length - 2] + " " + tooltag.Split(' ')[tooltag.Split(' ').Length - 1]; if (strOldToolName == "empty" || strOldToolName != toolname) { nCurrentToolCnt++; strOldToolName = toolname; } if (nCurrentToolCnt == nSelectedTool) { string strRefValue = lead.Split(' ')[lead.Split(' ').Length - 1]; string strvalue = lead.Split('\t')[lead.Split('\t').Length - 2]; strvalue = strvalue.Replace("Value ", ""); GraphData.Add(Convert.ToInt32(strvalue)); nRefValue = Convert.ToInt32(strRefValue); strToolName = toolname; } else { continue; } } } if (strToolName != null) { ShowGraphData(strToolName, nRefValue); } }
// updates the graphs and graph averages for a selected lap private void updateGraphsAndData(int selectedLapIndex) { Lap lap = ActiveActivity.Laps[selectedLapIndex]; DateTime start = lap.Trackpoints.First().Time; double max = 0; double min = 0; //update watts graph if (ActiveType == Sport.Biking) { List <DataPoint> wattsDataPoints = new List <DataPoint>(lap.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), (y.Extensions as BikeExtension).Watts)).ToList()); Console.WriteLine(wattsDataPoints.First().X); max = wattsDataPoints.Max(x => x.X) + 1; min = wattsDataPoints.Min(x => x.X); if (wattsDataPoints[0].Y >= 0) { WattsData = new GraphData(wattsDataPoints, max, min); } else { WattsData = null; } } // update hr graph List <DataPoint> hrDataPoints = new List <DataPoint>(lap.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), y.HeartRate)).ToList()); max = hrDataPoints.Max(x => x.X) + 1; min = hrDataPoints.Min(x => x.X); if (hrDataPoints[0].Y >= 0) { HeartRateData = new GraphData(hrDataPoints, max, min); } else { HeartRateData = null; } //update speed graph List <DataPoint> speedDataPoints = new List <DataPoint>(lap.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), y.Extensions.Speed)).ToList()); max = speedDataPoints.Max(x => x.X) + 1; min = speedDataPoints.Min(x => x.X); if (speedDataPoints[0].Y >= 0) { SpeedData = new GraphData(speedDataPoints, max, min); } else { SpeedData = null; } if (ActiveType == Sport.Biking) { // update cadence graph List <DataPoint> cadenceDataPoints = new List <DataPoint>(lap.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), y.Cadence)).ToList()); max = cadenceDataPoints.Max(x => x.X) + 1; min = cadenceDataPoints.Min(x => x.X); if (cadenceDataPoints[0].Y >= 0) { CadenceData = new GraphData(cadenceDataPoints, max, min); } else { CadenceData = null; } } else if (ActiveType == Sport.Running) { // update cadence graph List <DataPoint> cadenceDataPoints = new List <DataPoint>(lap.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), (y.Extensions as RunExtension).Cadence)).ToList()); max = cadenceDataPoints.Max(x => x.X) + 1; min = cadenceDataPoints.Min(x => x.X); if (cadenceDataPoints[0].Y >= 0) { CadenceData = new GraphData(cadenceDataPoints, max, min); } else { CadenceData = null; } } // update elevation graph List <DataPoint> altitudeDataPoints = new List <DataPoint>(lap.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), y.Altitude)).ToList()); max = altitudeDataPoints.Max(x => x.X) + 1; min = altitudeDataPoints.Min(x => x.X); if (altitudeDataPoints[0].Y != -1) { ElevationData = new GraphData(altitudeDataPoints, max, min); } else { ElevationData = null; } //Update HR stats if (ActiveActivity != null) { double avg = lap.AvgHeartRate; double maxim = lap.MaxHeartRate; if (avg < 0) { HeartRateInfo = "No HR data provided :("; } else { HeartRateInfo = "Average: " + Math.Round(avg, 0) + " bpm\nMax: " + Math.Round(maxim, 0) + " bpm"; } } //update cadence stats if (ActiveActivity != null) { if (ActiveActivity is BikeActivity) { double avg = lap.AvgCadence; double maxim = lap.MaxCadence; if (avg < 0) { CadenceInfo = "No cadence data provided :("; } else { CadenceInfo = "Average: " + Math.Round(avg, 0) + " spm\nMax: " + Math.Round(maxim, 0) + " spm"; } } } //Update speed stats if (ActiveActivity != null) { double avg = lap.AvgSpeed; double maxim = lap.MaxSpeed; if (avg < 0) { SpeedInfo = "No speed data provided :("; } else { SpeedInfo = "Average: " + Math.Round(avg, 2) + " mph\nMax: " + Math.Round(maxim, 2) + " mph"; } } // update power stats if (ActiveActivity != null) { if (ActiveActivity is BikeActivity) { double avg = lap.AvgPower; double maxim = lap.MaxPower; if (avg < 0) { WattsInfo = "No power data provided :("; } else { WattsInfo = "Average: " + Math.Round(avg, 0) + " W\nMax: " + Math.Round(maxim, 0) + " W"; } } else { WattsInfo = "No power data provided :("; } } //update elevation stats if (ActiveActivity != null) { var ascList = ActiveActivity.Laps.Select(x => x.ElevationGain); var descList = ActiveActivity.Laps.Select(x => x.ElevationLoss); double asc = lap.ElevationGain; double desc = lap.ElevationLoss; double largest = lap.BiggestClimb; if (asc < 0 && desc < 0) { ElevationInfo = "No elevation data provided :("; } else { ElevationInfo = "Ascent: " + Math.Round(asc, 0) + " ft\nDescent: " + Math.Round(desc, 0) + " ft\nLargest climb: " + Math.Round(largest, 0) + " ft"; } if (ActiveActivity != null) { if (ActiveActivity is BikeActivity) { Name = (ActiveActivity as BikeActivity).Name; } else if (ActiveActivity is RunActivity) { Name = (ActiveActivity as RunActivity).Name; } } } }
public static extern int AddGraph(GraphData graphData);
VisualElement GetSettings(GraphData graphData, Action onChange) { var element = new VisualElement() { name = "graphSettings" }; if (graphData.isSubGraph) { return(element); } void RegisterActionToUndo(string actionName) { graphData.owner.RegisterCompleteObjectUndo(actionName); } // Add Label var targetSettingsLabel = new Label("Target Settings"); targetSettingsLabel.style.unityFontStyleAndWeight = FontStyle.Bold; element.Add(new PropertyRow(targetSettingsLabel)); var targetList = new ReorderableListView <JsonData <Target> >( graphData.m_ActiveTargets, "Active Targets", false, // disallow reordering (active list is sorted) target => target.value.displayName); targetList.GetAddMenuOptions = () => graphData.GetPotentialTargetDisplayNames(); targetList.OnAddMenuItemCallback += (list, addMenuOptionIndex, addMenuOption) => { RegisterActionToUndo("Add Target"); graphData.SetTargetActive(addMenuOptionIndex); m_PostChangeTargetSettingsCallback(InspectorUpdateSource.GraphChanges); }; targetList.RemoveItemCallback += (list, itemIndex) => { RegisterActionToUndo("Remove Target"); graphData.SetTargetInactive(list[itemIndex].value); m_PostChangeTargetSettingsCallback(InspectorUpdateSource.GraphChanges); }; element.Add(targetList); // Iterate active TargetImplementations foreach (var target in graphData.activeTargets) { // Ensure enabled state is being tracked and get value bool foldoutActive; if (!m_TargetFoldouts.TryGetValue(target, out foldoutActive)) { foldoutActive = true; m_TargetFoldouts.Add(target, foldoutActive); } // Create foldout var foldout = new Foldout() { text = target.displayName, value = foldoutActive, name = "foldout" }; element.Add(foldout); foldout.AddToClassList("MainFoldout"); foldout.RegisterValueChangedCallback(evt => { // Update foldout value and rebuild m_TargetFoldouts[target] = evt.newValue; foldout.value = evt.newValue; onChange(); }); if (foldout.value) { // Get settings for Target var context = new TargetPropertyGUIContext(); target.GetPropertiesGUI(ref context, onChange, RegisterActionToUndo); element.Add(context); } } return(element); }
public void Verify_Edge_Added_To_Physical_Graph_Once_Corresponding_Source_Node_Added() { int actualSourceEdges; int actualTargetEdges; int expectedSourceEdges = 1; int expectedTargetEdges = 1; INode source = PrepareNode("Node1", ghostNode: true); INode target = PrepareNode("Node2", ghostNode: false); IEdge orphan = new Edge(source, target); GraphData graphData = new GraphData("scope"); // Add an edge with ghost nodes to the graph graphData.AddNode(target); graphData.AddEdge(orphan); // Add the missing node source = PrepareNode("Node1", ghostNode: false); graphData.AddNode(source); // Get the actual count for nodes actualSourceEdges = graphData.Edges(source).Count(); actualTargetEdges = graphData.Edges(target).Count(); Assert.AreEqual(expectedSourceEdges, actualSourceEdges); Assert.AreEqual(expectedTargetEdges, actualTargetEdges); }
public void TestImportAsset(string unityLocalPath, string fullPath) { unityLocalPath = unityLocalPath.Replace("\\", "/"); Debug.Log("Testing file: " + unityLocalPath); // invoke an import AssetDatabase.ImportAsset(unityLocalPath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate | ImportAssetOptions.DontDownloadFromCacheServer); // double check we can load it up and validate it string fileContents = File.ReadAllText(fullPath); Assert.Greater(fileContents.Length, 0); var graphGuid = AssetDatabase.AssetPathToGUID(unityLocalPath); var messageManager = new MessageManager(); GraphData graphData = new GraphData() { assetGuid = graphGuid, messageManager = messageManager }; MultiJson.Deserialize(graphData, fileContents); graphData.OnEnable(); graphData.ValidateGraph(); string fileExtension = Path.GetExtension(fullPath).ToLower(); bool isSubgraph = (fileExtension == "shadersubgraph"); if (isSubgraph) { // check that the SubGraphAsset is the same after versioning twice // this is important to ensure we're not importing subgraphs non-deterministically when they are out-of-date on disk AssetDatabase.ImportAsset(unityLocalPath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate | ImportAssetOptions.DontDownloadFromCacheServer); var subGraph = AssetDatabase.LoadAssetAtPath <SubGraphAsset>(unityLocalPath); var serialized = EditorJsonUtility.ToJson(subGraph); AssetDatabase.ImportAsset(unityLocalPath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate | ImportAssetOptions.DontDownloadFromCacheServer); var subGraph2 = AssetDatabase.LoadAssetAtPath <SubGraphAsset>(unityLocalPath); var serialized2 = EditorJsonUtility.ToJson(subGraph2); Assert.AreEqual(serialized, serialized2, $"Importing the subgraph {unityLocalPath} twice resulted in different subgraph assets."); } else { // check that the generated shader is the same after versioning twice // this is important to ensure we're not importing shaders non-deterministically when they are out-of-date on disk string fileNameNoExtension = Path.GetFileNameWithoutExtension(fullPath); var generator = new Generator(graphData, graphData.outputNode, GenerationMode.ForReals, fileNameNoExtension, null); string shader = generator.generatedShader; // version again GraphData graphData2 = new GraphData() { assetGuid = graphGuid, messageManager = messageManager }; MultiJson.Deserialize(graphData2, fileContents); graphData2.OnEnable(); graphData2.ValidateGraph(); var generator2 = new Generator(graphData2, graphData2.outputNode, GenerationMode.ForReals, fileNameNoExtension, null); string shader2 = generator2.generatedShader; Assert.AreEqual(shader, shader2, $"Importing the graph {unityLocalPath} twice resulted in different generated shaders."); } }
public static async Task <GraphData> ConvertToGraphData(List <CsvConcept> concepts, List <CsvElement> elements, List <CsvCountry> countries, List <CsvPeople> peoples, List <CsvProject> projects, List <CsvPublication> publications, List <CsvRegion> regions) { List <NodeElement> nodeElements = new List <NodeElement>(); List <NodeCountry> nodeCountries = new List <NodeCountry>(); List <NodeProject> nodeProjects = new List <NodeProject>(); List <NodeVt> nodeConcepts = new List <NodeVt>(); List <NodePublication> nodePublications = new List <NodePublication>(); List <NodeCaseStudy> nodePeople = new List <NodeCaseStudy>(); foreach (var item in elements) { nodeElements.Add(CsvElement.ToNodeElement(item)); } foreach (var item in countries) { nodeCountries.Add(CsvCountry.ToNodeElement(item)); } foreach (var item in regions) { nodeCountries.Add(CsvRegion.ToNodeElement(item)); } foreach (var item in projects) { nodeProjects.Add(CsvProject.ToNodeElement(item)); } foreach (var item in concepts) { nodeConcepts.Add(CsvConcept.ToNodeElement(item)); } foreach (var item in publications) { nodePublications.Add(CsvPublication.ToNodeElement(item)); } foreach (var item in peoples) { nodePeople.Add(CsvPeople.ToNodeElement(item)); } List <EdgeItem> edgeItems = new List <EdgeItem>(); foreach (var concept in concepts) { if (concept.LinkedElements.Contains(",")) { string[] items = concept.LinkedElements.Split(','); foreach (var s in items) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = s, weight = 2 }); } } else { if (!string.IsNullOrEmpty(concept.LinkedElements)) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = concept.LinkedElements, weight = 2 }); } } } foreach (var concept in elements) { if (concept.LinkedElements.Contains(",")) { string[] items = concept.LinkedElements.Split(','); foreach (var s in items) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = s, weight = 2 }); } } else { if (!string.IsNullOrEmpty(concept.LinkedElements)) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = concept.LinkedElements, weight = 2 }); } } } foreach (var concept in countries) { if (concept.LinkedElements.Contains(",")) { string[] items = concept.LinkedElements.Split(','); foreach (var s in items) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = s, weight = 2 }); } } else { if (!string.IsNullOrEmpty(concept.LinkedElements)) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = concept.LinkedElements, weight = 2 }); } } } foreach (var concept in regions) { if (concept.LinkedElements.Contains(",")) { string[] items = concept.LinkedElements.Split(','); foreach (var s in items) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = s, weight = 2 }); } } else { if (!string.IsNullOrEmpty(concept.LinkedElements)) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = concept.LinkedElements, weight = 2 }); } } } foreach (var concept in peoples) { if (concept.LinkedElements.Contains(",")) { string[] items = concept.LinkedElements.Split(','); foreach (var s in items) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = s, weight = 2 }); } } else { if (!string.IsNullOrEmpty(concept.LinkedElements)) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = concept.LinkedElements, weight = 2 }); } } } foreach (var concept in projects) { if (concept.LinkedElements.Contains(",")) { string[] items = concept.LinkedElements.Split(','); foreach (var s in items) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = s, weight = 2 }); } } else { if (!string.IsNullOrEmpty(concept.LinkedElements)) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = concept.LinkedElements, weight = 2 }); } } } foreach (var concept in publications) { if (concept.LinkedElements.Contains(",")) { string[] items = concept.LinkedElements.Split(','); foreach (var s in items) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = s, weight = 2 }); } } else { if (!string.IsNullOrEmpty(concept.LinkedElements)) { edgeItems.Add(new EdgeItem() { Object = concept.Name, predicate = "related", subject = concept.LinkedElements, weight = 2 }); } } } GraphData graphData = new GraphData() { Meta = new Meta() { generated = "Generated with ontoUcmd", language = "en" }, NodeElements = nodeElements, NodeCountries = nodeCountries, NodeProjects = nodeProjects, NodePublications = nodePublications, NodeVts = nodeConcepts, NodeCaseStudies = nodePeople, EdgeItems = edgeItems }; return(graphData); }
public GraphData(SrmDocument document, GraphData dataPrevious, int resultIndex, bool bestResult, PointsTypeMassError pointsType) { _document = document; _resultIndex = resultIndex; _replicateDisplay = ShowReplicate; int[,] counts2D = EMPTY_COUNTS; _displayType = MassErrorGraphController.HistogramDisplayType; _binSizePpm = Settings.Default.MassErorrHistogramBinSize; _transition = MassErrorGraphController.HistogramTransiton; _xAxis = MassErrorGraphController.Histogram2DXAxis; _pointsType = pointsType; if (_pointsType == PointsTypeMassError.targets_1FDR && !document.Settings.PeptideSettings.Integration.PeakScoringModel.IsTrained) { _pointsType = PointsTypeMassError.targets; } bool decoys = pointsType == PointsTypeMassError.decoys; bool precursors = _displayType == DisplayTypeMassError.precursors; while (ReferenceEquals(counts2D, EMPTY_COUNTS)) { if (_maxMass != double.MinValue) { counts2D = new int[xAxisBins, (int)((_maxMass - _minMass) / _binSizePpm + 1)]; } foreach (var nodePep in document.Molecules) { if (decoys != nodePep.IsDecoy) { continue; } var replicateIndex = bestResult && nodePep.BestResult != -1 ? nodePep.BestResult : resultIndex; foreach (var nodeGroup in nodePep.TransitionGroups) { foreach (var nodeTran in nodeGroup.Transitions) { if (precursors != nodeTran.IsMs1) { continue; } var mz = nodeTran.Mz.Value; if (replicateIndex >= 0) { AddChromInfo(nodeGroup, nodeTran, replicateIndex, mz, counts2D); } else { for (int i = 0; i < nodeTran.Results.Count; i++) { AddChromInfo(nodeGroup, nodeTran, i, mz, counts2D); } } } } } // No values. Leave _maxCount == 0 if (_maxMass == double.MinValue) { return; } } var points = new List <Point3D>(); for (int x = 0; x < counts2D.GetLength(0); x++) { for (int y = 0; y < counts2D.GetLength(1); y++) { int count = counts2D[x, y]; if (count > 0) { double binSizeX = (_maxX - _minX) / xAxisBins; double xPoint = x * binSizeX + _minX + binSizeX / 2; double yPoint = y * _binSizePpm + _minMass + _binSizePpm / 2; points.Add(new Point3D(xPoint, yPoint, count)); } _maxCount = Math.Max(_maxCount, count); } } _heatMapData = new HeatMapData(points); }
protected override void OnUpdate() { GraphData graphData = GetSingleton <GraphData>(); { EventSystem <AddPointEvent> .AddMissingBuffers(Entities, DestroyPickup_Query_MissingAddPointEvent, EntityManager); Entities.With(DestroyPickup_Query).ForEach((Unity.Entities.Entity DestroyPickup_QueryEntity) => { var DestroyPickup_Query_AddPointEventBuffer = EntityManager.GetBuffer <AddPointEvent>(DestroyPickup_QueryEntity); PostUpdateCommands.DestroyEntity(DestroyPickup_QueryEntity); DestroyPickup_Query_AddPointEventBuffer.Add(new AddPointEvent { }); graphData.Pickups_Amount = (graphData.Pickups_Amount - 1); } ); } { Entities.With(Empty_Query_WithAddPointEvent).ForEach((Unity.Entities.Entity Empty_QueryEntity, DynamicBuffer <AddPointEvent> eventBuffer) => { for (int event_index = 0; event_index < eventBuffer.Length; event_index++) { AddPointEvent ev = eventBuffer[event_index]; { var GameManager_QueryEntities = GameManager_Query.ToEntityArray(Allocator.TempJob); for (int GameManager_QueryIdx = 0; GameManager_QueryIdx < GameManager_QueryEntities.Length; GameManager_QueryIdx++) { var GameManager_QueryEntity = GameManager_QueryEntities[GameManager_QueryIdx]; var GameManager_QueryGameManager = EntityManager.GetSharedComponentData <GameManager>(GameManager_QueryEntity); graphData.Game_Score++; GameManager_QueryGameManager.Score.text = graphData.Game_Score.ToString(); if ((graphData.Pickups_Amount <= 0)) { GameManager_QueryGameManager.WinText.enabled = true; Time.timeScale = 0F; } PostUpdateCommands.SetSharedComponent <GameManager>(GameManager_QueryEntities[GameManager_QueryIdx], GameManager_QueryGameManager); } GameManager_QueryEntities.Dispose(); } } } ); } { Entities.With(GameManager_Query0Enter).ForEach((Unity.Entities.Entity GameManager_QueryEntity, GameManager GameManager_Query0EnterGameManager) => { { var PickupObjects_QueryEntities = PickupObjects_Query.ToEntityArray(Allocator.TempJob); for (int PickupObjects_QueryIdx = 0; PickupObjects_QueryIdx < PickupObjects_QueryEntities.Length; PickupObjects_QueryIdx++) { var PickupObjects_QueryEntity = PickupObjects_QueryEntities[PickupObjects_QueryIdx]; graphData.Pickups_Amount = (graphData.Pickups_Amount + 1); } PickupObjects_QueryEntities.Dispose(); } GameManager_Query0EnterGameManager.Score.text = graphData.Game_Score.ToString(); GameManager_Query0EnterGameManager.WinText.enabled = false; PostUpdateCommands.AddComponent <GameManager_QueryTracking>(GameManager_QueryEntity, default(GameManager_QueryTracking)); } ); } SetSingleton(graphData); }
void OnEnable() { if(!isEnabled) { dataObj = new SerializedObject(target); data = (GraphData) target; hookupSceneGUI(); EditorNode.SetObjHandler(nodeHandler); if(!hasLoadedGraph) ReadFromData(); isEnabled = true; } }
void HandleGraphUndoRedo(GraphData graphData) { AssertHelpers.IsNotNull(graphData, "GraphData is null while carrying out HandleUndoRedoAction"); AssertHelpers.IsNotNull(newGraphData, "NewGraphData is null while carrying out HandleUndoRedoAction"); graphData?.ReplaceWith(newGraphData); }
public void RefreshConnectors() { if (IsLoading) { return; } var remove = GraphItems.OfType <ConnectionViewModel>().ToArray(); foreach (var item in remove) { GraphItems.Remove(item); } var strategies = InvertGraphEditor.ConnectionStrategies; var outputs = GraphItems.OfType <ConnectorViewModel>().Where(p => p.Direction == ConnectorDirection.Output).ToArray(); var inputs = GraphItems.OfType <ConnectorViewModel>().Where(p => p.Direction != ConnectorDirection.Output).ToArray(); foreach (var output in outputs) { foreach (var input in inputs) { foreach (var strategy in strategies) { if (strategy.IsConnected(output, input)) { var strategy1 = strategy; var output1 = output; var input1 = input; output.HasConnections = true; input.HasConnections = true; GraphItems.Add(new ConnectionViewModel(this) { ConnectorA = output, ConnectorB = input, Color = strategy.ConnectionColor, DataObject = output.DataObject, Remove = (a) => { //a.Remove(a); strategy1.Remove(output1, input1); } }); } } } } var connectors = GraphItems.OfType <ConnectorViewModel>().ToArray(); foreach (var connection in CurrentRepository.All <ConnectionData>()) { ConnectorViewModel startConnector = null; ConnectorViewModel endConnector = null; for (int i = 0; i < connectors.Length; i++) { if (startConnector != null && endConnector != null) { break; } var p = connectors[i]; if (p.Direction == ConnectorDirection.Output && p.Identifier == connection.OutputIdentifier) { startConnector = p; } else if (p.Direction == ConnectorDirection.Input && p.Identifier == connection.InputIdentifier) { endConnector = p; } } // var startConnector = connectors.FirstOrDefault(p => p.Direction == ConnectorDirection.Output && p.Identifier == connection.OutputIdentifier); // var endConnector = connectors.FirstOrDefault(p => p.Direction == ConnectorDirection.Input && p.Identifier == connection.InputIdentifier); if (startConnector == null || endConnector == null) { continue; } var vm = endConnector.ConnectorFor.DataObject as IDiagramNodeItem; startConnector.HasConnections = true; endConnector.HasConnections = true; var connection1 = connection; GraphItems.Add(new ConnectionViewModel(this) { ConnectorA = endConnector, ConnectorB = startConnector, Color = startConnector.Color, DataObject = connection, Remove = (a) => { GraphData.RemoveConnection(a.ConnectorB.DataObject as IConnectable, a.ConnectorA.DataObject as IConnectable); } }); } //var endTime = DateTime.Now; //var diff = new TimeSpan(endTime.Ticks - startTime.Ticks); //Debug.Log(string.Format("{0} took {1} seconds {2} milliseconds", "New Strategy", diff.Seconds, diff.Milliseconds)); //var connections = new List<ConnectionViewModel>(); //var connectorInfo = new ConnectorInfo(connectors.ToArray(), this, CurrentRepository); //foreach (var strategy in InvertGraphEditor.ConnectionStrategies) //{ // var startTime = DateTime.Now; // strategy.GetConnections(connections, connectorInfo); // var endTime = DateTime.Now; // var diff = new TimeSpan(endTime.Ticks - startTime.Ticks); // Debug.Log(string.Format("{0} took {1} seconds {2} milliseconds", strategy.GetType().Name, diff.Seconds, diff.Milliseconds)); //} //foreach (var item in connections) //{ // GraphItems.Add(item); // item.ConnectorA.HasConnections = true; // item.ConnectorB.HasConnections = true; //} }
public BlackboardFieldView(GraphData graph, ShaderInput input, Texture icon, string text, string typeText) : base(icon, text, typeText) { styleSheets.Add(Resources.Load <StyleSheet>("Styles/ShaderGraphBlackboard")); m_Graph = graph; m_Input = input; }
public static Vertex Rung1(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "Rung1.html"; Edge e; string NextVertexName = "SubcrisisManeuvering_Result"; e = new Edge(d); e.State.VertexName = NextVertexName; e.State.PerceivedResolve += 5; e.HTML = "Assert openly and explicitly that unless the dispute is resolved in the immediate future further escalation will occur."; v.Edges.Add(e); //Soviets claim you're fanning the fire. e = new Edge(d); e.State.VertexName = NextVertexName; e.HTML = "Officially inspire newspaper stories to the effect that the chief of state takes a serious view of the matter."; v.Edges.Add(e); //Little effective change on Soviets. return v; }
public MaterialGraphView(GraphData graph) : this() { this.graph = graph; }
public static Vertex Index(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "SubcrisisManeuvering.html"; Edge e; e = new Edge(d); e.Invisible = d.Start.Rank1.InHand <= 0; e.State.VertexName = "SubcrisisManeuvering_Rung1"; e.State.Rank1.Played++; e.State.Rank1.InHand--; e.HTML = "Acknowledge Crisis"; v.Edges.Add(e); e = new Edge(d); e.Invisible = d.Start.Rank2_poli.InHand <= 0; e.State.VertexName = "SubcrisisManeuvering_Rung2_poli"; e.State.Rank2_poli.Played++; e.State.Rank2_poli.InHand--; e.HTML = "Make a Political Gesture"; v.Edges.Add(e); e = new Edge(d); e.Invisible = d.Start.Rank2_econ.InHand <= 0; e.State.VertexName = "SubcrisisManeuvering_Rung2_econ"; e.State.Rank2_econ.Played++; e.State.Rank2_econ.InHand--; e.HTML = "Make a Economic Gesture"; v.Edges.Add(e); e = new Edge(d); e.Invisible = d.Start.Rank2_dipl.InHand <= 0; e.State.VertexName = "SubcrisisManeuvering_Rung2_dipl"; e.State.Rank2_dipl.Played++; e.State.Rank2_dipl.InHand--; e.HTML = "Make a Diplomatic Gesture"; v.Edges.Add(e); e = new Edge(d); e.Invisible = d.Start.Rank3.InHand <= 0; e.State.VertexName = "SubcrisisManeuvering_Rung3"; e.State.Rank3.Played++; e.State.Rank3.InHand--; e.HTML = "Conclude subcrisis and address nation and world."; v.Edges.Add(e); return v; }
public RequestDataViewModel GetRequestResponseTimeGraphData() { RequestDataViewModel rdvm = new RequestDataViewModel(); try { // int setupInterval = GetSetupVal(); int setupInterval = Facade.SettingDomainController.GetValueByName(StaticStrings.ResponseTimeInterval); if (setupInterval <= 0) { setupInterval = 5; } //Better check int iterations = minutesADay / setupInterval; //This is for the current average //Delete all requests that is older than interval Facade.RequestDomainController.DeleteAllOlderThanInterval(setupInterval); //Now get them all, to see the current average List <Request> requestsLastInterval = Facade.RequestDomainController.GetAll(); int averageRightNow = CalculateAverage(requestsLastInterval); GraphData currentAverageData = new GraphData(); currentAverageData.x = DateTime.Now; currentAverageData.y = averageRightNow; //Last 24 hours request summaries. List <RequestSummary> allRequests = Facade.RequestSummaryDomainController.GetOneDayRequestSummaries(); List <GraphData> graphDataResponseTime = new List <GraphData>(); graphDataResponseTime.Add(currentAverageData); for (int i = 2; i < iterations + 1; i++) { var minutes = i * setupInterval; //0, 60, 120 List <RequestSummary> requests = allRequests.Where(x => x.DateTimeCreated >= DateTime.Now.AddMinutes(-minutes) //efter 12:13 && x.DateTimeCreated < DateTime.Now.AddMinutes(-minutes + setupInterval)).ToList(); //før 13:23 //finder vi 13:20 GraphData dataResponse = new GraphData(); DateTime time = GetStartOfInterval(minutes, setupInterval); //Hvis der ikke findes requests i dette interval, brug "time" //tag gennemsnittet fra forrige ? if (requests == null || requests.Count < 1) { dataResponse.y = 0; dataResponse.x = time; } else { // Ellers brug requestets tid. dataResponse.x = requests.LastOrDefault().DateTimeCreated.AddMinutes(setupInterval / 2); //? dataResponse.y = requests.Last().ResponseTime; } graphDataResponseTime.Add(dataResponse); } rdvm.AverageResponseTimeGraphData = graphDataResponseTime; } catch (Exception e) { Log.Error("RequestLogic - GetRequestResponseTimeGraphData: ", e); } return(rdvm); }
public static Vertex Rung2_dipl(GraphData d) { Vertex v = new Vertex(); v.Include = Root + "Rung2_dipl.html"; Edge e; string NextVertexName = "SubcrisisManeuvering_Result"; e = new Edge(d); e.State.VertexName = NextVertexName; //e.State.PerceivedCommitment += 10; //e.State.PublicAwareness += 5; //e.State.PerceivedInflexibility += 10; e.HTML = "Recall an ambassador for lengthy consultation."; v.Edges.Add(e); //soviets recall their ambassador too "for lengthy consultations" e = new Edge(d); //e.Disabled = e.State.PerceivedInflexibility < 5; e.State.VertexName = NextVertexName; //e.State.PerceivedCommitment += 5; //e.State.Pressure += 5; //e.State.PerceivedInflexibility += 10; e.HTML = "Refuse to facilitate negotiations on other issues."; v.Edges.Add(e); //Soviets reciprocate and halt negiotiations on arms control. e = new Edge(d); //e.Disabled = e.State.Prestige < 5; e.State.VertexName = NextVertexName; //e.State.Pressure += 5; //e.State.Prestige -= 5; e.HTML = "Make overtures to the other side's enemies"; v.Edges.Add(e); //Soviets respond with aircraft flights towards said enemies as a show of force. //(enemies are China and Yugoslavia-easy pressure targets) e = new Edge(d); //e.Disabled = e.State.PerceivedInflexibility > 5; e.State.VertexName = NextVertexName; //e.State.Pressure += 5; //e.State.PerceivedInflexibility += 5; e.HTML = "Denounce a treaty"; v.Edges.Add(e); //Soviets denounce a treaty as well. e = new Edge(d); e.State.VertexName = NextVertexName; //e.State.Pressure += 5; //e.State.PerceivedInflexibility += 5; e.HTML = "Make a private threat through diplomatic channels"; v.Edges.Add(e); //If state.pressure is low, Soviets make a private threat back. //If state.pressure is higher, Soviets make the private threat public and denounce it. return v; }
private List <GraphData> SessionDataListToGraphDataList( List <List <SessionData> > sessionDataList, int executionNumber) { List <GraphData> graphDataList = new List <GraphData>(); GraphData aeedGraphData = new GraphData() { YAxisTitle = "AEED Value", Executions = executionNumber, XAxisExecutionsNumber = Enumerable.Range(1, executionNumber).ToList() }; GraphData nroGraphData = new GraphData() { YAxisTitle = "NRO Value", Executions = executionNumber, XAxisExecutionsNumber = Enumerable.Range(1, executionNumber).ToList() }; GraphData bddGraphData = new GraphData() { YAxisTitle = "BDD Value", Executions = executionNumber, XAxisExecutionsNumber = Enumerable.Range(1, executionNumber).ToList() }; GraphData pdrGraphData = new GraphData() { YAxisTitle = "PDR Value", Executions = executionNumber, XAxisExecutionsNumber = Enumerable.Range(1, executionNumber).ToList() }; for (var executionNum = 0; executionNum < sessionDataList.Count; executionNum++) { foreach (var sessionData in sessionDataList[executionNum]) { if (sessionData.tabIndex == 0) { aeedGraphData.YAxisValuesDsr.Add(sessionData.CalculateAverageEndToEndDelay()); nroGraphData.YAxisValuesDsr.Add(sessionData.CalculateNormalizedRoutingOverhead()); bddGraphData.YAxisValuesDsr.Add(sessionData.CalculateBatteryDepletionDeviation()); pdrGraphData.YAxisValuesDsr.Add(sessionData.CalculatePacketDeliveryRatio()); } else if (sessionData.tabIndex == 1) { aeedGraphData.YAxisValuesSadsr.Add(sessionData.CalculateAverageEndToEndDelay()); nroGraphData.YAxisValuesSadsr.Add(sessionData.CalculateNormalizedRoutingOverhead()); bddGraphData.YAxisValuesSadsr.Add(sessionData.CalculateBatteryDepletionDeviation()); pdrGraphData.YAxisValuesSadsr.Add(sessionData.CalculatePacketDeliveryRatio()); } else if (sessionData.tabIndex == 2) { aeedGraphData.YAxisValuesMsadsr.Add(sessionData.CalculateAverageEndToEndDelay()); nroGraphData.YAxisValuesMsadsr.Add(sessionData.CalculateNormalizedRoutingOverhead()); bddGraphData.YAxisValuesMsadsr.Add(sessionData.CalculateBatteryDepletionDeviation()); pdrGraphData.YAxisValuesMsadsr.Add(sessionData.CalculatePacketDeliveryRatio()); } } } graphDataList.Add(aeedGraphData); graphDataList.Add(nroGraphData); graphDataList.Add(bddGraphData); graphDataList.Add(pdrGraphData); foreach (var graphData in graphDataList) { double averageDsr = graphData.YAxisValuesDsr.Where(x => x != -1).Average(); double averageSadsr = graphData.YAxisValuesSadsr.Where(x => x != -1).Average(); double averageMsadsr = graphData.YAxisValuesMsadsr.Where(x => x != -1).Average(); graphData.AverageDsr = averageDsr; graphData.AverageSadsr = averageSadsr; graphData.AverageMsadsr = averageMsadsr; } return(graphDataList); }
public void Verify_Edge_With_No_Ghost_Nodes_Is_Added_To_Physical_Graph() { int actualSourceEdges; int actualTargetEdges; int expectedSourceEdges = 1; int expectedTargetEdges = 1; INode source = PrepareNode("Node1", ghostNode: false); INode target = PrepareNode("Node2", ghostNode: false); IEdge edge = new Edge(source, target); GraphData graphData = new GraphData("scope"); // Add an edge without ghost nodes to the graph graphData.AddNode(source); graphData.AddNode(target); graphData.AddEdge(edge); // Get the actual count for nodes actualSourceEdges = graphData.Edges(source).Count(); actualTargetEdges = graphData.Edges(target).Count(); Assert.AreEqual(expectedSourceEdges, actualSourceEdges); Assert.AreEqual(expectedTargetEdges, actualTargetEdges); }
// Use this for initialization void Start() { graphData = GraphData.gd; }
public void ToSubGraph() { var graphView = graphEditorView.graphView; var path = EditorUtility.SaveFilePanelInProject("Save Sub Graph", "New Shader Sub Graph", ShaderSubGraphImporter.Extension, ""); path = path.Replace(Application.dataPath, "Assets"); if (path.Length == 0) { return; } graphObject.RegisterCompleteObjectUndo("Convert To Subgraph"); var nodes = graphView.selection.OfType <IShaderNodeView>().Where(x => !(x.node is PropertyNode || x.node is SubGraphOutputNode)).Select(x => x.node).Where(x => x.allowedInSubGraph).ToArray(); var bounds = Rect.MinMaxRect(float.PositiveInfinity, float.PositiveInfinity, float.NegativeInfinity, float.NegativeInfinity); foreach (var node in nodes) { var center = node.drawState.position.center; bounds = Rect.MinMaxRect( Mathf.Min(bounds.xMin, center.x), Mathf.Min(bounds.yMin, center.y), Mathf.Max(bounds.xMax, center.x), Mathf.Max(bounds.yMax, center.y)); } var middle = bounds.center; bounds.center = Vector2.zero; // Collect graph inputs var graphInputs = graphView.selection.OfType <BlackboardField>().Select(x => x.userData as ShaderInput); // Collect the property nodes and get the corresponding properties var propertyNodeGuids = graphView.selection.OfType <IShaderNodeView>().Where(x => (x.node is PropertyNode)).Select(x => ((PropertyNode)x.node).propertyGuid); var metaProperties = graphView.graph.properties.Where(x => propertyNodeGuids.Contains(x.guid)); // Collect the keyword nodes and get the corresponding keywords var keywordNodeGuids = graphView.selection.OfType <IShaderNodeView>().Where(x => (x.node is KeywordNode)).Select(x => ((KeywordNode)x.node).keywordGuid); var metaKeywords = graphView.graph.keywords.Where(x => keywordNodeGuids.Contains(x.guid)); var copyPasteGraph = new CopyPasteGraph( graphView.graph.assetGuid, graphView.selection.OfType <ShaderGroup>().Select(x => x.userData), graphView.selection.OfType <IShaderNodeView>().Where(x => !(x.node is PropertyNode || x.node is SubGraphOutputNode)).Select(x => x.node).Where(x => x.allowedInSubGraph).ToArray(), graphView.selection.OfType <Edge>().Select(x => x.userData as IEdge), graphInputs, metaProperties, metaKeywords, graphView.selection.OfType <StickyNote>().Select(x => x.userData)); var deserialized = CopyPasteGraph.FromJson(JsonUtility.ToJson(copyPasteGraph, false)); if (deserialized == null) { return; } var subGraph = new GraphData { isSubGraph = true }; subGraph.path = "Sub Graphs"; var subGraphOutputNode = new SubGraphOutputNode(); { var drawState = subGraphOutputNode.drawState; drawState.position = new Rect(new Vector2(bounds.xMax + 200f, 0f), drawState.position.size); subGraphOutputNode.drawState = drawState; } subGraph.AddNode(subGraphOutputNode); // Always copy deserialized keyword inputs foreach (ShaderKeyword keyword in deserialized.metaKeywords) { ShaderInput copiedInput = keyword.Copy(); subGraph.SanitizeGraphInputName(copiedInput); subGraph.SanitizeGraphInputReferenceName(copiedInput, keyword.overrideReferenceName); subGraph.AddGraphInput(copiedInput); // Update the keyword nodes that depends on the copied keyword var dependentKeywordNodes = deserialized.GetNodes <KeywordNode>().Where(x => x.keywordGuid == keyword.guid); foreach (var node in dependentKeywordNodes) { node.owner = graphView.graph; node.keywordGuid = copiedInput.guid; } } var groupGuidMap = new Dictionary <Guid, Guid>(); foreach (GroupData groupData in deserialized.groups) { var oldGuid = groupData.guid; var newGuid = groupData.RewriteGuid(); groupGuidMap[oldGuid] = newGuid; subGraph.CreateGroup(groupData); } List <Guid> groupGuids = new List <Guid>(); var nodeGuidMap = new Dictionary <Guid, Guid>(); foreach (var node in deserialized.GetNodes <AbstractMaterialNode>()) { var oldGuid = node.guid; var newGuid = node.RewriteGuid(); nodeGuidMap[oldGuid] = newGuid; var drawState = node.drawState; drawState.position = new Rect(drawState.position.position - middle, drawState.position.size); node.drawState = drawState; if (!groupGuids.Contains(node.groupGuid)) { groupGuids.Add(node.groupGuid); } // Checking if the group guid is also being copied. // If not then nullify that guid if (node.groupGuid != Guid.Empty) { node.groupGuid = !groupGuidMap.ContainsKey(node.groupGuid) ? Guid.Empty : groupGuidMap[node.groupGuid]; } subGraph.AddNode(node); } foreach (var note in deserialized.stickyNotes) { if (!groupGuids.Contains(note.groupGuid)) { groupGuids.Add(note.groupGuid); } if (note.groupGuid != Guid.Empty) { note.groupGuid = !groupGuidMap.ContainsKey(note.groupGuid) ? Guid.Empty : groupGuidMap[note.groupGuid]; } note.RewriteGuid(); subGraph.AddStickyNote(note); } // figure out what needs remapping var externalOutputSlots = new List <IEdge>(); var externalInputSlots = new List <IEdge>(); foreach (var edge in deserialized.edges) { var outputSlot = edge.outputSlot; var inputSlot = edge.inputSlot; Guid remappedOutputNodeGuid; Guid remappedInputNodeGuid; var outputSlotExistsInSubgraph = nodeGuidMap.TryGetValue(outputSlot.nodeGuid, out remappedOutputNodeGuid); var inputSlotExistsInSubgraph = nodeGuidMap.TryGetValue(inputSlot.nodeGuid, out remappedInputNodeGuid); // pasting nice internal links! if (outputSlotExistsInSubgraph && inputSlotExistsInSubgraph) { var outputSlotRef = new SlotReference(remappedOutputNodeGuid, outputSlot.slotId); var inputSlotRef = new SlotReference(remappedInputNodeGuid, inputSlot.slotId); subGraph.Connect(outputSlotRef, inputSlotRef); } // one edge needs to go to outside world else if (outputSlotExistsInSubgraph) { externalInputSlots.Add(edge); } else if (inputSlotExistsInSubgraph) { externalOutputSlots.Add(edge); } } // Find the unique edges coming INTO the graph var uniqueIncomingEdges = externalOutputSlots.GroupBy( edge => edge.outputSlot, edge => edge, (key, edges) => new { slotRef = key, edges = edges.ToList() }); var externalInputNeedingConnection = new List <KeyValuePair <IEdge, AbstractShaderProperty> >(); var amountOfProps = uniqueIncomingEdges.Count(); const int height = 40; const int subtractHeight = 20; var propPos = new Vector2(0, -((amountOfProps / 2) + height) - subtractHeight); foreach (var group in uniqueIncomingEdges) { var sr = group.slotRef; var fromNode = graphObject.graph.GetNodeFromGuid(sr.nodeGuid); var fromSlot = fromNode.FindOutputSlot <MaterialSlot>(sr.slotId); AbstractShaderProperty prop; switch (fromSlot.concreteValueType) { case ConcreteSlotValueType.Texture2D: prop = new Texture2DShaderProperty(); break; case ConcreteSlotValueType.Texture2DArray: prop = new Texture2DArrayShaderProperty(); break; case ConcreteSlotValueType.Texture3D: prop = new Texture3DShaderProperty(); break; case ConcreteSlotValueType.Cubemap: prop = new CubemapShaderProperty(); break; case ConcreteSlotValueType.Vector4: prop = new Vector4ShaderProperty(); break; case ConcreteSlotValueType.Vector3: prop = new Vector3ShaderProperty(); break; case ConcreteSlotValueType.Vector2: prop = new Vector2ShaderProperty(); break; case ConcreteSlotValueType.Vector1: prop = new Vector1ShaderProperty(); break; case ConcreteSlotValueType.Boolean: prop = new BooleanShaderProperty(); break; case ConcreteSlotValueType.Matrix2: prop = new Matrix2ShaderProperty(); break; case ConcreteSlotValueType.Matrix3: prop = new Matrix3ShaderProperty(); break; case ConcreteSlotValueType.Matrix4: prop = new Matrix4ShaderProperty(); break; case ConcreteSlotValueType.SamplerState: prop = new SamplerStateShaderProperty(); break; case ConcreteSlotValueType.Gradient: prop = new GradientShaderProperty(); break; default: throw new ArgumentOutOfRangeException(); } if (prop != null) { var materialGraph = (GraphData)graphObject.graph; var fromPropertyNode = fromNode as PropertyNode; var fromProperty = fromPropertyNode != null?materialGraph.properties.FirstOrDefault(p => p.guid == fromPropertyNode.propertyGuid) : null; prop.displayName = fromProperty != null ? fromProperty.displayName : fromSlot.concreteValueType.ToString(); subGraph.AddGraphInput(prop); var propNode = new PropertyNode(); { var drawState = propNode.drawState; drawState.position = new Rect(new Vector2(bounds.xMin - 300f, 0f) + propPos, drawState.position.size); propPos += new Vector2(0, height); propNode.drawState = drawState; } subGraph.AddNode(propNode); propNode.propertyGuid = prop.guid; foreach (var edge in group.edges) { subGraph.Connect( new SlotReference(propNode.guid, PropertyNode.OutputSlotId), new SlotReference(nodeGuidMap[edge.inputSlot.nodeGuid], edge.inputSlot.slotId)); externalInputNeedingConnection.Add(new KeyValuePair <IEdge, AbstractShaderProperty>(edge, prop)); } } } var uniqueOutgoingEdges = externalInputSlots.GroupBy( edge => edge.outputSlot, edge => edge, (key, edges) => new { slot = key, edges = edges.ToList() }); var externalOutputsNeedingConnection = new List <KeyValuePair <IEdge, IEdge> >(); foreach (var group in uniqueOutgoingEdges) { var outputNode = subGraph.outputNode as SubGraphOutputNode; AbstractMaterialNode node = graphView.graph.GetNodeFromGuid(group.edges[0].outputSlot.nodeGuid); MaterialSlot slot = node.FindSlot <MaterialSlot>(group.edges[0].outputSlot.slotId); var slotId = outputNode.AddSlot(slot.concreteValueType); var inputSlotRef = new SlotReference(outputNode.guid, slotId); foreach (var edge in group.edges) { var newEdge = subGraph.Connect(new SlotReference(nodeGuidMap[edge.outputSlot.nodeGuid], edge.outputSlot.slotId), inputSlotRef); externalOutputsNeedingConnection.Add(new KeyValuePair <IEdge, IEdge>(edge, newEdge)); } } if (FileUtilities.WriteShaderGraphToDisk(path, subGraph)) { AssetDatabase.ImportAsset(path); } var loadedSubGraph = AssetDatabase.LoadAssetAtPath(path, typeof(SubGraphAsset)) as SubGraphAsset; if (loadedSubGraph == null) { return; } var subGraphNode = new SubGraphNode(); var ds = subGraphNode.drawState; ds.position = new Rect(middle - new Vector2(100f, 150f), Vector2.zero); subGraphNode.drawState = ds; // Add the subgraph into the group if the nodes was all in the same group group if (groupGuids.Count == 1) { subGraphNode.groupGuid = groupGuids[0]; } graphObject.graph.AddNode(subGraphNode); subGraphNode.asset = loadedSubGraph; foreach (var edgeMap in externalInputNeedingConnection) { graphObject.graph.Connect(edgeMap.Key.outputSlot, new SlotReference(subGraphNode.guid, edgeMap.Value.guid.GetHashCode())); } foreach (var edgeMap in externalOutputsNeedingConnection) { graphObject.graph.Connect(new SlotReference(subGraphNode.guid, edgeMap.Value.inputSlot.slotId), edgeMap.Key.inputSlot); } graphObject.graph.RemoveElements( graphView.selection.OfType <IShaderNodeView>().Select(x => x.node).Where(x => x.allowedInSubGraph).ToArray(), new IEdge[] {}, new GroupData[] {}, graphView.selection.OfType <StickyNote>().Select(x => x.userData).ToArray()); graphObject.graph.ValidateGraph(); }
// updates the graphs and laps and stats (called on initial load in of a file) public void updateGraphsAndDataEntire() { StatsDisplayName = null; ActivityLoaded = true; double max = 0; double min = 0; DateTime start = ActiveActivity.Laps.First().Trackpoints.First().Time; //update watts graph if (ActiveType == Sport.Biking) { List <DataPoint> wattsDataPoints = new List <DataPoint>(ActiveActivity.Laps.SelectMany(x => x.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), (y.Extensions as BikeExtension).Watts))).ToList()); max = wattsDataPoints.Max(x => x.X) + 1; min = wattsDataPoints.Min(x => x.X); if (wattsDataPoints[0].Y >= 0) { WattsData = new GraphData(wattsDataPoints, max, min); } else { WattsData = null; } } // update hr graph List <DataPoint> hrDataPoints = new List <DataPoint>(ActiveActivity.Laps.SelectMany(x => x.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), y.HeartRate)).ToList())); max = hrDataPoints.Max(x => x.X) + 1; min = hrDataPoints.Min(x => x.X); if (hrDataPoints[0].Y >= 0) { HeartRateData = new GraphData(hrDataPoints, max, min); } else { HeartRateData = null; } //update speed graph List <DataPoint> speedDataPoints = new List <DataPoint>(ActiveActivity.Laps.SelectMany(x => x.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), y.Extensions.Speed)).ToList())); max = speedDataPoints.Max(x => x.X) + 1; min = speedDataPoints.Min(x => x.X); if (speedDataPoints[0].Y >= 0) { SpeedData = new GraphData(speedDataPoints, max, min); } else { SpeedData = null; } if (ActiveType == Sport.Biking) { // update cadence graph List <DataPoint> cadenceDataPoints = new List <DataPoint>(ActiveActivity.Laps.SelectMany(x => x.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), y.Cadence)).ToList())); max = cadenceDataPoints.Max(x => x.X) + 1; min = cadenceDataPoints.Min(x => x.X); if (cadenceDataPoints[0].Y >= 0) { CadenceData = new GraphData(cadenceDataPoints, max, min); } else { CadenceData = null; } } else if (ActiveType == Sport.Running) { // update cadence graph List <DataPoint> cadenceDataPoints = new List <DataPoint>(ActiveActivity.Laps.SelectMany(x => x.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), (y.Extensions as RunExtension).Cadence)).ToList())); max = cadenceDataPoints.Max(x => x.X) + 1; min = cadenceDataPoints.Min(x => x.X); if (cadenceDataPoints[0].Y >= 0) { CadenceData = new GraphData(cadenceDataPoints, max, min); } else { CadenceData = null; } } // update elevation graph List <DataPoint> altitudeDataPoints = new List <DataPoint>(ActiveActivity.Laps.SelectMany(x => x.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), y.Altitude)).ToList())); max = altitudeDataPoints.Max(x => x.X) + 1; min = altitudeDataPoints.Min(x => x.X); if (altitudeDataPoints[0].Y != -1) { ElevationData = new GraphData(altitudeDataPoints, max, min); } else { ElevationData = null; } //update hr stats if (ActiveActivity != null) { double avg = ActiveActivity.AvgHeartRate; double maxim = ActiveActivity.MaxHeartRate; if (avg < 0) { HeartRateInfo = "No HR data provided :("; } else { HeartRateInfo = "Average: " + Math.Round(avg, 0) + " bpm\nMax: " + Math.Round(maxim, 0) + " bpm"; } } //update cadence stats if (ActiveActivity != null) { if (ActiveActivity is BikeActivity) { BikeActivity b = (BikeActivity)ActiveActivity; double avg = b.AvgCadence; double maxim = b.MaxCadence; if (avg < 0) { CadenceInfo = "No cadence data provided :("; } else { CadenceInfo = "Average: " + Math.Round(avg, 0) + " rpm\nMax: " + Math.Round(maxim, 0) + " rpm"; } } else if (ActiveActivity is RunActivity) { RunActivity a = (RunActivity)ActiveActivity; double avg = a.AvgCadence; double maxim = a.MaxCadence; if (avg < 0) { CadenceInfo = "No cadence data provided :("; } else { CadenceInfo = "Average: " + Math.Round(avg, 0) + " spm\nMax: " + Math.Round(maxim, 0) + " spm"; } } } // update speed stats if (ActiveActivity != null) { double avg = ActiveActivity.AvgSpeed; double maxim = ActiveActivity.MaxSpeed; if (avg < 0) { SpeedInfo = "No speed data provided :("; } else { SpeedInfo = "Average: " + Math.Round(avg, 2) + " mph\nMax: " + Math.Round(maxim, 2) + " mph"; } } // update watts stats if (ActiveActivity != null) { if (ActiveActivity is BikeActivity) { BikeActivity b = (BikeActivity)ActiveActivity; double avg = b.AvgPower; double maxim = b.MaxPower; if (avg < 0) { WattsInfo = "No power data provided :("; } else { WattsInfo = "Average: " + Math.Round(avg, 0) + " W\nMax: " + Math.Round(maxim, 0) + " W"; } } else { WattsInfo = "No power data provided :("; } } //update elevation stats if (ActiveActivity != null) { var ascList = ActiveActivity.Laps.Select(x => x.ElevationGain); var descList = ActiveActivity.Laps.Select(x => x.ElevationLoss); double asc = 0; double desc = 0; foreach (double a in ascList) { asc += a; } foreach (double d in descList) { desc += d; } double largest = ActiveActivity.Laps.Max(x => x.BiggestClimb); if (asc < 0 && desc < 0) { ElevationInfo = "No elevation data provided :("; } else { ElevationInfo = "Ascent: " + Math.Round(asc, 0) + " ft\nDescent: " + Math.Round(desc, 0) + " ft\nLargest climb: " + Math.Round(largest, 0) + " ft"; } } }
private List<Point> GetPointsZoom(GraphData graphData) { List<Point> list = new List<Point>(); if ((FrameZoom.Height != 0) && (FrameZoom.Width != 0)) { Point item = new Point(); for (int i = 0; i < graphData.Value.Count; i++) { int num = (frameFull.Right - graphData.Value.Count) + i; item.Y = workingArea.Bottom - ((workingArea.Height * (graphData.Value[i] - FrameZoom.Bottom)) / FrameZoom.Height); item.X = workingArea.Right - ((workingArea.Width * (FrameZoom.Right - num)) / FrameZoom.Width); list.Add(item); } } return list; }
public void AddGraph(GraphData graph) { InitNonExistingRepo(); repo.AddGraph(graph); }