public NetworkLayoutRecord( BayesianNetwork network, NetworkLayout layout, NetworkLayoutOptions options) { Debug.Assert(options != null, "Layout options cannot be null."); this.Network = network; this.NetworkLayout = layout; this.Options = options; // Manually specify sizes. Dictionary <string, float> sizes = new Dictionary <string, float>(); foreach (var v in network.Variables) { sizes[v.Key] = Workbench.NetworkLayoutVertexSizeNormal; } // Instantiate algorithm. AlgorithmState = new LayoutAlgorithm(network.Clone(), sizes, options); // Copy existing positions over. if (layout != null && layout.Positions != null && layout.Positions.Count > 0) { foreach (var kvp in layout.Positions) { AlgorithmState.Positions[kvp.Key] = kvp.Value; } } }
static void Main(string[] args) { // deserialize JSON directly from a file Console.Write("Reading and Deserializing responseDumpbeforeLayout.txt ... "); Timeline root; using (var file = File.OpenText(@"C:\Users\Wahib\Desktop\responseDumpbeforeLayout.txt")) { var serializer = new JsonSerializer(); root = (Timeline)serializer.Deserialize(file, typeof(Timeline)); } Console.WriteLine("[Done]"); // calculating layout Console.Write("Calculating Layout ... "); var layoutAlg = new LayoutAlgorithm(); layoutAlg.CalulateLayout(root); Console.WriteLine("[Done]"); // converting layout to scene graph Console.Write("Converting layout to scene graph ... "); var sceneGraph = layoutAlg.Convert(root); Console.WriteLine("[Done]"); // serialize scenegraph directly to a JSON file Console.Write("Serializing and Writting responseDumpafterLayout.txt ... "); using (var file = File.CreateText(@"C:\Users\Wahib\Desktop\responseDumpafterLayout.txt")) { var serializer = new JsonSerializer(); serializer.Serialize(file, sceneGraph); } Console.WriteLine("[Done]"); Console.WriteLine("Press any key to exit ..."); Console.ReadKey(); }
public void TestLayout() { var dataSource = new TestDataSource(); new TestDataGen().GenerateDataItems(dataSource, 10, 0); var boxContainer = new BoxContainer(dataSource); TestDataGen.GenerateBoxSizes(boxContainer); var diagram = new Diagram(); diagram.Boxes = boxContainer; diagram.LayoutSettings.LayoutStrategies.Add("default", new LinearLayoutStrategy()); diagram.LayoutSettings.DefaultLayoutStrategyId = "default"; var state = new LayoutState(diagram) { BoxSizeFunc = dataId => boxContainer.BoxesByDataId[dataId].Size }; LayoutAlgorithm.Apply(state); Assert.AreEqual(5, diagram.VisualTree?.Depth); }
public void Convert(FileInfo dotFile, FileInfo plainFile) { try { string arguments; if (Algorithm == LayoutAlgorithm.Hierarchy || Algorithm == LayoutAlgorithm.Flow || Algorithm == LayoutAlgorithm.Auto) { RunWithDot(out arguments, dotFile, plainFile); } else { RunWithSfdp(out arguments, dotFile, plainFile); } var startInfo = new ProcessStartInfo("cmd", arguments); startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.WorkingDirectory = Path.GetTempPath(); var stdErr = new StringWriter(); var ret = Processes.Execute(startInfo, null, stdErr); if (Algorithm == LayoutAlgorithm.Sfdp) { // ignore the error code for this engine - it mostly still works :) ret = 0; } if (ret != 0 || !plainFile.Exists || dotFile.LastWriteTime > plainFile.LastWriteTime) { // limit the size of the error message otherwise we will blow the messagebox window // showing this unhandled exception later on var msg = stdErr.ToString(); if (msg.Length > 512) { msg = msg.Substring(0, 512); } throw new InvalidOperationException("Dot plain file generation failed: " + msg); } } catch { if (Algorithm == LayoutAlgorithm.Hierarchy || Algorithm == LayoutAlgorithm.Flow || Algorithm == LayoutAlgorithm.Auto) { // unfort dot.exe dies quite often with "trouble in init_rank" if graph is too complex // -> try fallback with sfdp.exe Algorithm = LayoutAlgorithm.Sfdp; Convert(dotFile, plainFile); } else { throw; } } }
private void QuickLayout() { var state = new LayoutState(m_diagram); state.BoxSizeFunc = dataId => m_diagram.Boxes.BoxesByDataId[dataId].Size; state.LayoutOptimizerFunc = LayoutOptimizer; LayoutAlgorithm.Apply(state); RenderBoxes(m_diagram.VisualTree, DrawCanvas); }
public CircleNodeScene() { this.mGraph = new Digraph <CircleNode, ArrowEdge>(); this.mLayoutTimer = new Timer(); this.mLayoutTimer.Interval = 1000 / 25; this.mLayoutTimer.Tick += new EventHandler(OnLayoutTimerTick); this.mLayout = null; this.mMouseUpHistory = new int[3]; for (int i = 0; i < this.mMouseUpHistory.Length; i++) { this.mMouseUpHistory[i] = -1; } }
private void layoutAlgSelectedIndexChanged(object sender, EventArgs e) { if (this.layoutAlgCMB.SelectedIndex != this.mPrevLayoutIndex) { this.mPrevLayoutIndex = this.layoutAlgCMB.SelectedIndex; this.mScene.Layout = this.mLayouts[this.mPrevLayoutIndex]; this.layoutStartStopBTN.Text = "Start"; LayoutAlgorithm <CircleNode, ArrowEdge> alg = this.mLayouts[this.mPrevLayoutIndex]; /*if (alg.Spring == null) * { * this.layoutParamsGrid.SelectedObject = alg;//.Parameters; * } * else * { * this.layoutParamsGrid.SelectedObjects * = new object[] { alg, alg.Spring }; * }/* */ this.layoutParamsGrid.SelectedObject = alg;//.Parameters; } }
public TreemapGenerator() { this.m_oNodes = new Nodes(null); this.m_oNodes.TreemapGenerator = this; this.m_iPaddingPx = 5; this.m_iPaddingDecrementPerLevelPx = 1; this.m_iPenWidthPx = 3; this.m_iPenWidthDecrementPerLevelPx = 1; this.m_oBackColor = SystemColors.Window; this.m_oBorderColor = SystemColors.WindowFrame; this.m_eNodeColorAlgorithm = NodeColorAlgorithm.UseColorMetric; this.m_oMinColor = Color.Red; this.m_oMaxColor = Color.Green; this.m_fMinColorMetric = -100f; this.m_fMaxColorMetric = 100f; this.m_iDiscretePositiveColors = 20; this.m_iDiscreteNegativeColors = 20; this.m_sFontFamily = "Arial"; this.m_fFontMinSizePt = 8f; this.m_fFontMaxSizePt = 100f; this.m_fFontIncrementPt = 2f; this.m_oFontSolidColor = SystemColors.WindowText; this.m_iFontMinAlpha = 105; this.m_iFontMaxAlpha = 255; this.m_iFontAlphaIncrementPerLevel = 50; this.m_oSelectedFontColor = SystemColors.HighlightText; this.m_oSelectedBackColor = SystemColors.Highlight; this.m_iNodeLevelsWithText = NodeLevelsWithText.All; this.m_iMinNodeLevelWithText = 0; this.m_iMaxNodeLevelWithText = 999; this.m_eTextLocation = TextLocation.Top; this.m_eEmptySpaceLocation = EmptySpaceLocation.DeterminedByLayoutAlgorithm; this.m_oSelectedNode = null; this.m_oSavedSelectedNodeBitmap = null; this.m_bInBeginUpdate = false; this.m_eLayoutAlgorithm = LayoutAlgorithm.BottomWeightedSquarified; }
protected override void OnValueChanged(ModelRoot element, LayoutAlgorithm oldValue, LayoutAlgorithm newValue) { base.OnValueChanged(element, oldValue, newValue); if (!element.Store.InUndoRedoOrRollback) { // if this is the first time we've been here, cache what's alread there if (oldValue != LayoutAlgorithm.Default && !settingsCache.ContainsKey(oldValue) && element.LayoutAlgorithmSettings != null) { settingsCache[oldValue] = element.LayoutAlgorithmSettings; } // use the prior settings for this layout type if available if (newValue != LayoutAlgorithm.Default && settingsCache.ContainsKey(newValue)) { element.LayoutAlgorithmSettings = settingsCache[newValue]; } else { // if not, set some defaults that make sense in our context switch (newValue) { case LayoutAlgorithm.Default: element.LayoutAlgorithmSettings = null; return; case LayoutAlgorithm.FastIncremental: FastIncrementalLayoutSettings fastIncrementalLayoutSettings = new FastIncrementalLayoutSettings(); element.LayoutAlgorithmSettings = fastIncrementalLayoutSettings; break; case LayoutAlgorithm.MDS: MdsLayoutSettings mdsLayoutSettings = new MdsLayoutSettings(); mdsLayoutSettings.ScaleX = 1; mdsLayoutSettings.ScaleY = 1; mdsLayoutSettings.AdjustScale = true; mdsLayoutSettings.RemoveOverlaps = true; element.LayoutAlgorithmSettings = mdsLayoutSettings; break; case LayoutAlgorithm.Ranking: RankingLayoutSettings rankingLayoutSettings = new RankingLayoutSettings(); rankingLayoutSettings.ScaleX = 1; rankingLayoutSettings.ScaleY = 1; element.LayoutAlgorithmSettings = rankingLayoutSettings; break; case LayoutAlgorithm.Sugiyama: SugiyamaLayoutSettings sugiyamaLayoutSettings = new SugiyamaLayoutSettings { LayerSeparation = 1, MinNodeHeight = 1, MinNodeWidth = 1 }; element.LayoutAlgorithmSettings = sugiyamaLayoutSettings; break; } element.LayoutAlgorithmSettings.ClusterMargin = 1; element.LayoutAlgorithmSettings.NodeSeparation = 1; element.LayoutAlgorithmSettings.EdgeRoutingSettings.Padding = .3; element.LayoutAlgorithmSettings.EdgeRoutingSettings.PolylinePadding = 1.5; element.LayoutAlgorithmSettings.EdgeRoutingSettings.EdgeRoutingMode = EdgeRoutingMode.StraightLine; settingsCache[newValue] = element.LayoutAlgorithmSettings; } } }
public NetworkLayoutRecord( BayesianNetwork network, NetworkLayout layout, NetworkLayoutOptions options) { Debug.Assert(options != null, "Layout options cannot be null."); this.Network = network; this.NetworkLayout = layout; this.Options = options; // Manually specify sizes. Dictionary<string, float> sizes = new Dictionary<string, float>(); foreach (var v in network.Variables) { sizes[v.Key] = Workbench.NetworkLayoutVertexSizeNormal; } // Instantiate algorithm. AlgorithmState = new LayoutAlgorithm(network.Clone(), sizes, options); // Copy existing positions over. if (layout != null && layout.Positions != null && layout.Positions.Count > 0) { foreach (var kvp in layout.Positions) { AlgorithmState.Positions[kvp.Key] = kvp.Value; } } }
private void StartLayout(bool resetBoxes) { TextLayoutTimeElapsed.Text = string.Empty; // release any existing progress on background layout m_progressWaitHandle?.Dispose(); m_progressWaitHandle = new AutoResetEvent(true); // re-create source data, diagram and layout data structures if (resetBoxes || m_diagram == null) { m_dataSource = new TestDataSource(); new TestDataGen().GenerateDataItems((TestDataSource)m_dataSource, 200, 5); //m_dataSource = new DebugDataSource(); //await ((DebugDataSource)m_dataSource).Load(); var boxContainer = new BoxContainer(m_dataSource); TestDataGen.GenerateBoxSizes(boxContainer); //await ((DebugDataSource)m_dataSource).ApplyState(boxContainer); foreach (var box in boxContainer.BoxesById.Values) { if (!box.IsSpecial) { box.IsCollapsed = true; } } m_diagram = new Diagram { Boxes = boxContainer }; m_diagram.LayoutSettings.LayoutStrategies.Add("linear", new LinearLayoutStrategy { ParentAlignment = BranchParentAlignment.Center }); m_diagram.LayoutSettings.LayoutStrategies.Add("hanger", new MultiLineHangerLayoutStrategy { ParentAlignment = BranchParentAlignment.Center }); m_diagram.LayoutSettings.LayoutStrategies.Add("singleColumn", new SingleColumnLayoutStrategy { ParentAlignment = BranchParentAlignment.Left }); m_diagram.LayoutSettings.LayoutStrategies.Add("fishbone1", new MultiLineFishboneLayoutStrategy { ParentAlignment = BranchParentAlignment.Center, MaxGroups = 1 }); m_diagram.LayoutSettings.LayoutStrategies.Add("fishbone2", new MultiLineFishboneLayoutStrategy { ParentAlignment = BranchParentAlignment.Center, MaxGroups = 2 }); m_diagram.LayoutSettings.LayoutStrategies.Add("hstack1", new StackingLayoutStrategy { Orientation = StackOrientation.SingleRowHorizontal }); m_diagram.LayoutSettings.LayoutStrategies.Add("vstack1", new StackingLayoutStrategy { Orientation = StackOrientation.SingleColumnVertical }); m_diagram.LayoutSettings.LayoutStrategies.Add("assistants", new FishboneAssistantsLayoutStrategy { ParentAlignment = BranchParentAlignment.Center }); m_diagram.LayoutSettings.DefaultLayoutStrategyId = "hanger"; m_diagram.LayoutSettings.DefaultAssistantLayoutStrategyId = "assistants"; //m_diagram.LayoutSettings.BranchSpacing = 5; } var state = new LayoutState(m_diagram); if (CbInteractiveMode.IsChecked.GetValueOrDefault(false)) { state.BoundaryChanged += StateBoundaryChanged; } state.OperationChanged += StateOperationChanged; state.LayoutOptimizerFunc = LayoutOptimizer; Task.Factory.StartNew(() => { m_timer = Stopwatch.StartNew(); LayoutAlgorithm.Apply(state); m_timer.Stop(); Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { TextLayoutTimeElapsed.Text = m_timer.Elapsed.ToString(); }); }) .ContinueWith( (prev, s) => { m_progressWaitHandle.Dispose(); m_progressWaitHandle = null; }, null, TaskContinuationOptions.None); }
private void RenderBoxes(BoxTree visualTree, Canvas drawCanvas) { drawCanvas.Children.Clear(); var boundingRect = LayoutAlgorithm.ComputeBranchVisualBoundingRect(visualTree); drawCanvas.Width = boundingRect.Size.Width; drawCanvas.Height = boundingRect.Size.Height; drawCanvas.RenderTransform = new TranslateTransform { X = -boundingRect.Left, Y = -boundingRect.Top }; Func <BoxTree.Node, bool> renderBox = node => { if (node.Level == 0) { return(true); } if (node.State.IsHidden) { return(true); } var box = node.Element; var frame = node.State; var branchFrameRectangle = new Rectangle { RenderTransform = new TranslateTransform { X = node.State.BranchExterior.Left, Y = node.State.BranchExterior.Top }, Width = node.State.BranchExterior.Size.Width, Height = node.State.BranchExterior.Size.Height, Stroke = new SolidColorBrush(Colors.Blue) { Opacity = 0.6 }, StrokeThickness = 0.5, DataContext = box }; var boxRectangle = new Rectangle { RenderTransform = new TranslateTransform { X = frame.Left, Y = frame.Top }, Width = frame.Size.Width, Height = frame.Size.Height, Fill = new SolidColorBrush(GetBoxFillColor(node)) { Opacity = box.IsSpecial ? 0.1 : 1 }, Stroke = new SolidColorBrush(GetBoxStroke(box)) { Opacity = box.IsSpecial ? 0.1 : 1 }, IsHitTestVisible = !box.IsSpecial, StrokeThickness = 1, DataContext = box }; boxRectangle.DoubleTapped += BoxOnDoubleTapped; drawCanvas.Children.Add(boxRectangle); drawCanvas.Children.Add(branchFrameRectangle); drawCanvas.Children.Add(new TextBlock { RenderTransform = new TranslateTransform { X = frame.Left + 5, Y = frame.Top + 5 }, Width = double.NaN, Height = double.NaN, Text = box.IsSpecial ? "" : TrimText($"{box.Id} ({box.DataId})"), IsHitTestVisible = false }); if (!box.IsCollapsed && node.State.Connector != null) { var solidBrush = new SolidColorBrush(Colors.Black); foreach (var edge in node.State.Connector.Segments) { var line = new Line { X1 = edge.From.X, Y1 = edge.From.Y, X2 = edge.To.X, Y2 = edge.To.Y, Stroke = solidBrush, StrokeEndLineCap = PenLineCap.Round, StrokeThickness = 1, IsHitTestVisible = false }; if (box.IsSpecial) { var len = Math.Max(Math.Abs(line.X2 - line.X1), Math.Abs(line.Y2 - line.Y1)); if (len > 2) { line.StrokeDashArray = new DoubleCollection { 2 }; } } drawCanvas.Children.Add(line); } } return(true); }; visualTree.IterateChildFirst(renderBox); }
static void Main(string[] args) { Timeline root; var sw = new Stopwatch(); /* Console.Write("Generate Testing Data ... "); sw.Start(); root = Utility.GenerateTestingData(100, 10, 0); sw.Stop(); Console.WriteLine("Done [" + sw.ElapsedMilliseconds + "ms]"); */ Console.Write("Deserializing ResponseDump.txt ... "); sw.Start(); using (var file = File.OpenText(@"../../ResponseDump.txt")) { var serializer = new JsonSerializer(); var r = (TimelineArray)serializer.Deserialize(file, typeof(TimelineArray)); root = r.d[0]; } Console.WriteLine("Done [" + sw.ElapsedMilliseconds + "ms]"); Console.Write("Calculating Layout ... "); sw.Restart(); var layoutAlg = new LayoutAlgorithm(); layoutAlg.CalulateLayout(root); sw.Stop(); Console.WriteLine("Done [" + sw.ElapsedMilliseconds + "ms]"); Console.Write("Updating Database ... "); using (var connection = new SqlConnection(@"Data Source=(localdb)\v11.0;Initial Catalog=LayoutTesting;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False")) { connection.Open(); new SqlCommand("DELETE FROM Exhibits", connection).ExecuteNonQuery(); new SqlCommand("DELETE FROM Timelines", connection).ExecuteNonQuery(); sw.Restart(); BulkInsert(root, connection); //Insert(root, connection); sw.Stop(); connection.Close(); } Console.WriteLine("Done [" + sw.ElapsedMilliseconds + "ms]"); Console.WriteLine("Press and key to exit ..."); Console.ReadKey(); }
static string GetImage(string graph, LayoutAlgorithm a) { int ExitCode = -1; Process Process = new Process (); ; //Defining the filename of the app if (a == LayoutAlgorithm.Dot) Process.StartInfo.FileName = "dot"; else if (a == LayoutAlgorithm.Twopi) Process.StartInfo.FileName = "twopi"; else if (a == LayoutAlgorithm.Neato) Process.StartInfo.FileName = "neato"; //Assigning the args to the filename Process.StartInfo.Arguments = @"-Tpng"; Process.StartInfo.UseShellExecute = false; //Set output of program to be written to process output stream Process.StartInfo.RedirectStandardOutput = true; Process.StartInfo.RedirectStandardInput = true; string strOutput = ""; byte[] result; try { //Starting the process Process.Start (); Process.StandardInput.Write (graph); Process.StandardInput.Close (); // strOutput = Process.StandardOutput.ReadToEnd(); using (var streamReader = new MemoryStream ()) { Process.StandardOutput.BaseStream.CopyTo (streamReader); result = streamReader.ToArray (); } //Waiting for the process to exit Process.WaitForExit (); //Grabbing the exit code ExitCode = Process.ExitCode; //Close the process Process.Close (); } catch (Exception ex) { throw new Exception (ex.Message); } byte[] bytes = new byte[strOutput.Length * sizeof(char)]; System.Buffer.BlockCopy (strOutput.ToCharArray (), 0, bytes, 0, bytes.Length); return string.Format ("data:image/jpg;base64,{0}", Convert.ToBase64String (result)); }
public void SetUp() { layoutAlgorithm = new LayoutAlgorithm(new FrequencyWeightSetter(), new CorrespondingToWeightSizeProvider(), new WordOrganizerBySize(), new CircularLayouter()); }