TECH TREES WHOO

Implemented procedural tech tree generation by porting GraphSharp to Unity.
Also, some database editor convenience changes.
This commit is contained in:
hyperion51 2020-04-11 19:18:02 +01:00
commit d5f2e3734a
573 changed files with 31001 additions and 222 deletions

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 59b531dac7b0fc440b9946b386c0dda4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,31 @@
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Windows;
using QuickGraph;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Compound
{
public class CompoundLayoutContext<TVertex, TEdge, TGraph>
: LayoutContext<TVertex, TEdge, TGraph>, ICompoundLayoutContext<TVertex, TEdge, TGraph>
where TEdge : IEdge<TVertex>
where TGraph : class, IBidirectionalGraph<TVertex, TEdge>
{
public CompoundLayoutContext(
TGraph graph,
IDictionary<TVertex, float2> positions,
IDictionary<TVertex, float2> sizes,
LayoutMode mode,
// IDictionary<TVertex, Thickness> vertexBorders,
IDictionary<TVertex, CompoundVertexInnerLayoutType> layoutTypes)
: base( graph, positions, sizes, mode )
{
// VertexBorders = vertexBorders;
LayoutTypes = layoutTypes;
}
// public IDictionary<TVertex, Thickness> VertexBorders { get; private set; }
public IDictionary<TVertex, CompoundVertexInnerLayoutType> LayoutTypes { get; private set; }
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 01aaa31a669873342a18865ecea141e3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,34 @@
using System.Collections.Generic;
using QuickGraph;
using System.Windows;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Compound
{
public class CompoundLayoutIterationEventArgs<TVertex, TEdge>
: LayoutIterationEventArgs<TVertex, TEdge>, ICompoundLayoutIterationEventArgs<TVertex>
where TVertex : class
where TEdge : IEdge<TVertex>
{
public CompoundLayoutIterationEventArgs(
int iteration,
double statusInPercent,
string message,
IDictionary<TVertex, float2> vertexPositions,
IDictionary<TVertex, float2> innerCanvasSizes)
: base(iteration, statusInPercent, message, vertexPositions)
{
InnerCanvasSizes = innerCanvasSizes;
}
#region ICompoundLayoutIterationEventArgs<TVertex> Members
public IDictionary<TVertex, float2> InnerCanvasSizes
{
get; private set;
}
#endregion
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f2dc57d0a594b9741b197804e5c3cf47
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,10 @@
namespace GraphSharp.Algorithms.Layout.Compound
{
public enum CompoundVertexInnerLayoutType
{
Automatic,
ContextFree,
Contextual,
Fixed
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4587271fd90cae24e84685cdb311dc7b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 751b64aba9e41e34cbcc3f2f0832f02e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,475 @@
using System;
using System.Diagnostics.Contracts;
using System.Windows;
using System.Linq;
using QuickGraph;
using System.Collections.Generic;
using System.Collections;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Compound.FDP
{
public partial class CompoundFDPLayoutAlgorithm<TVertex, TEdge, TGraph>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IBidirectionalGraph<TVertex, TEdge>
{
/// <summary>
/// Informations for compound vertices.
/// </summary>
private readonly IDictionary<TVertex, CompoundVertexData> _compoundVertexDatas =
new Dictionary<TVertex, CompoundVertexData>();
/// <summary>
/// Informations for the simple vertices.
/// </summary>
private readonly IDictionary<TVertex, SimpleVertexData> _simpleVertexDatas =
new Dictionary<TVertex, SimpleVertexData>();
/// <summary>
/// Informations for all kind of vertices.
/// </summary>
private readonly IDictionary<TVertex, VertexData> _vertexDatas =
new Dictionary<TVertex, VertexData>();
/// <summary>
/// The levels of the graph (generated by the containment associations).
/// </summary>
private readonly IList<HashSet<TVertex>> _levels =
new List<HashSet<TVertex>>();
public IList<HashSet<TVertex>> Levels
{
get { return _levels; }
}
private class RemovedTreeNodeData<TVertex1, TEdge1>
{
public readonly TVertex1 Vertex;
public readonly TEdge1 Edge;
public RemovedTreeNodeData(TVertex1 vertex, TEdge1 edge)
{
Vertex = vertex;
Edge = edge;
}
}
/// <summary>
/// The list of the removed root-tree-nodes and edges by it's level
/// (level = distance from the closest not removed node).
/// </summary>
private readonly Stack<IList<RemovedTreeNodeData<TVertex,TEdge>>> _removedRootTreeNodeLevels =
new Stack<IList<RemovedTreeNodeData<TVertex,TEdge>>>();
private readonly HashSet<TVertex> _removedRootTreeNodes =
new HashSet<TVertex>();
private readonly HashSet<TEdge> _removedRootTreeEdges =
new HashSet<TEdge>();
/// <summary>
/// Temporary dictionary for the inner canvas sizes (do not depend on this!!! inside
/// the algorithm, use the vertexData objects instead).
/// </summary>
private IDictionary<TVertex, float2> _innerCanvasSizes;
/// <summary>
/// The dictionary of the initial vertex sizes.
/// DO NOT USE IT AFTER THE INITIALIZATION.
/// </summary>
private readonly IDictionary<TVertex, float2> _vertexSizes;
/// <summary>
/// The dictionary of the vertex bordex.
/// DO NOT USE IT AFTER THE INITIALIZATION.
/// </summary>
// private readonly IDictionary<TVertex, Thickness> _vertexBorders;
/// <summary>
/// The dictionary of the layout types of the compound vertices.
/// DO NOT USE IT AFTER THE INITIALIZATION.
/// </summary>
private readonly IDictionary<TVertex, CompoundVertexInnerLayoutType> _layoutTypes;
private readonly IMutableCompoundGraph<TVertex, TEdge> _compoundGraph;
/// <summary>
/// Represents the root vertex.
/// </summary>
private readonly CompoundVertexData _rootCompoundVertex =
new CompoundVertexData(
null, null, false, new float2(),
new float2(), //new Thickness(),
CompoundVertexInnerLayoutType.Automatic);
#region Constructors
public CompoundFDPLayoutAlgorithm(
TGraph visitedGraph,
IDictionary<TVertex, float2> vertexSizes,
// IDictionary<TVertex, Thickness> vertexBorders,
IDictionary<TVertex, CompoundVertexInnerLayoutType> layoutTypes)
: this(visitedGraph, vertexSizes, /*vertexBorders,*/ layoutTypes, null, null)
{
}
public CompoundFDPLayoutAlgorithm(
TGraph visitedGraph,
IDictionary<TVertex, float2> vertexSizes,
// IDictionary<TVertex, Thickness> vertexBorders,
IDictionary<TVertex, CompoundVertexInnerLayoutType> layoutTypes,
IDictionary<TVertex, float2> vertexPositions,
CompoundFDPLayoutParameters oldParameters)
: base(visitedGraph, vertexPositions, oldParameters)
{
_vertexSizes = vertexSizes;
//_vertexBorders = vertexBorders;
_layoutTypes = layoutTypes;
if (VisitedGraph is ICompoundGraph<TVertex, TEdge>)
_compoundGraph = new CompoundGraph<TVertex, TEdge>(VisitedGraph as ICompoundGraph<TVertex, TEdge>);
else
_compoundGraph = new CompoundGraph<TVertex, TEdge>(VisitedGraph);
}
#endregion
public int LevelOfVertex(TVertex vertex)
{
return _vertexDatas[vertex].Level;
}
#region ICompoundLayoutAlgorithm<TVertex,TEdge,TGraph> Members
public IDictionary<TVertex, float2> InnerCanvasSizes
{
get
{
return _compoundVertexDatas.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.InnerCanvasSize);
}
}
#endregion
#region Nested type: CompoundVertexData
/// <summary>
/// Data for the compound vertices.
/// </summary>
private class CompoundVertexData : VertexData
{
/// <summary>
/// The thickness of the borders of the compound vertex.
/// </summary>
// public readonly Thickness Borders;
/// <summary>
/// Gets the layout type of the compound vertex.
/// </summary>
public readonly CompoundVertexInnerLayoutType InnerVertexLayoutType;
private float2 _innerCanvasSize;
private float2 _size;
private ICollection<VertexData> _children;
public CompoundVertexData(TVertex vertex,
VertexData movableParent,
bool isFixedToParent,
float2 position,
float2 size,
// Thickness borders,
CompoundVertexInnerLayoutType innerVertexLayoutType)
: base(vertex, movableParent, isFixedToParent, position)
{
//Borders = borders;
//calculate the size of the inner canvas
InnerCanvasSize = new float2(max(0.0f, size.x),// - Borders.Left - Borders.Right
max(0.0f, size.y));// - Borders.Top - Borders.Bottom
InnerVertexLayoutType = innerVertexLayoutType;
}
/// <summary>
/// The size of the inner canvas of the compound vertex.
/// </summary>
public float2 InnerCanvasSize
{
get { return _innerCanvasSize; }
set
{
_innerCanvasSize = value;
//set the size of the canvas
_size = new float2(_innerCanvasSize.x,// + Borders.Left + Borders.Right,
_innerCanvasSize.y); //+ Borders.Top + Borders.Bottom
}
}
/// <summary>
/// The overall size of the vertex (inner canvas size + borders + ...).
/// </summary>
public override float2 Size
{
get { return _size; }
}
/// <summary>
/// Modifies the position of the children with the given
/// vector.
/// </summary>
/// <param name="force">The vector of the position modification.</param>
private void PropogateToChildren(float2 force)
{
foreach (var child in _children)
{
child.ApplyForce(force);
}
}
public ICollection<VertexData> Children
{
get { return _children; }
set
{
_children = value;
}
}
internal override void ApplyForce(float2 force)
{
Position += force;
PropogateToChildren(force);
RecalculateBounds();
}
public float2 InnerCanvasCenter
{
get
{
return new float2(
Position.x - Size.x / 2 + /*Borders.Left +*/ InnerCanvasSize.x / 2,
Position.y - Size.y / 2 + /*Borders.Top +*/ InnerCanvasSize.y / 2
);
}
set
{
Position = new float2(
value.x - InnerCanvasSize.x / 2 /*- Borders.Left*/ + Size.x / 2,
value.y - InnerCanvasSize.y / 2 /*- Borders.Top*/ + Size.y / 2
);
}
}
public void RecalculateBounds()
{
if (_children == null)
{
InnerCanvasSize = new float2(); //TODO padding
return;
}
float2 topLeft = new float2(float.PositiveInfinity, float.PositiveInfinity);
float2 bottomRight = new float2(float.NegativeInfinity, float.NegativeInfinity);
foreach (var child in _children)
{
topLeft.x = Math.Min(topLeft.x, child.Position.x - child.Size.x / 2);
topLeft.y = Math.Min(topLeft.y, child.Position.y - child.Size.y / 2);
bottomRight.x = Math.Max(bottomRight.x, child.Position.x + child.Size.x / 2);
bottomRight.y = Math.Max(bottomRight.y, child.Position.y + child.Size.y / 2);
}
InnerCanvasSize = new float2(bottomRight.y - topLeft.y, bottomRight.y - topLeft.y);
InnerCanvasCenter = new float2((topLeft.x + bottomRight.x) / 2.0f, (topLeft.y + bottomRight.y) / 2.0f);
}
}
#endregion
#region Nested type: SimpleVertexData
private class SimpleVertexData : VertexData
{
/// <summary>
/// The size of the vertex.
/// </summary>
private readonly float2 _size;
public SimpleVertexData(TVertex vertex, VertexData movableParent, bool isFixed, float2 position, float2 size)
: base(vertex, movableParent, isFixed, position)
{
_size = size;
}
/// <summary>
/// Gets the actual size of the vertex (inner size + border + anything else...).
/// </summary>
public override float2 Size
{
get { return _size; }
}
internal override void ApplyForce(float2 force)
{
Position += force;
}
}
#endregion
#region Nested type: VertexData
/// <summary>
/// Data for the simple vertices.
/// </summary>
private abstract class VertexData
{
/// <summary>
/// Gets the vertex which is wrapped by this object.
/// </summary>
public readonly TVertex Vertex;
public CompoundVertexData Parent;
private float2 _springForce;
private float2 _repulsionForce;
private float2 _gravitationForce;
private float2 _applicationForce;
private float2 _previousForce;
private float2 _childrenForce;
protected VertexData _movableParent;
protected VertexData(TVertex vertex, VertexData movableParent, bool isFixedToParent, float2 position)
{
Vertex = vertex;
MovableParent = movableParent;
IsFixedToParent = isFixedToParent;
Parent = null;
Position = position;
}
/// <summary>
/// If the vertex is fixed (cannot be moved), that's it's parent
/// that could be moved (if there's any).
///
/// This property can only be set once.
/// </summary>
public VertexData MovableParent
{
get { return _movableParent; }
set
{
_movableParent = value;
}
}
/// <summary>
/// Gets or sets that the position of the vertex is fixed to
/// it's parent vertex or not.
/// </summary>
public bool IsFixedToParent { get; set; }
/// <summary>
/// Gets the actual size of the vertex (inner size + border + anything else...).
/// </summary>
public abstract float2 Size { get; }
/// <summary>
/// The level of the vertex inside the graph.
/// </summary>
public int Level;
/// <summary>
/// The position of the vertex.
/// </summary>
public float2 Position;
/// <summary>
/// Gets or sets the spring force.
/// </summary>
public float2 SpringForce
{
get { return IsFixedToParent ? new float2() : _springForce; }
set
{
if (IsFixedToParent)
_springForce = new float2();
else _springForce = value;
}
}
/// <summary>
/// Gets or sets the spring force.
/// </summary>
public float2 RepulsionForce
{
get { return IsFixedToParent ? new float2() : _repulsionForce; }
set
{
if (IsFixedToParent)
_repulsionForce = new float2();
else _repulsionForce = value;
}
}
/// <summary>
/// Gets or sets the spring force.
/// </summary>
public float2 GravitationForce
{
get { return IsFixedToParent ? new float2() : _gravitationForce; }
set
{
if (IsFixedToParent)
_gravitationForce = new float2();
else _gravitationForce = value;
}
}
/// <summary>
/// Gets or sets the spring force.
/// </summary>
public float2 ApplicationForce
{
get { return IsFixedToParent ? new float2() : _applicationForce; }
set
{
if (IsFixedToParent)
_applicationForce = new float2();
else _applicationForce = value;
}
}
internal abstract void ApplyForce(float2 force);
public float2 ApplyForce(float limit)
{
var force = _springForce
+ _repulsionForce
+ _gravitationForce
+ _applicationForce
+ 0.5f * _childrenForce;
Parent._childrenForce += force;
if (length(force) > limit)
force *= limit / length(force);
force += 0.7f * _previousForce;
if (length(force) > limit)
force *= limit / length(force);
ApplyForce(force);
_springForce = new float2();
_repulsionForce = new float2();
_gravitationForce = new float2();
_applicationForce = new float2();
_childrenForce = new float2();
_previousForce = force;
return force;
}
}
#endregion
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 04f6319aebf16be48b7d36d70101d150
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,278 @@
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using QuickGraph;
using System;
using System.Diagnostics.Contracts;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Compound.FDP
{
public partial class CompoundFDPLayoutAlgorithm<TVertex, TEdge, TGraph>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IBidirectionalGraph<TVertex, TEdge>
{
private static void RemoveAll<T>(ICollection<T> set, IEnumerable<T> elements)
{
foreach (var e in elements)
{
set.Remove(e);
}
}
/// <summary>
/// <list type="ul">
/// <listheader>
/// Initializes the algorithm, and the following things:
/// </listheader>
/// <item>the nodes sizes (of the compound vertices)</item>
/// <item>the thresholds for the convergence</item>
/// <item>random initial positions (if the position is not null)</item>
/// <item>remove the 'tree-nodes' from the root graph (level 0)</item>
/// </list>
/// </summary>
/// <param name="vertexSizes">The dictionary of the inner canvas sizes
/// of the compound vertices.</param>
/// <param name="vertexBorders">The dictionary of the border thickness of
/// the compound vertices.</param>
/// <param name="layoutTypes">The dictionary of the layout types of
/// the compound vertices.</param>
private void Init(IDictionary<TVertex, float2> vertexSizes, /*IDictionary<TVertex, Thickness> vertexBorders, */IDictionary<TVertex, CompoundVertexInnerLayoutType> layoutTypes)
{
InitializeWithRandomPositions(100, 100);
var movableParentUpdateQueue = new Queue<TVertex>();
_rootCompoundVertex.Children = new HashSet<VertexData>();
InitialLevels();
InitSimpleVertices(vertexSizes);
InitCompoundVertices(/*vertexBorders, */vertexSizes, layoutTypes, /*out*/ movableParentUpdateQueue);
SetLevelIndices();
//TODO do we need this?
InitMovableParentOfFixedVertices(movableParentUpdateQueue);
RemoveTreeNodesFromRootGraph();
InitGravitationMagnitude();
}
private void InitGravitationMagnitude()
{
//get the average width and height
float sumWidth = 0, sumHeight = 0;
foreach (var vertex in _levels[0])
{
var v = _vertexDatas[vertex];
sumWidth += v.Size.x;
sumHeight += v.Size.y;
}
if (_levels[0].Count > 0)
_gravityForceMagnitude = min(sumWidth, sumHeight) / _levels[0].Count;
}
private void RemoveTreeNodesFromRootGraph()
{
bool removed = true;
for (int i = 0; removed; i++)
{
removed = false;
foreach (var vertex in _levels[0])
{
if (_compoundGraph.Degree(vertex) != 1 || _compoundGraph.IsCompoundVertex(vertex))
continue;
TEdge edge = default(TEdge);
if (_compoundGraph.InDegree(vertex) > 0)
edge = _compoundGraph.InEdge(vertex, 0);
else
edge = _compoundGraph.OutEdge(vertex, 0);
if (_removedRootTreeEdges.Contains(edge))
continue;
//the vertex is a leaf tree node
removed = true;
while (_removedRootTreeNodeLevels.Count <= i)
_removedRootTreeNodeLevels.Push(new List<RemovedTreeNodeData<TVertex,TEdge>>());
//add to the removed vertices
_removedRootTreeNodeLevels.Peek().Add(new RemovedTreeNodeData<TVertex,TEdge>(vertex, edge));
_removedRootTreeNodes.Add(vertex);
_removedRootTreeEdges.Add(edge);
}
if (removed && _removedRootTreeNodeLevels.Count > 0)
//remove from the level
foreach (var tnd in _removedRootTreeNodeLevels.Peek())
{
_levels[0].Remove(tnd.Vertex);
//remove the vertex from the graph
_compoundGraph.RemoveEdge(tnd.Edge);
_compoundGraph.RemoveVertex(tnd.Vertex);
}
}
}
private void InitMovableParentOfFixedVertices(Queue<TVertex> movableParentUpdateQueue)
{
while (movableParentUpdateQueue.Count > 0)
{
//geth the compound vertex with the fixed layout
var fixedLayoutedCompoundVertex = movableParentUpdateQueue.Dequeue();
//find the not fixed predecessor
TVertex movableVertex = fixedLayoutedCompoundVertex;
for (; ; )
{
//if the vertex hasn't parent
if (movableVertex == null)
break;
TVertex parent = _compoundGraph.GetParent(movableVertex);
if (parent == null)
break;
//if the parent's layout type is fixed
if (_compoundVertexDatas[parent].InnerVertexLayoutType != CompoundVertexInnerLayoutType.Fixed)
break;
movableVertex = parent;
}
//the movable vertex is the ancestor of the children of the vertex
//that could be moved
//fix the child vertices and set the movable parent
foreach (var childVertex in _compoundGraph.GetChildrenVertices(fixedLayoutedCompoundVertex))
{
var data = _vertexDatas[childVertex];
data.IsFixedToParent = true;
data.MovableParent = _vertexDatas[movableVertex];
}
}
}
/// <summary>
/// Initializes the data of the simple vertices.
/// </summary>
/// <param name="vertexSizes">Dictionary of the vertex sizes.</param>
private void InitSimpleVertices(IDictionary<TVertex, float2> vertexSizes)
{
foreach (var vertex in _compoundGraph.SimpleVertices)
{
float2 vertexSize;
vertexSizes.TryGetValue(vertex, out vertexSize);
var position = new float2();
VertexPositions.TryGetValue(vertex, out position);
//create the information container for this simple vertex
var dataContainer = new SimpleVertexData(vertex, _rootCompoundVertex, false, position, vertexSize);
dataContainer.Parent = _rootCompoundVertex;
_simpleVertexDatas[vertex] = dataContainer;
_vertexDatas[vertex] = dataContainer;
_rootCompoundVertex.Children.Add(dataContainer);
}
}
/// <summary>
/// Initializes the data of the compound vertices.
/// </summary>
/// <param name="vertexBorders">Dictionary of the border thicknesses.</param>
/// <param name="vertexSizes">Dictionary of the vertex sizes.</param>
/// <param name="layoutTypes">Dictionary of the layout types.</param>
/// <param name="movableParentUpdateQueue">The compound vertices with fixed layout
/// should be added to this queue.</param>
private void InitCompoundVertices(
//IDictionary<TVertex, Thickness> vertexBorders,
IDictionary<TVertex, float2> vertexSizes,
IDictionary<TVertex, CompoundVertexInnerLayoutType> layoutTypes,
Queue<TVertex> movableParentUpdateQueue)
{
for (int i = _levels.Count - 1; i >= 0; i--)
{
foreach (var vertex in _levels[i])
{
if (!_compoundGraph.IsCompoundVertex(vertex))
continue;
//get the data of the vertex
// Thickness border;
// vertexBorders.TryGetValue(vertex, out border);
float2 vertexSize;
vertexSizes.TryGetValue(vertex, out vertexSize);
var layoutType = CompoundVertexInnerLayoutType.Automatic;
layoutTypes.TryGetValue(vertex, out layoutType);
if (layoutType == CompoundVertexInnerLayoutType.Fixed)
{
movableParentUpdateQueue.Enqueue(vertex);
}
var position = new float2();
VertexPositions.TryGetValue(vertex, out position);
//create the information container for this compound vertex
var dataContainer = new CompoundVertexData(vertex, _rootCompoundVertex, false, position, vertexSize, /*border, */layoutType);
if (i == 0)
{
dataContainer.Parent = _rootCompoundVertex;
_rootCompoundVertex.Children.Add(dataContainer);
}
_compoundVertexDatas[vertex] = dataContainer;
_vertexDatas[vertex] = dataContainer;
//add the datas of the childrens
var children = _compoundGraph.GetChildrenVertices(vertex);
var childrenData = children.Select(v => _vertexDatas[v]).ToList();
dataContainer.Children = childrenData;
foreach (var child in dataContainer.Children)
{
_rootCompoundVertex.Children.Remove(child);
child.Parent = dataContainer;
}
}
}
}
private void InitialLevels()
{
var verticesLeft = new HashSet<TVertex>(VisitedGraph.Vertices);
//initial 0th level
_levels.Add(new HashSet<TVertex>(VisitedGraph.Vertices.Where(v => _compoundGraph.GetParent(v) == default(TVertex))));
RemoveAll(verticesLeft, _levels[0]);
//other layers
for (int i = 1; verticesLeft.Count > 0; i++)
{
var nextLevel = new HashSet<TVertex>();
foreach (var parent in _levels[i - 1])
{
if (_compoundGraph.GetChildrenCount(parent) <= 0)
continue;
foreach (var children in _compoundGraph.GetChildrenVertices(parent))
nextLevel.Add(children);
}
_levels.Add(nextLevel);
RemoveAll(verticesLeft, nextLevel);
}
}
private void SetLevelIndices()
{
//set the level indexes in the vertex datas
for (int i = 0; i < _levels.Count; i++)
{
foreach (var v in _levels[i])
_vertexDatas[v].Level = i;
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bfb500bde641d9b42a21f471a6359c29
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,399 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using QuickGraph;
using System.Diagnostics.Contracts;
using System.Diagnostics;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using Random = System.Random;
namespace GraphSharp.Algorithms.Layout.Compound.FDP
{
/// <typeparam name="TVertex">The type of the vertices.</typeparam>
/// <typeparam name="TEdge">The type of the edges.</typeparam>
/// <typeparam name="TGraph">The type of the graph.</typeparam>
public partial class CompoundFDPLayoutAlgorithm<TVertex, TEdge, TGraph> :
DefaultParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, CompoundFDPLayoutParameters>,
ICompoundLayoutAlgorithm<TVertex, TEdge, TGraph>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IBidirectionalGraph<TVertex, TEdge>
{
/*[ContractInvariantMethod]
private void InvariantContracts()
{
Contract.Invariant(1 <= _phase && _phase <= 3);
Contract.Invariant(_treeGrowingStep > 0);
}*/
private float _temperature = 0;
private float _temperatureDelta; //need to be initialized
private readonly float _temperatureLambda = 0.99f;
private readonly Random rnd = new Random(DateTime.Now.Millisecond);
/// <summary>
/// <para>Phase of the layout process.</para>
/// <para>Values: 1,2,3</para>
/// </summary>
private int _phase = 1;
/// <summary>
/// The steps in the actual phase.
/// </summary>
private int _step;
/// <summary>
/// The maximal iteration count in the phases.
/// </summary>
private /*readonly*/ int[] _maxIterationCounts = new int[3] { 30, 70, 50 };
/// <summary>
/// The error thresholds for the phases (calculated inside the Init method).
/// </summary>
private readonly float[] _errorThresholds = new float[3];
/// <summary>
/// Indicates whether the removed tree-node
/// has been grown back or not.
/// </summary>
private bool _allTreesGrown
{
get { return _removedRootTreeNodeLevels.Count == 0; }
}
/// <summary>
/// Grows back a tree-node level in every 'treeGrowingStep'th step.
/// </summary>
private int _treeGrowingStep = 5;
/// <summary>
/// The magnitude of the gravity force calculated in the init phased.
/// </summary>
private float _gravityForceMagnitude;
/// <summary>
/// Has been the gravity center initiated or not.
/// </summary>
private bool _gravityCenterCalculated;
private float _phaseDependentRepulsionMultiplier = 1.0f;
/// <summary>
/// This method is the skeleton of the layout algorithm.
/// </summary>
protected override void InternalCompute()
{
//call initialize
Init(_vertexSizes, /*_vertexBorders,*/ _layoutTypes);
//Phases:
//1: layout the skeleton graph without app. specific and gravitation forces.
//2: add the removed tree nodes and apply app. specific and gravitation forces.
//3: stabilization
/* ********* FOR OPTIMIZATION PURPOSES ********** */
_maxIterationCounts = new int[3];
_maxIterationCounts[0] = Parameters.Phase1Iterations;
_maxIterationCounts[1] = Parameters.Phase2Iterations;
_maxIterationCounts[2] = Parameters.Phase3Iterations;
var _temperatureMultipliers = new float[3]
{
1.0f,
Parameters.Phase2TemperatureInitialMultiplier,
Parameters.Phase3TemperatureInitialMultiplier
};
float initialTemperature = sqrt(_compoundGraph.VertexCount) * Parameters.IdealEdgeLength;
float minimalTemperature = initialTemperature * 0.1f;
_temperature = initialTemperature;
_gravityCenterCalculated = false;
for (_phase = 1; _phase <= 3; _phase++)
{
_temperature = initialTemperature * _temperatureMultipliers[_phase - 1];
_phaseDependentRepulsionMultiplier = _phase < 2 ? 0.5f : 1.0f;
//TODO put back the error and its threshold
/*float error = _errorThresholds[_phase] + 1;*/
for (_step = _maxIterationCounts[_phase - 1];
(_step > 0 && true/*error > _errorThresholds[_phase - 1] */) || (_phase == 2 && !_allTreesGrown);
_step--)
{
/*error = 0;*/
ApplySpringForces();
ApplyRepulsionForces();
if (_phase > 1)
{
ApplyGravitationForces();
ApplyApplicationSpecificForces();
}
if (ReportOnIterationEndNeeded)
SavePositions();
CalcNodePositionsAndSizes();
if (_phase == 2 && !_allTreesGrown && _step % _treeGrowingStep == 0)
GrowTreesOneLevel();
_temperature *= _temperatureLambda;
_temperature = Math.Max(_temperature, minimalTemperature);
}
if (!_gravityCenterCalculated)
{
_rootCompoundVertex.RecalculateBounds();
_gravityCenterCalculated = true;
}
//if (_phase == 1)
_temperature *= Parameters.TemperatureDecreasing;
}
SavePositions();
}
private void SavePositions()
{
foreach (var vertex in _vertexDatas.Keys)
{
var v = _vertexDatas[vertex];
VertexPositions[vertex] = v.Position;
}
/*var iterationEndedArgs =
new CompoundLayoutIterationEventArgs<TVertex, TEdge>(
0, 0, string.Empty,
VertexPositions,
InnerCanvasSizes);*/
//build the test vertex infos
var vertexInfos = _vertexDatas.ToDictionary(
kvp => kvp.Key,
kvp => new TestingCompoundVertexInfo(
kvp.Value.SpringForce,
kvp.Value.RepulsionForce,
kvp.Value.GravitationForce,
kvp.Value.ApplicationForce));
var iterationEndedArgs =
new TestingCompoundLayoutIterationEventArgs<TVertex, TEdge, TestingCompoundVertexInfo, object>(
0, 0, string.Format("Phase: {0}, Steps: {1}", _phase, _step),
VertexPositions,
InnerCanvasSizes,
vertexInfos,
_rootCompoundVertex.InnerCanvasCenter);
//raise the event
OnIterationEnded(iterationEndedArgs);
}
private void GrowTreesOneLevel()
{
if (_removedRootTreeNodeLevels.Count <= 0)
return;
var treeNodeDatas = _removedRootTreeNodeLevels.Pop();
foreach (var tnd in treeNodeDatas)
{
_removedRootTreeNodes.Remove(tnd.Vertex);
_removedRootTreeEdges.Remove(tnd.Edge);
_levels[0].Add(tnd.Vertex);
_compoundGraph.AddVertex(tnd.Vertex);
_compoundGraph.AddEdge(tnd.Edge);
var otherVertex = tnd.Edge.GetOtherVertex(tnd.Vertex);
_vertexDatas[tnd.Vertex].Position = _vertexDatas[otherVertex].Position;
}
}
private float2 GetSpringForce(float idealLength, float2 uPos, float2 vPos, float2 uSize, float2 vSize)
{
var positionVector = (uPos - vPos);
if (abs(math.length(positionVector)) < .001f)
{
var compensationVector = new float2((float) rnd.NextDouble(), (float) rnd.NextDouble());
positionVector = compensationVector * 2;
uPos += compensationVector;
vPos -= compensationVector;
}
positionVector = normalize(positionVector);
//get the clipping points
var c_u = LayoutUtil.GetClippingPoint(uSize, uPos, vPos);
var c_v = LayoutUtil.GetClippingPoint(vSize, vPos, uPos);
float2 F = (c_u - c_v);
bool isSameDirection = LayoutUtil.IsSameDirection(positionVector, F);
float length = 0;
if (isSameDirection)
length = math.length(F) - idealLength;
else
length = math.length(F) + idealLength;
if (abs(math.length(F)) < .001f)
F = -positionVector;
F = normalize(F);
if (length > 0)
F *= -1;
var Fs = pow(length / (idealLength), 2) / Parameters.ElasticConstant * F;
return Fs;
}
private float2 GetRepulsionForce(float2 uPos, float2 vPos, float2 uSize, float2 vSize, float repulsionRange)
{
var positionVector = (uPos - vPos);
if (math.length(positionVector) == 0)
{
var compensationVector = new float2((float) rnd.NextDouble(), (float) rnd.NextDouble());
positionVector = compensationVector * 2;
uPos += compensationVector;
vPos -= compensationVector;
}
positionVector = normalize(positionVector);
var c_u = LayoutUtil.GetClippingPoint(uSize, uPos, vPos);
var c_v = LayoutUtil.GetClippingPoint(vSize, vPos, uPos);
var F = c_u - c_v;
var isSameDirection = LayoutUtil.IsSameDirection(positionVector, F);
var Fr = new float2();
if (isSameDirection && math.length(F) > repulsionRange)
return new float2();
float length = Math.Max(1, math.length(F));
//float length = F.LengthSquared;
length = pow(isSameDirection ? length / (Parameters.IdealEdgeLength * 2.0f) : 1 / length, 2);
Fr = Parameters.RepulsionConstant / length * positionVector * _phaseDependentRepulsionMultiplier;
return Fr;
}
/// <summary>
/// Applies the attraction forces (between the end nodes
/// of the edges).
/// </summary>
private void ApplySpringForces()
{
foreach (var edge in VisitedGraph.Edges)
{
if (!_allTreesGrown && (_removedRootTreeNodes.Contains(edge.Source) || _removedRootTreeNodes.Contains(edge.Target)))
continue;
//get the ideal edge length
float idealLength = Parameters.IdealEdgeLength;
var u = _vertexDatas[edge.Source];
var v = _vertexDatas[edge.Target];
var multiplier = (u.Level + v.Level) / 2.0f + 1;
if (IsInterGraphEdge(edge))
{
//idealLength *= (u.Level + v.Level + 1) * Parameters.NestingFactor;
idealLength *= 1 + (u.Level + v.Level + 1) * Parameters.NestingFactor;
//multiplier = 1;
}
var Fs = GetSpringForce(idealLength, u.Position, v.Position, u.Size, v.Size) * multiplier;
//aggregate the forces
if ((u.IsFixedToParent && u.MovableParent == null) ^ (v.IsFixedToParent && v.MovableParent == null))
Fs *= 2;
if (!u.IsFixedToParent)
u.SpringForce += Fs /* * u.Mass / (u.Mass + v.Mass)*/;
else if (u.MovableParent != null)
{
u.MovableParent.SpringForce += Fs;
}
if (!v.IsFixedToParent)
v.SpringForce -= Fs /* * v.Mass / (u.Mass + v.Mass)*/;
else if (v.MovableParent != null)
{
v.MovableParent.SpringForce -= Fs;
}
}
}
/// <summary>
/// Applies the repulsion forces between every node-pair.
/// </summary>
private void ApplyRepulsionForces()
{
var repulsionRange = Parameters.IdealEdgeLength * Parameters.SeparationMultiplier;
for (int i = _levels.Count - 1; i >= 0; i--)
{
var checkedVertices = new HashSet<TVertex>();
foreach (var uVertex in _levels[i])
{
checkedVertices.Add(uVertex);
var u = _vertexDatas[uVertex];
foreach (var vVertex in _levels[i])
{
if (checkedVertices.Contains(vVertex))
continue;
var v = _vertexDatas[vVertex];
if (u.Parent != v.Parent)
continue; //the two vertex not in the same graph
var Fr = GetRepulsionForce(u.Position, v.Position, u.Size, v.Size, repulsionRange) * pow(u.Level + 1,2);
if (u.IsFixedToParent ^ v.IsFixedToParent)
Fr *= 2;
if (!u.IsFixedToParent)
u.RepulsionForce += Fr /** u.Mass / (u.Mass + v.Mass)*/;
if (!v.IsFixedToParent)
v.RepulsionForce -= Fr /** v.Mass / (u.Mass + v.Mass)*/;
}
}
}
}
/// <summary>
/// Applies the gravitation forces.
/// </summary>
private void ApplyGravitationForces()
{
for (int i = _levels.Count - 1; i >= 0; i--)
{
foreach (var uVertex in _levels[i])
{
var u = _vertexDatas[uVertex];
var center = u.Parent.InnerCanvasCenter;
var Fg = center - u.Position;
if (math.length(Fg) < .001f)
continue;
float length = Math.Max(1, math.length(Fg) / (Parameters.IdealEdgeLength * 2.0f));
Fg = normalize(Fg);
Fg *= Parameters.GravitationFactor * _gravityForceMagnitude * pow(u.Level + 1,2) / pow(length, 0.25f);
u.GravitationForce += Fg;
}
}
}
/// <summary>
/// Applies the application specific forces to the vertices.
/// </summary>
protected virtual void ApplyApplicationSpecificForces()
{
}
private void CalcNodePositionsAndSizes()
{
for (int i = _levels.Count - 1; i >= 0; i--)
{
foreach (var uVertex in _levels[i])
{
var u = _vertexDatas[uVertex];
var force = u.ApplyForce(_temperature * max(1, _step) / 100.0f * Parameters.DisplacementLimitMultiplier);
}
}
}
private bool IsInterGraphEdge(TEdge e)
{
return _vertexDatas[e.Source].Parent != _vertexDatas[e.Target].Parent;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 18b1a2cf0e101ee4cb799f53aebfff4c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,222 @@
namespace GraphSharp.Algorithms.Layout.Compound.FDP
{
public class CompoundFDPLayoutParameters : LayoutParametersBase
{
private float _idealEdgeLength = 25;
private float _elasticConstant = 0.005f;
private float _repulsionConstant = 150;
private float _nestingFactor = 0.2f;
private float _gravitationFactor = 8;
private int _phase1Iterations = 50;
private int _phase2Iterations = 70;
private int _phase3Iterations = 30;
private float _phase2TemperatureInitialMultiplier = 0.5f;
private float _phase3TemperatureInitialMultiplier = 0.2f;
private float _temperatureDecreasing = 0.5f;
private float _temperatureFactor = 0.95f;
private float _displacementLimitMultiplier = 0.5f;
private float _separationMultiplier = 15;
/// <summary>
/// Gets or sets the ideal edge length.
/// </summary>
public float IdealEdgeLength
{
get { return _idealEdgeLength; }
set
{
if (value == _idealEdgeLength)
return;
_idealEdgeLength = value;
NotifyPropertyChanged("IdealEdgeLength");
}
}
/// <summary>
/// Gets or sets the elastic constant for the edges.
/// </summary>
public float ElasticConstant
{
get { return _elasticConstant; }
set
{
if (value == _elasticConstant)
return;
_elasticConstant = value;
NotifyPropertyChanged("ElasticConstant");
}
}
/// <summary>
/// Gets or sets the repulsion constant for the node-node
/// repulsion.
/// </summary>
public float RepulsionConstant
{
get { return _repulsionConstant; }
set
{
if (value == _repulsionConstant)
return;
_repulsionConstant = value;
NotifyPropertyChanged("RepulsionConstant");
}
}
/// <summary>
/// Gets or sets the factor of the ideal edge length for the
/// inter-graph edges.
/// </summary>
public float NestingFactor
{
get { return _nestingFactor; }
set
{
if (value == _nestingFactor)
return;
_nestingFactor = value;
NotifyPropertyChanged("NestingFactor");
}
}
/// <summary>
/// Gets or sets the factor of the gravitation.
/// </summary>
public float GravitationFactor
{
get { return _gravitationFactor; }
set
{
if (value == _gravitationFactor)
return;
_gravitationFactor = value;
NotifyPropertyChanged("GravitationFactor");
}
}
public int Phase1Iterations
{
get { return _phase1Iterations; }
set
{
if (value == _phase1Iterations)
return;
_phase1Iterations = value;
NotifyPropertyChanged("Phase1Iterations");
}
}
public int Phase2Iterations
{
get { return _phase2Iterations; }
set
{
if (value == _phase2Iterations)
return;
_phase2Iterations = value;
NotifyPropertyChanged("Phase2Iterations");
}
}
public int Phase3Iterations
{
get { return _phase3Iterations; }
set
{
if (value == _phase3Iterations)
return;
_phase3Iterations = value;
NotifyPropertyChanged("Phase3Iterations");
}
}
public float Phase2TemperatureInitialMultiplier
{
get { return _phase2TemperatureInitialMultiplier; }
set
{
if (value == _phase2TemperatureInitialMultiplier)
return;
_phase2TemperatureInitialMultiplier = value;
NotifyPropertyChanged("Phase2TemperatureInitialMultiplier");
}
}
public float Phase3TemperatureInitialMultiplier
{
get { return _phase3TemperatureInitialMultiplier; }
set
{
if (value == _phase3TemperatureInitialMultiplier)
return;
_phase3TemperatureInitialMultiplier = value;
NotifyPropertyChanged("Phase3TemperatureInitialMultiplier");
}
}
public float TemperatureDecreasing
{
get { return _temperatureDecreasing; }
set
{
if (value == _temperatureDecreasing)
return;
_temperatureDecreasing = value;
NotifyPropertyChanged("TemperatureDecreasing");
}
}
public float TemperatureFactor
{
get { return _temperatureFactor; }
set
{
if (value == _temperatureFactor)
return;
_temperatureFactor = value;
NotifyPropertyChanged("TemperatureFactor");
}
}
public float DisplacementLimitMultiplier
{
get { return _displacementLimitMultiplier; }
set
{
if (value == _displacementLimitMultiplier)
return;
_displacementLimitMultiplier = value;
NotifyPropertyChanged("DisplacementLimitMultiplier");
}
}
public float SeparationMultiplier
{
get { return _separationMultiplier; }
set
{
if (value == _separationMultiplier)
return;
_separationMultiplier = value;
NotifyPropertyChanged("SeparationMultiplier");
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fb985b217904cfb40a64fc91d7846140
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,16 @@
using System.Collections.Generic;
using System.Windows;
using QuickGraph;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Compound
{
public interface ICompoundLayoutAlgorithm<TVertex, TEdge, TGraph> : ILayoutAlgorithm<TVertex, TEdge, TGraph>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IBidirectionalGraph<TVertex, TEdge>
{
IDictionary<TVertex, float2> InnerCanvasSizes { get; }
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0e4cf28522a9e174e88fbe8ba7aa302b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,14 @@
using System.Collections.Generic;
using QuickGraph;
using System.Windows;
namespace GraphSharp.Algorithms.Layout.Compound
{
public interface ICompoundLayoutContext<TVertex, TEdge, TGraph> : ILayoutContext<TVertex, TEdge, TGraph>
where TEdge : IEdge<TVertex>
where TGraph : IBidirectionalGraph<TVertex, TEdge>
{
// IDictionary<TVertex, Thickness> VertexBorders { get; }
IDictionary<TVertex, CompoundVertexInnerLayoutType> LayoutTypes { get; }
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 05b8cb2e16ce46b40935e68b560a7547
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,14 @@
using System.Collections.Generic;
using System.Windows;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Compound
{
public interface ICompoundLayoutIterationEventArgs<TVertex>
: ILayoutIterationEventArgs<TVertex>
where TVertex : class
{
IDictionary<TVertex, float2> InnerCanvasSizes { get; }
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0f86aed8aefca354f88d2d60172c1b3d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using QuickGraph;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Compound
{
public class TestingCompoundLayoutIterationEventArgs<TVertex, TEdge, TVertexInfo, TEdgeInfo>
: CompoundLayoutIterationEventArgs<TVertex, TEdge>, ILayoutInfoIterationEventArgs<TVertex, TEdge, TVertexInfo, TEdgeInfo>
where TVertex : class
where TEdge : IEdge<TVertex>
{
private IDictionary<TVertex, TVertexInfo> vertexInfos;
public float2 GravitationCenter { get; private set; }
public TestingCompoundLayoutIterationEventArgs(
int iteration,
double statusInPercent,
string message,
IDictionary<TVertex, float2> vertexPositions,
IDictionary<TVertex, float2> innerCanvasSizes,
IDictionary<TVertex, TVertexInfo> vertexInfos,
float2 gravitationCenter)
: base(iteration, statusInPercent, message, vertexPositions, innerCanvasSizes)
{
this.vertexInfos = vertexInfos;
this.GravitationCenter = gravitationCenter;
}
public override object GetVertexInfo(TVertex vertex)
{
TVertexInfo info = default(TVertexInfo);
if (vertexInfos.TryGetValue(vertex, out info))
return info;
return null;
}
public IDictionary<TVertex, TVertexInfo> VertexInfos
{
get { return this.vertexInfos; }
}
public IDictionary<TEdge, TEdgeInfo> EdgeInfos
{
get { return null; }
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2749eb7cc688780428b6826a1bb9f799
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,22 @@
using System.Windows;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Compound
{
public class TestingCompoundVertexInfo
{
public TestingCompoundVertexInfo(float2 springForce, float2 repulsionForce, float2 gravityForce, float2 applicationForce)
{
SpringForce = springForce;
RepulsionForce = repulsionForce;
GravityForce = gravityForce;
ApplicationForce = applicationForce;
}
public float2 SpringForce { get; set; }
public float2 RepulsionForce { get; set; }
public float2 GravityForce { get; set; }
public float2 ApplicationForce { get; set; }
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f49438cc322bc5840aecb2cd2f78dabe
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 91bee5591d233f24db1aa32e4f3a0243
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,74 @@
using System.Collections.Generic;
using System.Linq;
using QuickGraph;
using GraphSharp.Algorithms.Layout.Simple.Tree;
namespace GraphSharp.Algorithms.Layout.Contextual
{
public class ContextualLayoutAlgorithmFactory<TVertex, TEdge, TGraph> : IContextualLayoutAlgorithmFactory<TVertex, TEdge, TGraph>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : class, IBidirectionalGraph<TVertex, TEdge>
{
private readonly string[] algorithmTypes = new[] { "DoubleTree", "BalloonTree" };
public IEnumerable<string> AlgorithmTypes
{
get { return algorithmTypes; }
}
public ILayoutAlgorithm<TVertex, TEdge, TGraph> CreateAlgorithm( string newAlgorithmType, ILayoutContext<TVertex, TEdge, TGraph> context, ILayoutParameters parameters )
{
var layoutContext = context as ContextualLayoutContext<TVertex, TEdge, TGraph>;
switch ( newAlgorithmType )
{
case "DoubleTree":
return new DoubleTreeLayoutAlgorithm<TVertex, TEdge, TGraph>( layoutContext.Graph, layoutContext.Positions, layoutContext.Sizes, parameters as DoubleTreeLayoutParameters, layoutContext.SelectedVertex );
case "BalloonTree":
return new BalloonTreeLayoutAlgorithm<TVertex, TEdge, TGraph>( layoutContext.Graph, layoutContext.Positions, layoutContext.Sizes, parameters as BalloonTreeLayoutParameters, layoutContext.SelectedVertex );
default:
return null;
}
}
public ILayoutParameters CreateParameters( string algorithmType, ILayoutParameters oldParameters )
{
switch ( algorithmType )
{
case "DoubleTree":
return !( oldParameters is DoubleTreeLayoutParameters ) ? new DoubleTreeLayoutParameters() : (DoubleTreeLayoutParameters)( oldParameters as DoubleTreeLayoutParameters ).Clone();
case "BaloonTree":
return !( oldParameters is BalloonTreeLayoutParameters ) ? new BalloonTreeLayoutParameters() : (BalloonTreeLayoutParameters)( oldParameters as BalloonTreeLayoutParameters ).Clone();
default:
return null;
}
}
public string GetAlgorithmType( ILayoutAlgorithm<TVertex, TEdge, TGraph> algorithm )
{
if ( algorithm is DoubleTreeLayoutAlgorithm<TVertex, TEdge, TGraph> )
return "DoubleTree";
if ( algorithm is BalloonTreeLayoutAlgorithm<TVertex, TEdge, TGraph> )
return "BalloonTree";
return string.Empty;
}
public bool IsValidAlgorithm( string algorithmType )
{
return ( AlgorithmTypes.Contains( algorithmType ) );
}
public bool NeedEdgeRouting( string algorithmType )
{
return true;
}
public bool NeedOverlapRemoval( string algorithmType )
{
return false;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4b08537ed969a3b489a3544360dbc2bb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,22 @@
using System.Collections.Generic;
using QuickGraph;
using System.Windows;
using System.Diagnostics.Contracts;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Contextual
{
public class ContextualLayoutContext<TVertex, TEdge, TGraph> : LayoutContext<TVertex, TEdge, TGraph>
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
{
public TVertex SelectedVertex { get; private set; }
public ContextualLayoutContext( TGraph graph, TVertex selectedVertex, IDictionary<TVertex, float2> positions, IDictionary<TVertex, float2> sizes )
: base( graph, positions, sizes, LayoutMode.Simple )
{
SelectedVertex = selectedVertex;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b79468344f5b45c4399f30f6812459f5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,198 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using QuickGraph;
using System.Diagnostics.Contracts;
using GraphSharp.Algorithms.Layout.Simple.Tree;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Contextual
{
public enum DoubleTreeVertexType
{
Backward,
Forward,
Center
}
public class DoubleTreeLayoutAlgorithm<TVertex, TEdge, TGraph> : ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, DoubleTreeVertexType, object, DoubleTreeLayoutParameters>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IBidirectionalGraph<TVertex, TEdge>
{
readonly TVertex root;
readonly IDictionary<TVertex, float2> vertexSizes;
protected override DoubleTreeLayoutParameters DefaultParameters
{
get { return new DoubleTreeLayoutParameters(); }
}
public DoubleTreeLayoutAlgorithm( TGraph visitedGraph, IDictionary<TVertex, float2> vertexPositions, IDictionary<TVertex, float2> vertexSizes, DoubleTreeLayoutParameters oldParameters, TVertex selectedVertex )
: base( visitedGraph, vertexPositions, oldParameters )
{
root = selectedVertex;
this.vertexSizes = ( vertexSizes ?? new Dictionary<TVertex, float2>() );
}
protected override void InternalCompute()
{
//
// Separate the two sides
//
HashSet<TVertex> side1, side2;
SeparateSides( VisitedGraph, root, out side1, out side2 );
#region Build the temporary graph for the two sides
//
// The IN side
//
//on the IN side we should reverse the edges
var graph1 = new BidirectionalGraph<TVertex, Edge<TVertex>>();
graph1.AddVertexRange( side1 );
foreach ( var v in side1 )
{
vertexInfos[v] = DoubleTreeVertexType.Backward;
foreach ( var e in VisitedGraph.InEdges( v ) )
{
if ( !side1.Contains( e.Source ) || e.Source.Equals( e.Target ) )
continue;
//reverse the edge
graph1.AddEdge( new Edge<TVertex>( e.Target, e.Source ) );
}
}
//
// The OUT side
//
var graph2 = new BidirectionalGraph<TVertex, TEdge>();
graph2.AddVertexRange( side2 );
foreach ( var v in side2 )
{
vertexInfos[v] = DoubleTreeVertexType.Forward;
foreach ( var e in VisitedGraph.OutEdges( v ) )
{
if ( !side2.Contains( e.Target ) || e.Source.Equals( e.Target ) )
continue;
//simply add the edge
graph2.AddEdge( e );
}
}
vertexInfos[root] = DoubleTreeVertexType.Center;
#endregion
LayoutDirection side2Direction = Parameters.Direction;
LayoutDirection side1Direction = Parameters.Direction;
switch ( side2Direction )
{
case LayoutDirection.BottomToTop:
side1Direction = LayoutDirection.TopToBottom;
break;
case LayoutDirection.LeftToRight:
side1Direction = LayoutDirection.RightToLeft;
break;
case LayoutDirection.RightToLeft:
side1Direction = LayoutDirection.LeftToRight;
break;
case LayoutDirection.TopToBottom:
side1Direction = LayoutDirection.BottomToTop;
break;
}
//
// SimpleTree layout on the two side
//
var side1LayoutAlg = new SimpleTreeLayoutAlgorithm<TVertex, Edge<TVertex>, BidirectionalGraph<TVertex, Edge<TVertex>>>(
graph1, VertexPositions, vertexSizes,
new SimpleTreeLayoutParameters
{
LayerGap = Parameters.LayerGap,
VertexGap = Parameters.VertexGap,
Direction = side1Direction,
SpanningTreeGeneration = SpanningTreeGeneration.BFS
} );
var side2LayoutAlg = new SimpleTreeLayoutAlgorithm<TVertex, TEdge, BidirectionalGraph<TVertex, TEdge>>(
graph2, VertexPositions, vertexSizes,
new SimpleTreeLayoutParameters
{
LayerGap = Parameters.LayerGap,
VertexGap = Parameters.VertexGap,
Direction = side2Direction,
SpanningTreeGeneration = SpanningTreeGeneration.BFS
} );
side1LayoutAlg.Compute();
side2LayoutAlg.Compute();
//
// Merge the layouts
//
var side2Translate = side1LayoutAlg.VertexPositions[root] - side2LayoutAlg.VertexPositions[root];
foreach ( var v in side1 )
VertexPositions[v] = side1LayoutAlg.VertexPositions[v];
foreach ( var v in side2 )
VertexPositions[v] = side2LayoutAlg.VertexPositions[v] + side2Translate;
NormalizePositions();
}
/// <summary>
/// Separates the points of the graph according to the given <paramref name="selectedVertex"/>.
/// </summary>
/// <param name="graph"></param>
/// <param name="selectedVertex"></param>
/// <param name="side1"></param>
/// <param name="side2"></param>
public static void SeparateSides( TGraph graph, TVertex selectedVertex, out HashSet<TVertex> side1, out HashSet<TVertex> side2 )
{
var visitedVertices = new HashSet<TVertex> { selectedVertex };
//create the set of the side 1 and 2
side1 = new HashSet<TVertex> { selectedVertex };
side2 = new HashSet<TVertex> { selectedVertex };
var queue1 = new Queue<TVertex>();
var queue2 = new Queue<TVertex>();
queue1.Enqueue( selectedVertex );
queue2.Enqueue( selectedVertex );
do
{
//get the next layer of vertices on the IN side
for ( int i = 0, n = queue1.Count; i < n; i++ )
{
var vertex = queue1.Dequeue();
foreach ( var edge in graph.InEdges( vertex ) )
{
if ( ( graph.ContainsVertex( edge.Source ) && visitedVertices.Add( edge.Source ) ) || vertex.Equals( selectedVertex ) )
{
queue1.Enqueue( edge.Source );
side1.Add( edge.Source );
}
}
}
//get the next layer of vertices on the OUT side
for ( int i = 0, n = queue2.Count; i < n; i++ )
{
var vertex = queue2.Dequeue();
foreach ( var edge in graph.OutEdges( vertex ) )
{
if ( ( graph.ContainsVertex( edge.Target ) && visitedVertices.Add( edge.Target ) ) || vertex.Equals( selectedVertex ) )
{
queue2.Enqueue( edge.Target );
side2.Add( edge.Target );
}
}
}
} while ( queue1.Count > 0 || queue2.Count > 0 );
//we got the 2 sides
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ca869432dda75b0488e5e13d6b853059
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,80 @@
namespace GraphSharp.Algorithms.Layout.Contextual
{
public enum DoubleTreeSides
{
Side1,
Side2
}
public class DoubleTreeLayoutParameters : LayoutParametersBase
{
private LayoutDirection direction = LayoutDirection.LeftToRight;
/// <summary>
/// Gets or sets the layout direction.
/// </summary>
public LayoutDirection Direction
{
get { return direction; }
set
{
if ( direction != value )
{
direction = value;
NotifyPropertyChanged( "Direction" );
}
}
}
private float layerGap = 10;
/// <summary>
/// Gets or sets the gap between the layers.
/// </summary>
public float LayerGap
{
get { return layerGap; }
set
{
if ( layerGap != value )
{
layerGap = value;
NotifyPropertyChanged( "LayerGap" );
}
}
}
private float vertexGap = 10;
/// <summary>
/// Gets or sets the gap between the neighbor vertices in a layer.
/// </summary>
public float VertexGap
{
get { return vertexGap; }
set
{
if ( vertexGap != value )
{
vertexGap = value;
NotifyPropertyChanged( "VertexGap" );
}
}
}
private DoubleTreeSides prioritizedTreeSide = DoubleTreeSides.Side1;
/// <summary>
/// Gets or sets the the prioritized tree side (the one with the bigger priority: where a vertex
/// goes if it should go on both side).
/// </summary>
public DoubleTreeSides PrioritizedTreeSide
{
get { return prioritizedTreeSide; }
set
{
if ( prioritizedTreeSide != value )
{
prioritizedTreeSide = value;
NotifyPropertyChanged( "PrioritizedTreeSide" );
}
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4b7810d4c9a602945b703c39de543302
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,12 @@
using QuickGraph;
using System.Diagnostics.Contracts;
namespace GraphSharp.Algorithms.Layout.Contextual
{
public interface IContextualLayoutAlgorithmFactory<TVertex, TEdge, TGraph> : ILayoutAlgorithmFactory<TVertex, TEdge, TGraph>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : class, IBidirectionalGraph<TVertex, TEdge>
{
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b771698c04360d54786bcda1fcc06c22
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,32 @@
using System.Collections.Generic;
using System.Windows;
using QuickGraph;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Contextual
{
public class RadialTreeLayoutAlgorithm<TVertex, TEdge, TGraph> : DefaultParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, RadialTreeLayoutParameters>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IBidirectionalGraph<TVertex, TEdge>
{
private readonly TVertex root;
public RadialTreeLayoutAlgorithm(
TGraph visitedGraph,
IDictionary<TVertex, float2> vertexPositions,
RadialTreeLayoutParameters oldParameters,
TVertex selectedVertex )
: base( visitedGraph, vertexPositions, oldParameters )
{
this.root = selectedVertex;
}
protected override void InternalCompute()
{
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 87c52b55f6c18524db96158ea5b9bb21
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,7 @@
namespace GraphSharp.Algorithms.Layout.Contextual
{
public class RadialTreeLayoutParameters : LayoutParametersBase
{
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ea6f658fd5b673c47bc2d527b7e55abf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,64 @@
using System.Collections.Generic;
using QuickGraph.Algorithms;
using QuickGraph;
using System.Windows;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout
{
public delegate void LayoutIterationEndedEventHandler<TVertex, TEdge>( object sender, ILayoutIterationEventArgs<TVertex> e )
where TVertex : class
where TEdge : IEdge<TVertex>;
public delegate void LayoutIterationEndedEventHandler<TVertex, TEdge, TVertexInfo, TEdgeInfo>( object sender, ILayoutInfoIterationEventArgs<TVertex, TEdge, TVertexInfo, TEdgeInfo> e )
where TVertex : class
where TEdge : IEdge<TVertex>;
/// <summary>
/// Reports the progress of the layout.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="percent">The status of the progress in percent.</param>
public delegate void ProgressChangedEventHandler(object sender, double percent);
public interface ILayoutAlgorithm<TVertex, TEdge, TGraph, TVertexInfo, TEdgeInfo> : ILayoutAlgorithm<TVertex, TEdge, TGraph>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
{
/// <summary>
/// Extra informations, calculated by the layout
/// </summary>
IDictionary<TVertex, TVertexInfo> VertexInfos { get; }
/// <summary>
/// Extra informations, calculated by the layout
/// </summary>
IDictionary<TEdge, TEdgeInfo> EdgeInfos { get; }
new event LayoutIterationEndedEventHandler<TVertex, TEdge, TVertexInfo, TEdgeInfo> IterationEnded;
}
public interface ILayoutAlgorithm<TVertex, TEdge, TGraph> : IAlgorithm<TGraph>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
{
IDictionary<TVertex, float2> VertexPositions { get; }
/// <summary>
/// Returns with the extra layout information of the vertex (or null).
/// </summary>
object GetVertexInfo( TVertex vertex );
/// <summary>
/// Returns with the extra layout information of the edge (or null).
/// </summary>
object GetEdgeInfo( TEdge edge );
event LayoutIterationEndedEventHandler<TVertex, TEdge> IterationEnded;
event ProgressChangedEventHandler ProgressChanged;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0f1afdff86cccf8498709efbd37366cc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,38 @@
using System.Collections.Generic;
using QuickGraph;
using System.Diagnostics.Contracts;
namespace GraphSharp.Algorithms.Layout
{
public interface ILayoutAlgorithmFactory<TVertex, TEdge, TGraph>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : class, IBidirectionalGraph<TVertex, TEdge>
{
IEnumerable<string> AlgorithmTypes { get; }
/// <summary>
/// Creates a new algorithm specified by the newAlgorithmType parameter.
/// </summary>
/// <param name="newAlgorithmType">The identifier of the new layout algorithm.</param>
/// <param name="context"></param>
/// <param name="parameters"></param>
/// <returns>The new layout algorithm object.</returns>
ILayoutAlgorithm<TVertex, TEdge, TGraph> CreateAlgorithm( string newAlgorithmType, ILayoutContext<TVertex, TEdge, TGraph> context, ILayoutParameters parameters );
ILayoutParameters CreateParameters( string algorithmType, ILayoutParameters oldParameters );
bool IsValidAlgorithm( string algorithmType );
/// <summary>
/// Gets the type of the algorithm (usually the name of the algorithm which identifies the algorithm).
/// </summary>
/// <param name="algorithm">The layout algorithm object.</param>
/// <returns>The identified of the algorithm.</returns>
string GetAlgorithmType( ILayoutAlgorithm<TVertex, TEdge, TGraph> algorithm );
bool NeedEdgeRouting( string algorithmType );
bool NeedOverlapRemoval( string algorithmType );
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 25df130b4dde3bc409d99a7e0e250b08
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,21 @@
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using QuickGraph;
using System.Windows;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout
{
public interface ILayoutContext<TVertex, TEdge, TGraph>
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
{
IDictionary<TVertex, float2> Positions { get; }
IDictionary<TVertex, float2> Sizes { get; }
TGraph Graph { get; }
LayoutMode Mode { get; }
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a53021c32b555184291d2b55424ba6bb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QuickGraph;
namespace GraphSharp.Algorithms.Layout
{
public interface ILayoutInfoIterationEventArgs<TVertex, TEdge>
: ILayoutIterationEventArgs<TVertex>
where TVertex : class
where TEdge : IEdge<TVertex>
{
object GetVertexInfo(TVertex vertex);
object GetEdgeInfo(TEdge edge);
}
public interface ILayoutInfoIterationEventArgs<TVertex, TEdge, TVertexInfo, TEdgeInfo>
: ILayoutInfoIterationEventArgs<TVertex, TEdge>
where TVertex : class
where TEdge : IEdge<TVertex>
{
IDictionary<TVertex, TVertexInfo> VertexInfos { get; }
IDictionary<TEdge, TEdgeInfo> EdgeInfos { get; }
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 544c5b7b388ed714ab69f066f2cfdde8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout
{
public interface ILayoutIterationEventArgs<TVertex>
where TVertex : class
{
/// <summary>
/// Represent the status of the layout algorithm in percent.
/// </summary>
double StatusInPercent { get; }
/// <summary>
/// If the user sets this value to <code>true</code>, the algorithm aborts ASAP.
/// </summary>
bool Abort { get; set; }
/// <summary>
/// Number of the actual iteration.
/// </summary>
int Iteration { get; }
/// <summary>
/// Message, textual representation of the status of the algorithm.
/// </summary>
string Message { get; }
IDictionary<TVertex, float2> VertexPositions { get; }
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ebb2337ea7f8b45409f5cad9c28e8411
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,7 @@

namespace GraphSharp.Algorithms.Layout
{
public interface ILayoutParameters : IAlgorithmParameters
{
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e695e04e52109b549bb318f45de1e92c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,13 @@
namespace GraphSharp.Algorithms.Layout
{
public interface IParameterizedLayoutAlgorithm
{
ILayoutParameters GetParameters();
}
public interface IParameterizedLayoutAlgorithm<TParam> : IParameterizedLayoutAlgorithm
where TParam : ILayoutParameters
{
TParam Parameters { get; }
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 347a186ff88cf4d4d94459dac9dc2511
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,134 @@
using System.Collections.Generic;
using QuickGraph;
using System.Windows;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout
{
public abstract class LayoutAlgorithmBase<TVertex, TEdge, TGraph, TVertexInfo, TEdgeInfo> : LayoutAlgorithmBase<TVertex, TEdge, TGraph>, ILayoutAlgorithm<TVertex, TEdge, TGraph, TVertexInfo, TEdgeInfo>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
{
protected readonly IDictionary<TVertex, TVertexInfo> vertexInfos = new Dictionary<TVertex, TVertexInfo>();
protected readonly IDictionary<TEdge, TEdgeInfo> edgeInfos = new Dictionary<TEdge, TEdgeInfo>();
protected LayoutAlgorithmBase( TGraph visitedGraph )
: base( visitedGraph )
{
}
protected LayoutAlgorithmBase( TGraph visitedGraph, IDictionary<TVertex, float2> vertexPositions )
: base( visitedGraph, vertexPositions )
{
}
public IDictionary<TVertex, TVertexInfo> VertexInfos
{
get { return vertexInfos; }
}
public IDictionary<TEdge, TEdgeInfo> EdgeInfos
{
get { return edgeInfos; }
}
public new event LayoutIterationEndedEventHandler<TVertex, TEdge, TVertexInfo, TEdgeInfo> IterationEnded;
public override object GetVertexInfo( TVertex vertex )
{
TVertexInfo info;
if ( VertexInfos.TryGetValue( vertex, out info ) )
return info;
return null;
}
public override object GetEdgeInfo( TEdge edge )
{
TEdgeInfo info;
if ( EdgeInfos.TryGetValue( edge, out info ) )
return info;
return null;
}
}
public abstract class LayoutAlgorithmBase<TVertex, TEdge, TGraph> : AlgorithmBase, ILayoutAlgorithm<TVertex, TEdge, TGraph>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
{
private readonly Dictionary<TVertex, float2> vertexPositions;
private readonly TGraph visitedGraph;
public IDictionary<TVertex, float2> VertexPositions
{
get { return vertexPositions; }
}
public TGraph VisitedGraph
{
get { return visitedGraph; }
}
public event LayoutIterationEndedEventHandler<TVertex, TEdge> IterationEnded;
public event ProgressChangedEventHandler ProgressChanged;
public bool ReportOnIterationEndNeeded
{
get { return IterationEnded != null; }
}
public bool ReportOnProgressChangedNeeded
{
get { return ProgressChanged != null; }
}
protected LayoutAlgorithmBase( TGraph visitedGraph ) :
this( visitedGraph, null )
{
}
protected LayoutAlgorithmBase( TGraph visitedGraph, IDictionary<TVertex, float2> vertexPositions )
{
this.visitedGraph = visitedGraph;
if ( vertexPositions != null )
this.vertexPositions = new Dictionary<TVertex, float2>( vertexPositions );
else
this.vertexPositions = new Dictionary<TVertex, float2>( visitedGraph.VertexCount );
}
protected virtual void OnIterationEnded( ILayoutIterationEventArgs<TVertex> args )
{
if ( IterationEnded != null )
{
IterationEnded( this, args );
//if the layout should be aborted
if ( args.Abort )
Abort();
}
}
protected virtual void OnProgressChanged( double percent )
{
if ( ProgressChanged != null )
ProgressChanged( this, percent );
}
public virtual object GetVertexInfo( TVertex vertex )
{
return null;
}
public virtual object GetEdgeInfo( TEdge edge )
{
return null;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e5ed2d8fad48ceb40921704cc183dcf4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,29 @@
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using QuickGraph;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout
{
public class LayoutContext<TVertex, TEdge, TGraph> : ILayoutContext<TVertex, TEdge, TGraph>
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
{
public IDictionary<TVertex, float2> Positions { get; private set; }
public IDictionary<TVertex, float2> Sizes { get; private set; }
public TGraph Graph { get; private set; }
public LayoutMode Mode { get; private set; }
public LayoutContext( TGraph graph, IDictionary<TVertex, float2> positions, IDictionary<TVertex, float2> sizes, LayoutMode mode )
{
Graph = graph;
Positions = positions;
Sizes = sizes;
Mode = mode;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 15b31b1debb281241bf3569233e00999
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,10 @@
namespace GraphSharp.Algorithms.Layout
{
public enum LayoutDirection
{
LeftToRight = 0,
TopToBottom = 1,
RightToLeft = 2,
BottomToTop = 3
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: eb0a45e349c95054fa03b65979516c49
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.Windows;
using QuickGraph;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout
{
public class LayoutIterationEventArgs<TVertex, TEdge, TVertexInfo, TEdgeInfo>
: LayoutIterationEventArgs<TVertex, TEdge>,
ILayoutInfoIterationEventArgs<TVertex, TEdge, TVertexInfo, TEdgeInfo>
where TVertex : class
where TEdge : IEdge<TVertex>
{
public LayoutIterationEventArgs()
: this( 0, 0, string.Empty, null, null, null )
{ }
public LayoutIterationEventArgs( int iteration, double statusInPercent )
: this( iteration, statusInPercent, string.Empty, null, null, null )
{ }
public LayoutIterationEventArgs( int iteration, double statusInPercent, string message )
: this( iteration, statusInPercent, message, null, null, null )
{ }
public LayoutIterationEventArgs( int iteration, double statusInPercent,
IDictionary<TVertex, float2> vertexPositions )
: this( iteration, statusInPercent, string.Empty, vertexPositions, null, null )
{ }
public LayoutIterationEventArgs( int iteration, double statusInPercent, string message,
IDictionary<TVertex, float2> vertexPositions,
IDictionary<TVertex, TVertexInfo> vertexInfos,
IDictionary<TEdge, TEdgeInfo> edgeInfos)
: base( iteration, statusInPercent, message, vertexPositions )
{
this.VertexInfos = vertexInfos;
this.EdgeInfos = edgeInfos;
}
public IDictionary<TVertex, TVertexInfo> VertexInfos { get; private set; }
public IDictionary<TEdge, TEdgeInfo> EdgeInfos { get; private set; }
public sealed override object GetVertexInfo( TVertex vertex )
{
if ( VertexInfos == null )
return null;
TVertexInfo info;
return VertexInfos.TryGetValue( vertex, out info ) ? info : default( TVertexInfo );
}
public sealed override object GetEdgeInfo( TEdge edge )
{
if ( EdgeInfos == null )
return null;
TEdgeInfo info;
return EdgeInfos.TryGetValue( edge, out info ) ? info : default( TEdgeInfo );
}
}
public class LayoutIterationEventArgs<TVertex, TEdge>
: EventArgs,
ILayoutIterationEventArgs<TVertex>,
ILayoutInfoIterationEventArgs<TVertex, TEdge>
where TVertex : class
where TEdge : IEdge<TVertex>
{
public LayoutIterationEventArgs()
: this( 0, 0, string.Empty, null )
{ }
public LayoutIterationEventArgs( int iteration, double statusInPercent )
: this( iteration, statusInPercent, string.Empty, null )
{ }
public LayoutIterationEventArgs( int iteration, double statusInPercent, string message )
: this( iteration, statusInPercent, message, null )
{ }
public LayoutIterationEventArgs( int iteration, double statusInPercent,
IDictionary<TVertex, float2> vertexPositions )
: this( iteration, statusInPercent, string.Empty, vertexPositions )
{ }
public LayoutIterationEventArgs( int iteration, double statusInPercent, string message,
IDictionary<TVertex, float2> vertexPositions )
{
this.StatusInPercent = statusInPercent;
this.Iteration = iteration;
this.Abort = false;
this.Message = message;
this.VertexPositions = vertexPositions;
}
/// <summary>
/// Represent the status of the layout algorithm in percent.
/// </summary>
public double StatusInPercent { get; private set; }
/// <summary>
/// If the user sets this value to <code>true</code>, the algorithm aborts ASAP.
/// </summary>
public bool Abort { get; set; }
/// <summary>
/// Number of the actual iteration.
/// </summary>
public int Iteration { get; private set; }
/// <summary>
/// Message, textual representation of the status of the algorithm.
/// </summary>
public string Message { get; private set; }
public IDictionary<TVertex, float2> VertexPositions { get; private set; }
public virtual object GetVertexInfo( TVertex vertex )
{
return null;
}
public virtual object GetEdgeInfo( TEdge edge )
{
return null;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6d3c1472672479e4b9351e7cb64429e9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,15 @@
namespace GraphSharp.Algorithms.Layout
{
public enum LayoutMode
{
/// <summary>
/// Simple layout mode without compound vertices.
/// </summary>
Simple,
/// <summary>
/// Compound vertices, compound graph.
/// </summary>
Compound
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ff251831c085b2c44a1e86161fd1790a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,28 @@
using System.ComponentModel;
namespace GraphSharp.Algorithms.Layout
{
public abstract class LayoutParametersBase : ILayoutParameters
{
#region ICloneable Members
public object Clone()
{
return this.MemberwiseClone();
}
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName)
{
//delegating to the event...
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a0e5f7d0914a45347b63c566ac4f4e7c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout
{
public class LayoutState<TVertex, TEdge>
{
/// <summary>
/// Gets the position of every vertex in this state of the layout process.
/// </summary>
public IDictionary<TVertex, float2> Positions { get; protected set; }
public IDictionary<TVertex, float2> OverlapRemovedPositions { get; set; }
public IDictionary<TEdge, float2[]> RouteInfos { get; set; }
/// <summary>
/// Gets how much time did it take to compute the position of the vertices (till the end of this iteration).
/// </summary>
public TimeSpan ComputationTime { get; protected set; }
/// <summary>
/// Gets the index of the iteration.
/// </summary>
public int Iteration { get; protected set; }
/// <summary>
/// Get the status message of this layout state.
/// </summary>
public string Message { get; protected set; }
public LayoutState(
IDictionary<TVertex, float2> positions,
IDictionary<TVertex, float2> overlapRemovedPositions,
IDictionary<TEdge, float2[]> routeInfos,
TimeSpan computationTime,
int iteration,
string message )
{
Debug.Assert( computationTime != null );
Positions = positions;
OverlapRemovedPositions = overlapRemovedPositions != null ? overlapRemovedPositions : positions;
if ( routeInfos != null )
RouteInfos = routeInfos;
else
RouteInfos = new Dictionary<TEdge, float2[]>( 0 );
ComputationTime = computationTime;
Iteration = iteration;
Message = message;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cbc73da39f389d54da74f106b14b3b95
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,161 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System;
using System.Diagnostics.Contracts;
using System.Linq;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout
{
[DebuggerDisplay("First = {First}, Second = {Second}")]
public class Pair
{
public int First;
public int Second;
public int Weight = 1;
}
public static class LayoutUtil
{
public static int BiLayerCrossCount(IEnumerable<Pair> pairs, int firstLayerVertexCount, int secondLayerVertexCount)
{
if (pairs == null)
return 0;
//radix sort of the pair, order by First asc, Second asc
#region Sort by Second ASC
var radixBySecond = new List<Pair>[secondLayerVertexCount];
List<Pair> r;
int pairCount = 0;
foreach (var pair in pairs)
{
//get the radix where the pair should be inserted
r = radixBySecond[pair.Second];
if (r == null)
{
r = new List<Pair>();
radixBySecond[pair.Second] = r;
}
r.Add(pair);
pairCount++;
}
#endregion
#region Sort By First ASC
var radixByFirst = new List<Pair>[firstLayerVertexCount];
foreach (var list in radixBySecond)
{
if (list == null)
continue;
foreach (var pair in list)
{
//get the radix where the pair should be inserted
r = radixByFirst[pair.First];
if (r == null)
{
r = new List<Pair>();
radixByFirst[pair.First] = r;
}
r.Add(pair);
}
}
#endregion
//
// Build the accumulator tree
//
int firstIndex = 1;
while (firstIndex < pairCount)
firstIndex *= 2;
int treeSize = 2 * firstIndex - 1;
firstIndex -= 1;
int[] tree = new int[treeSize];
//
// Count the crossings
//
int crossCount = 0;
int index;
foreach (var list in radixByFirst)
{
if (list == null)
continue;
foreach (var pair in list)
{
index = pair.Second + firstIndex;
tree[index] += pair.Weight;
while (index > 0)
{
if (index % 2 > 0)
crossCount += tree[index + 1] * pair.Weight;
index = (index - 1) / 2;
tree[index] += pair.Weight;
}
}
}
return crossCount;
}
public static float2 GetClippingPoint(float2 size, float2 s, float2 t)
{
float[] sides = new float[4];
sides[0] = (s.x - size.x / 2.0f - t.x) / (s.x - t.x);
sides[1] = (s.y - size.y / 2.0f - t.y) / (s.y - t.y);
sides[2] = (s.x + size.x / 2.0f - t.x) / (s.x - t.x);
sides[3] = (s.y + size.y / 2.0f - t.y) / (s.y - t.y);
float fi = 0;
for (int i = 0; i < 4; i++)
{
if (sides[i] <= 1)
fi = max(fi, sides[i]);
}
if (fi == 0)
{
fi = float.PositiveInfinity;
for (int i = 0; i < 4; i++)
fi = min(fi, Math.Abs(sides[i]));
fi *= -1;
}
return t + fi * (s - t);
}
public static bool IsSameDirection(float2 a, float2 b)
{
return Math.Sign(a.x) == Math.Sign(b.x) && Math.Sign(a.y) == Math.Sign(b.y);
}
public static int BiLayerCrossCount(List<Pair> edgePairs)
{
int[] firsts = edgePairs.Select(e => e.First).Distinct().OrderBy(f => f).ToArray();
int[] seconds = edgePairs.Select(e => e.Second).Distinct().OrderBy(f => f).ToArray();
Dictionary<int, int> firstMap = new Dictionary<int, int>(firsts.Length);
Dictionary<int, int> secondMap = new Dictionary<int, int>(seconds.Length);
for (int i = 0; i < firsts.Length; i++)
{
firstMap.Add(firsts[i], i);
}
for (int i = 0; i < seconds.Length; i++)
{
secondMap.Add(seconds[i], i);
}
foreach (var pair in edgePairs)
{
pair.First = firstMap[pair.First];
pair.Second = secondMap[pair.Second];
}
return BiLayerCrossCount(edgePairs, firsts.Length, seconds.Length);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5cc4aef7ed007fb4e82b4302c8892fb6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,257 @@
using System;
using System.Collections.Generic;
using QuickGraph;
using System.Linq;
using System.Diagnostics;
using System.Windows;
using Random = System.Random;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout
{
public abstract class ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TVertexInfo, TEdgeInfo, TParam> : ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TParam>, ILayoutAlgorithm<TVertex, TEdge, TGraph, TVertexInfo, TEdgeInfo>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
where TParam : class, ILayoutParameters
{
protected readonly IDictionary<TVertex, TVertexInfo> vertexInfos = new Dictionary<TVertex, TVertexInfo>();
protected readonly IDictionary<TEdge, TEdgeInfo> edgeInfos = new Dictionary<TEdge, TEdgeInfo>();
protected ParameterizedLayoutAlgorithmBase( TGraph visitedGraph )
: base( visitedGraph, null, null ) { }
protected ParameterizedLayoutAlgorithmBase( TGraph visitedGraph, IDictionary<TVertex, float2> vertexPositions,
TParam oldParameters )
: base( visitedGraph, vertexPositions, oldParameters )
{
}
#region ILayoutAlgorithm<TVertex,TEdge,TGraph,TVertexInfo,TEdgeInfo> Members
public IDictionary<TVertex, TVertexInfo> VertexInfos
{
get { return vertexInfos; }
}
public IDictionary<TEdge, TEdgeInfo> EdgeInfos
{
get { return edgeInfos; }
}
protected override ILayoutIterationEventArgs<TVertex> CreateLayoutIterationEventArgs( int iteration, float statusInPercent, string message, IDictionary<TVertex, float2> vertexPositions )
{
return new LayoutIterationEventArgs<TVertex, TEdge, TVertexInfo, TEdgeInfo>( iteration, statusInPercent, message, vertexPositions, vertexInfos, edgeInfos );
}
public new event LayoutIterationEndedEventHandler<TVertex, TEdge, TVertexInfo, TEdgeInfo> IterationEnded;
public override object GetVertexInfo( TVertex vertex )
{
TVertexInfo info;
if ( VertexInfos.TryGetValue( vertex, out info ) )
return info;
return null;
}
public override object GetEdgeInfo( TEdge edge )
{
TEdgeInfo info;
if ( EdgeInfos.TryGetValue( edge, out info ) )
return info;
return null;
}
#endregion
}
/// <summary>
/// Use this class as a base class for your layout algorithm
/// if it's parameter class has a default contstructor.
/// </summary>
/// <typeparam name="TVertex">The type of the vertices.</typeparam>
/// <typeparam name="TEdge">The type of the edges.</typeparam>
/// <typeparam name="TGraph">The type of the graph.</typeparam>
/// <typeparam name="TParam">The type of the parameters. Must be based on the LayoutParametersBase.</typeparam>
public abstract class DefaultParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TParam> : ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TParam>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
where TParam : class, ILayoutParameters, new()
{
protected DefaultParameterizedLayoutAlgorithmBase(TGraph visitedGraph)
: base(visitedGraph)
{
}
protected DefaultParameterizedLayoutAlgorithmBase(TGraph visitedGraph, IDictionary<TVertex, float2> vertexPositions, TParam oldParameters)
: base(visitedGraph, vertexPositions, oldParameters)
{
}
protected override TParam DefaultParameters
{
get { return new TParam(); }
}
}
/// <typeparam name="TVertex">Type of the vertices.</typeparam>
/// <typeparam name="TEdge">Type of the edges.</typeparam>
/// <typeparam name="TGraph">Type of the graph.</typeparam>
/// <typeparam name="TParam">Type of the parameters. Must be based on the LayoutParametersBase.</typeparam>
public abstract class ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TParam> : LayoutAlgorithmBase<TVertex, TEdge, TGraph>, IParameterizedLayoutAlgorithm<TParam>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
where TParam : class, ILayoutParameters
{
#region Properties
/// <summary>
/// Parameters of the algorithm. For more information see <see cref="LayoutParametersBase"/>.
/// </summary>
public TParam Parameters { get; protected set; }
public ILayoutParameters GetParameters()
{
return Parameters;
}
public TraceSource TraceSource { get; protected set; }
#endregion
#region Constructors
protected ParameterizedLayoutAlgorithmBase( TGraph visitedGraph )
: this( visitedGraph, null, null ) { }
protected ParameterizedLayoutAlgorithmBase( TGraph visitedGraph, IDictionary<TVertex, float2> vertexPositions,
TParam oldParameters )
: base( visitedGraph, vertexPositions )
{
InitParameters( oldParameters );
TraceSource = new TraceSource( "LayoutAlgorithm", SourceLevels.All );
}
#endregion
#region Initializers
protected abstract TParam DefaultParameters { get; }
/// <summary>
/// Initializes the parameters (cloning or creating new parameter object with default values).
/// </summary>
/// <param name="oldParameters">Parameters from a prevorious layout. If it is null,
/// the parameters will be set to the default ones.</param>
protected void InitParameters( TParam oldParameters )
{
if (oldParameters == null)
Parameters = DefaultParameters;
else
{
Parameters = (TParam)oldParameters.Clone();
}
}
/// <summary>
/// Initializes the positions of the vertices. Assign a random position inside the 'bounding box' to the vertices without positions.
/// It does NOT modify the position of the other vertices.
///
/// It generates an <code>IterationEnded</code> event.
///
/// Bounding box:
/// x coordinates: float.Epsilon - <code>width</code>
/// y coordinates: float.Epsilon - <code>height</code>
/// </summary>
/// <param name="width">Width of the bounding box.</param>
/// <param name="height">Height of the bounding box.</param>
protected virtual void InitializeWithRandomPositions( float width, float height )
{
InitializeWithRandomPositions( width, height, 0, 0 );
}
/// <summary>
/// Initializes the positions of the vertices. Assign a random position inside the 'bounding box' to the vertices without positions.
/// It does NOT modify the position of the other vertices.
///
/// It generates an <code>IterationEnded</code> event.
///
/// Bounding box:
/// x coordinates: float.Epsilon - <code>width</code>
/// y coordinates: float.Epsilon - <code>height</code>
/// </summary>
/// <param name="width">Width of the bounding box.</param>
/// <param name="height">Height of the bounding box.</param>
/// <param name="translate_x">Translates the generated x coordinate.</param>
/// <param name="translate_y">Translates the generated y coordinate.</param>
protected virtual void InitializeWithRandomPositions( float width, float height, float translate_x, float translate_y )
{
var rnd = new Random( DateTime.Now.Millisecond );
//initialize with random position
foreach ( TVertex v in VisitedGraph.Vertices )
{
//for vertices without assigned position
if ( !VertexPositions.ContainsKey( v ) )
{
VertexPositions[v] =
new float2(
max( float.Epsilon, (float) rnd.NextDouble() * width + translate_x ),
max( float.Epsilon, (float) rnd.NextDouble() * height + translate_y ) );
}
}
}
protected virtual void NormalizePositions()
{
lock ( SyncRoot )
{
NormalizePositions( VertexPositions );
}
}
protected static void NormalizePositions( IDictionary<TVertex, float2> vertexPositions )
{
if ( vertexPositions == null || vertexPositions.Count == 0 )
return;
//get the topLeft position
var topLeft = new float2( float.PositiveInfinity, float.PositiveInfinity );
foreach ( var pos in vertexPositions.Values.ToArray() )
{
topLeft.x = Math.Min( topLeft.x, pos.x );
topLeft.y = Math.Min( topLeft.y, pos.y );
}
//translate with the topLeft position
foreach ( var v in vertexPositions.Keys.ToArray() )
{
var pos = vertexPositions[v];
pos.x -= topLeft.x;
pos.y -= topLeft.y;
vertexPositions[v] = pos;
}
}
#endregion
protected void OnIterationEnded( int iteration, float statusInPercent, string message, bool normalizePositions )
{
//copy the actual positions
IDictionary<TVertex, float2> vertexPositions;
lock ( SyncRoot )
{
vertexPositions = new Dictionary<TVertex, float2>( VertexPositions );
}
if ( normalizePositions )
NormalizePositions( vertexPositions );
var args = CreateLayoutIterationEventArgs( iteration, statusInPercent, message, vertexPositions );
OnIterationEnded( args );
}
protected virtual ILayoutIterationEventArgs<TVertex> CreateLayoutIterationEventArgs( int iteration, float statusInPercent, string message, IDictionary<TVertex, float2> vertexPositions )
{
return new LayoutIterationEventArgs<TVertex, TEdge>( iteration, statusInPercent, message, vertexPositions );
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d856cf5544be0ba46b3a6616e0048a6a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2f3d3d09bf972274cae93d379fff0279
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 128e94b302287834cad013aa6e4a0570
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Windows;
using System.Diagnostics;
using QuickGraph;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Simple.Circular
{
public class CircularLayoutAlgorithm<TVertex, TEdge, TGraph> : DefaultParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, CircularLayoutParameters>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IBidirectionalGraph<TVertex, TEdge>
{
readonly IDictionary<TVertex, float2> sizes;
public CircularLayoutAlgorithm( TGraph visitedGraph, IDictionary<TVertex, float2> vertexPositions, IDictionary<TVertex, float2> vertexSizes, CircularLayoutParameters parameters )
: base( visitedGraph, vertexPositions, parameters )
{
//Contract.Requires( vertexSizes != null );
//Contract.Requires( visitedGraph.Vertices.All( v => vertexSizes.ContainsKey( v ) ) );
sizes = vertexSizes;
}
protected override void InternalCompute()
{
//calculate the size of the circle
float perimeter = 0;
float[] halfSize = new float[VisitedGraph.VertexCount];
int i = 0;
foreach ( var v in VisitedGraph.Vertices )
{
float2 s = sizes[v];
halfSize[i] = sqrt( s.x * s.x + s.y * s.y ) * 0.5f;
perimeter += halfSize[i] * 2;
i++;
}
float radius = perimeter / ( 2 * PI );
//
//precalculation
//
float angle = 0, a;
i = 0;
foreach ( var v in VisitedGraph.Vertices )
{
a = sin( halfSize[i] * 0.5f / radius ) * 2;
angle += a;
if ( ReportOnIterationEndNeeded )
VertexPositions[v] = new float2( cos( angle ) * radius + radius, sin( angle ) * radius + radius );
angle += a;
}
if ( ReportOnIterationEndNeeded )
OnIterationEnded( 0, 50, "Precalculation done.", false );
//recalculate radius
radius = angle / ( 2 * PI ) * radius;
//calculation
angle = 0;
i = 0;
foreach ( var v in VisitedGraph.Vertices )
{
a = sin( halfSize[i] * 0.5f / radius ) * 2;
angle += a;
VertexPositions[v] = new float2( cos( angle ) * radius + radius, sin( angle ) * radius + radius );
angle += a;
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6f8341a206cc9964089b93fcac58b273
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,7 @@
namespace GraphSharp.Algorithms.Layout.Simple.Circular
{
public class CircularLayoutParameters : LayoutParametersBase
{
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 91108515ccd418547bd9e48441e6e782
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ff1534e43aabf354c80b48d1cfa6cc2a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,72 @@
using System;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Simple.FDP
{
/// <summary>
/// Parameters of the Fruchterman-Reingold Algorithm (FDP), bounded version.
/// </summary>
public class BoundedFRLayoutParameters : FRLayoutParametersBase
{
#region Properties, Parameters
//some of the parameters declared with 'internal' modifier to 'speed up'
private float _width = 100;
private float _height = 100;
private float _k;
/// <summary>
/// Width of the bounding box.
/// </summary>
public float Width
{
get { return _width; }
set
{
_width = value;
UpdateParameters();
NotifyPropertyChanged("Width");
}
}
/// <summary>
/// Height of the bounding box.
/// </summary>
public float Height
{
get { return _height; }
set
{
_height = value;
UpdateParameters();
NotifyPropertyChanged("Height");
}
}
/// <summary>
/// Constant. <code>IdealEdgeLength = sqrt(height * width / vertexCount)</code>
/// </summary>
public override float K
{
get { return _k; }
}
/// <summary>
/// Gets the initial temperature of the mass.
/// </summary>
public override float InitialTemperature
{
get { return min(Width, Height) / 10; }
}
protected override void UpdateParameters()
{
_k = sqrt(_width * Height / VertexCount);
NotifyPropertyChanged("K");
base.UpdateParameters();
}
#endregion
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 120b9afd84b16064e83179d9a4b23a71
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GraphSharp.Algorithms.Layout.Simple.FDP
{
public enum FRCoolingFunction
{
Linear,
Exponential
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bb279af3040a08c409519d90b9a0de08
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,152 @@
using System;
using System.Collections.Generic;
using QuickGraph;
using QuickGraph.Algorithms;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Simple.FDP
{
public class FRLayoutAlgorithm<Vertex, Edge, Graph> : ParameterizedLayoutAlgorithmBase<Vertex, Edge, Graph, FRLayoutParametersBase>
where Vertex : class
where Edge : IEdge<Vertex>
where Graph : IVertexAndEdgeListGraph<Vertex, Edge>
{
/// <summary>
/// Actual temperature of the 'mass'.
/// </summary>
private float _temperature;
private float _maxWidth = float.PositiveInfinity;
private float _maxHeight = float.PositiveInfinity;
protected override FRLayoutParametersBase DefaultParameters
{
get { return new FreeFRLayoutParameters(); }
}
#region Constructors
public FRLayoutAlgorithm(Graph visitedGraph)
: base(visitedGraph) { }
public FRLayoutAlgorithm(Graph visitedGraph, IDictionary<Vertex, float2> vertexPositions, FRLayoutParametersBase parameters)
: base(visitedGraph, vertexPositions, parameters) { }
#endregion
/// <summary>
/// It computes the layout of the vertices.
/// </summary>
protected override void InternalCompute()
{
//initializing the positions
if (Parameters is BoundedFRLayoutParameters)
{
var param = Parameters as BoundedFRLayoutParameters;
InitializeWithRandomPositions(param.Width, param.Height);
_maxWidth = param.Width;
_maxHeight = param.Height;
}
else
{
InitializeWithRandomPositions(10.0f, 10.0f);
}
Parameters.VertexCount = VisitedGraph.VertexCount;
// Actual temperature of the 'mass'. Used for cooling.
var minimalTemperature = Parameters.InitialTemperature*0.01;
_temperature = Parameters.InitialTemperature;
for (int i = 0;
i < Parameters._iterationLimit
&& _temperature > minimalTemperature
&& State != ComputationState.PendingAbortion;
i++)
{
IterateOne();
//make some cooling
switch (Parameters._coolingFunction)
{
case FRCoolingFunction.Linear:
_temperature *= (1.0f - i / (float)Parameters._iterationLimit);
break;
case FRCoolingFunction.Exponential:
_temperature *= Parameters._lambda;
break;
}
//iteration ended, do some report
if (ReportOnIterationEndNeeded)
{
float statusInPercent = i / (float)Parameters._iterationLimit;
OnIterationEnded(i, statusInPercent, string.Empty, true);
}
}
}
protected void IterateOne()
{
//create the forces (zero forces)
var forces = new Dictionary<Vertex, float2>();
#region Repulsive forces
var force = new float2(0, 0);
foreach (Vertex v in VisitedGraph.Vertices)
{
force.x = 0; force.y = 0;
float2 posV = VertexPositions[v];
foreach (Vertex u in VisitedGraph.Vertices)
{
//doesn't repulse itself
if (u.Equals(v))
continue;
//calculating repulsive force
float2 delta = posV - VertexPositions[u];
float length = max(math.length(delta), float.Epsilon);
delta = delta / length * Parameters.ConstantOfRepulsion / length;
force += delta;
}
forces[v] = force;
}
#endregion
#region Attractive forces
foreach (Edge e in VisitedGraph.Edges)
{
Vertex source = e.Source;
Vertex target = e.Target;
//vonzóerõ számítása a két pont közt
float2 delta = VertexPositions[source] - VertexPositions[target];
float length = Math.Max(math.length(delta), float.Epsilon);
delta = delta / length * pow(length, 2) / Parameters.ConstantOfAttraction;
forces[source] -= delta;
forces[target] += delta;
}
#endregion
#region Limit displacement
foreach (Vertex v in VisitedGraph.Vertices)
{
float2 pos = VertexPositions[v];
//erõ limitálása a temperature-el
float2 delta = forces[v];
float length = Math.Max(math.length(delta), float.Epsilon);
delta = delta / length * Math.Min(math.length(delta), _temperature);
//erõhatás a pontra
pos += delta;
//falon ne menjünk ki
pos.x = Math.Min(_maxWidth, Math.Max(0, pos.x));
pos.y = Math.Min(_maxHeight, Math.Max(0, pos.y));
VertexPositions[v] = pos;
}
#endregion
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e7ce74323a78afc46a5f018de01e0303
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Simple.FDP
{
/// <summary>
/// Parameters base for the Fruchterman-Reingold Algorithm (FDP).
/// </summary>
public abstract class FRLayoutParametersBase : LayoutParametersBase
{
#region Properties, Parameters
private int _vertexCount;
internal float _attractionMultiplier = 1.2f;
internal float _repulsiveMultiplier = 0.6f;
internal int _iterationLimit = 200;
internal float _lambda = 0.95f;
internal FRCoolingFunction _coolingFunction = FRCoolingFunction.Exponential;
/// <summary>
/// Count of the vertices (used to calculate the constants)
/// </summary>
internal int VertexCount
{
get { return _vertexCount; }
set
{
_vertexCount = value;
UpdateParameters();
NotifyPropertyChanged( "VertexCount" );
}
}
protected virtual void UpdateParameters()
{
CalculateConstantOfRepulsion();
CalculateConstantOfAttraction();
}
private void CalculateConstantOfRepulsion()
{
ConstantOfRepulsion = pow( K * _repulsiveMultiplier, 2 );
NotifyPropertyChanged( "ConstantOfRepulsion" );
}
private void CalculateConstantOfAttraction()
{
ConstantOfAttraction = K * _attractionMultiplier;
NotifyPropertyChanged( "ConstantOfAttraction" );
}
/// <summary>
/// Gets the computed ideal edge length.
/// </summary>
public abstract float K { get; }
/// <summary>
/// Gets the initial temperature of the mass.
/// </summary>
public abstract float InitialTemperature { get; }
/// <summary>
/// Constant. <code>Equals with K * attractionMultiplier</code>
/// </summary>
public float ConstantOfAttraction { get; private set; }
/// <summary>
/// Multiplier of the attraction. Default value is 2.
/// </summary>
public float AttractionMultiplier
{
get { return _attractionMultiplier; }
set
{
_attractionMultiplier = value;
CalculateConstantOfAttraction();
NotifyPropertyChanged( "AttractionMultiplier" );
}
}
/// <summary>
/// Constant. Equals with <code>Pow(K * repulsiveMultiplier, 2)</code>
/// </summary>
public float ConstantOfRepulsion { get; private set; }
/// <summary>
/// Multiplier of the repulsion. Default value is 1.
/// </summary>
public float RepulsiveMultiplier
{
get { return _repulsiveMultiplier; }
set
{
_repulsiveMultiplier = value;
CalculateConstantOfRepulsion();
NotifyPropertyChanged( "RepulsiveMultiplier" );
}
}
/// <summary>
/// Limit of the iterations. Default value is 200.
/// </summary>
public int IterationLimit
{
get { return _iterationLimit; }
set
{
_iterationLimit = value;
NotifyPropertyChanged( "IterationLimit" );
}
}
/// <summary>
/// Lambda for the cooling. Default value is 0.95.
/// </summary>
public float Lambda
{
get { return _lambda; }
set
{
_lambda = value;
NotifyPropertyChanged( "Lamdba" );
}
}
/// <summary>
/// Gets or sets the cooling function which could be Linear or Exponential.
/// </summary>
public FRCoolingFunction CoolingFunction
{
get { return _coolingFunction; }
set
{
_coolingFunction = value;
NotifyPropertyChanged( "CoolingFunction" );
}
}
#endregion
/// <summary>
/// Default constructor
/// </summary>
public FRLayoutParametersBase()
{
//update the parameters
UpdateParameters();
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 957efa365a091cc4486edd6c7f0f6546
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace GraphSharp.Algorithms.Layout.Simple.FDP
{
public class FreeFRLayoutParameters : FRLayoutParametersBase
{
private float _idealEdgeLength = 10;
public override float K
{
get { return _idealEdgeLength; }
}
public override float InitialTemperature
{
get { return sqrt(pow(_idealEdgeLength, 2) * VertexCount); }
}
/// <summary>
/// Constant. Represents the ideal length of the edges.
/// </summary>
public float IdealEdgeLength
{
get { return _idealEdgeLength; }
set
{
_idealEdgeLength = value;
UpdateParameters();
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 64d97455df1107244af8c38e4b944298
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,179 @@
using System;
using System.Collections.Generic;
using QuickGraph;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using Random = System.Random;
namespace GraphSharp.Algorithms.Layout.Simple.FDP
{
public class ISOMLayoutAlgorithm<TVertex, TEdge, TGraph> : DefaultParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, ISOMLayoutParameters>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IBidirectionalGraph<TVertex, TEdge>
{
#region Private fields
private Queue<TVertex> _queue;
private Dictionary<TVertex, ISOMData> _isomDataDict;
private readonly Random _rnd = new Random( DateTime.Now.Millisecond );
private float2 _tempPos;
private float adaptation;
private int radius;
#endregion
#region Constructors
public ISOMLayoutAlgorithm( TGraph visitedGraph, ISOMLayoutParameters oldParameters )
: base( visitedGraph )
{
Init( oldParameters );
}
public ISOMLayoutAlgorithm( TGraph visitedGraph, IDictionary<TVertex, float2> vertexPositions,
ISOMLayoutParameters oldParameters )
: base( visitedGraph, vertexPositions, oldParameters )
{
Init( oldParameters );
}
protected void Init( ISOMLayoutParameters oldParameters )
{
//init _parameters
base.InitParameters( oldParameters );
_queue = new Queue<TVertex>();
_isomDataDict = new Dictionary<TVertex, ISOMData>();
adaptation = Parameters.InitialAdaption;
}
#endregion
protected override void InternalCompute()
{
//initialize vertex positions
InitializeWithRandomPositions( Parameters.Width, Parameters.Height );
//initialize ISOM data
foreach ( var vertex in VisitedGraph.Vertices )
{
ISOMData isomData;
if ( !_isomDataDict.TryGetValue( vertex, out isomData ) )
{
isomData = new ISOMData();
_isomDataDict[vertex] = isomData;
}
}
radius = Parameters.InitialRadius;
for ( int epoch = 0; epoch < Parameters.MaxEpoch; epoch++ )
{
Adjust();
//Update Parameters
float factor = exp( -1 * Parameters.CoolingFactor * ( 1.0f * epoch / Parameters.MaxEpoch ) );
adaptation = Math.Max( Parameters.MinAdaption, factor * Parameters.InitialAdaption );
if ( radius > Parameters.MinRadius && epoch % Parameters.RadiusConstantTime == 0 )
{
radius--;
}
//report
if ( ReportOnIterationEndNeeded )
OnIterationEnded( epoch, (float)epoch / (float)Parameters.MaxEpoch, "Iteration " + epoch + " finished.", true );
else if (ReportOnProgressChangedNeeded)
OnProgressChanged( (float)epoch / (float)Parameters.MaxEpoch * 100 );
}
}
/// <summary>
/// R<>ntsunk egyet az <20>sszes ponton.
/// </summary>
protected void Adjust()
{
_tempPos = new float2();
//get a random point in the container
_tempPos.x = 0.1f * Parameters.Width + ( (float) _rnd.NextDouble() * 0.8f * Parameters.Width );
_tempPos.y = 0.1f * Parameters.Height + ( (float) _rnd.NextDouble() * 0.8f * Parameters.Height );
//find the closest vertex to this random point
TVertex closest = GetClosest( _tempPos );
//adjust the vertices to the selected vertex
foreach ( TVertex v in VisitedGraph.Vertices )
{
ISOMData vid = _isomDataDict[v];
vid.Distance = 0;
vid.Visited = false;
}
AdjustVertex( closest );
}
private void AdjustVertex( TVertex closest )
{
_queue.Clear();
ISOMData vid = _isomDataDict[closest];
vid.Distance = 0;
vid.Visited = true;
_queue.Enqueue( closest );
while ( _queue.Count > 0 )
{
TVertex current = _queue.Dequeue();
ISOMData currentVid = _isomDataDict[current];
float2 pos = VertexPositions[current];
float2 force = _tempPos - pos;
float factor = adaptation / pow( 2, currentVid.Distance );
pos += factor * force;
VertexPositions[current] = pos;
//ha m<>g a hat<61>k<EFBFBD>r<EFBFBD>n bel<65>l van
if ( currentVid.Distance < radius )
{
//akkor a szomszedokra is hatassal vagyunk
foreach ( TVertex neighbour in VisitedGraph.GetNeighbours<TVertex, TEdge>( current ) )
{
ISOMData nvid = _isomDataDict[neighbour];
if ( !nvid.Visited )
{
nvid.Visited = true;
nvid.Distance = currentVid.Distance + 1;
_queue.Enqueue( neighbour );
}
}
}
}
}
/// <summary>
/// Finds the the closest vertex to the given position.
/// </summary>
/// <param name="tempPos">The position.</param>
/// <returns>Returns with the reference of the closest vertex.</returns>
private TVertex GetClosest( float2 tempPos )
{
TVertex vertex = default( TVertex );
float distance = float.MaxValue;
//find the closest vertex
foreach ( TVertex v in VisitedGraph.Vertices )
{
float d = length( tempPos - VertexPositions[v] );
if ( d < distance )
{
vertex = v;
distance = d;
}
}
return vertex;
}
private class ISOMData
{
public float2 Force = new float2();
public bool Visited = false;
public float Distance = 0.0f;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 035f3d213d531c14fa6592266205bda9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,131 @@
namespace GraphSharp.Algorithms.Layout.Simple.FDP
{
public class ISOMLayoutParameters : LayoutParametersBase
{
private float _width = 300;
/// <summary>
/// Width of the bounding box. Default value is 300.
/// </summary>
public float Width
{
get { return _width; }
set
{
_width = value;
NotifyPropertyChanged("Width");
}
}
private float _height = 300;
/// <summary>
/// Height of the bounding box. Default value is 300.
/// </summary>
public float Height
{
get { return _height; }
set
{
_height = value;
NotifyPropertyChanged("Height");
}
}
private int maxEpoch = 2000;
/// <summary>
/// Maximum iteration number. Default value is 2000.
/// </summary>
public int MaxEpoch
{
get { return maxEpoch; }
set
{
maxEpoch = value;
NotifyPropertyChanged("MaxEpoch");
}
}
private int _radiusConstantTime = 100;
/// <summary>
/// Radius constant time. Default value is 100.
/// </summary>
public int RadiusConstantTime
{
get { return _radiusConstantTime; }
set
{
_radiusConstantTime = value;
NotifyPropertyChanged("RadiusConstantTime");
}
}
private int _initialRadius = 5;
/// <summary>
/// Default value is 5.
/// </summary>
public int InitialRadius
{
get { return _initialRadius; }
set
{
_initialRadius = value;
NotifyPropertyChanged("InitialRadius");
}
}
private int _minRadius = 1;
/// <summary>
/// Minimal radius. Default value is 1.
/// </summary>
public int MinRadius
{
get { return _minRadius; }
set
{
_minRadius = value;
NotifyPropertyChanged("MinRadius");
}
}
private float _initialAdaption = 0.9f;
/// <summary>
/// Default value is 0.9.
/// </summary>
public float InitialAdaption
{
get { return _initialAdaption; }
set
{
_initialAdaption = value;
NotifyPropertyChanged("InitialAdaption");
}
}
private float _minAdaption;
/// <summary>
/// Default value is 0.
/// </summary>
public float MinAdaption
{
get { return _minAdaption; }
set
{
_minAdaption = value;
NotifyPropertyChanged("MinAdaption");
}
}
private float _coolingFactor = 2;
/// <summary>
/// Default value is 2.
/// </summary>
public float CoolingFactor
{
get { return _coolingFactor; }
set
{
_coolingFactor = value;
NotifyPropertyChanged("CoolingFactor");
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8b1088bfa03e3fb41b450bdd2bfacc22
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,296 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using QuickGraph;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using System.Diagnostics;
namespace GraphSharp.Algorithms.Layout.Simple.FDP
{
public class KKLayoutAlgorithm<Vertex, Edge, Graph> : DefaultParameterizedLayoutAlgorithmBase<Vertex, Edge, Graph, KKLayoutParameters>
where Vertex : class
where Edge : IEdge<Vertex>
where Graph : IBidirectionalGraph<Vertex, Edge>
{
#region Variables needed for the layout
/// <summary>
/// Minimal distances between the vertices.
/// </summary>
private float[,] distances;
private float[,] edgeLengths;
private float[,] springConstants;
//cache for speed-up
private Vertex[] vertices;
/// <summary>
/// Positions of the vertices, stored by indices.
/// </summary>
private float2[] positions;
private float diameter;
private float idealEdgeLength;
#endregion
#region Contructors
public KKLayoutAlgorithm( Graph visitedGraph, KKLayoutParameters oldParameters )
: this( visitedGraph, null, oldParameters ) { }
public KKLayoutAlgorithm( Graph visitedGraph, IDictionary<Vertex, float2> vertexPositions,
KKLayoutParameters oldParameters )
: base( visitedGraph, vertexPositions, oldParameters ) { }
#endregion
protected override void InternalCompute()
{
#region Initialization
distances = new float[VisitedGraph.VertexCount, VisitedGraph.VertexCount];
edgeLengths = new float[VisitedGraph.VertexCount, VisitedGraph.VertexCount];
springConstants = new float[VisitedGraph.VertexCount, VisitedGraph.VertexCount];
vertices = new Vertex[VisitedGraph.VertexCount];
positions = new float2[VisitedGraph.VertexCount];
//initializing with random positions
InitializeWithRandomPositions( Parameters.Width, Parameters.Height );
//copy positions into array (speed-up)
int index = 0;
foreach ( var v in VisitedGraph.Vertices )
{
vertices[index] = v;
positions[index] = VertexPositions[v];
index++;
}
//calculating the diameter of the graph
//TODO check the diameter algorithm
diameter = VisitedGraph.GetDiameter<Vertex, Edge, Graph>( out distances );
//L0 is the length of a side of the display area
float L0 = Math.Min( Parameters.Width, Parameters.Height );
//ideal length = L0 / max d_i,j
idealEdgeLength = ( L0 / diameter ) * Parameters.LengthFactor;
//calculating the ideal distance between the nodes
for ( int i = 0; i < VisitedGraph.VertexCount - 1; i++ )
{
for ( int j = i + 1; j < VisitedGraph.VertexCount; j++ )
{
//distance between non-adjacent vertices
float dist = diameter * Parameters.DisconnectedMultiplier;
//calculating the minimal distance between the vertices
if ( distances[i, j] != float.MaxValue )
dist = Math.Min( distances[i, j], dist );
if ( distances[j, i] != float.MaxValue )
dist = Math.Min( distances[j, i], dist );
distances[i, j] = distances[j, i] = dist;
edgeLengths[i, j] = edgeLengths[j, i] = idealEdgeLength * dist;
springConstants[i, j] = springConstants[j, i] = Parameters.K / pow( dist, 2 );
}
}
#endregion
int n = VisitedGraph.VertexCount;
if ( n == 0 )
return;
//TODO check this condition
for ( int currentIteration = 0; currentIteration < Parameters.MaxIterations; currentIteration++ )
{
#region An iteration
float maxDeltaM = float.NegativeInfinity;
int pm = -1;
//get the 'p' with the max delta_m
for ( int i = 0; i < n; i++ )
{
float deltaM = CalculateEnergyGradient( i );
if ( maxDeltaM < deltaM )
{
maxDeltaM = deltaM;
pm = i;
}
}
//TODO is needed?
if ( pm == -1 )
return;
//calculating the delta_x & delta_y with the Newton-Raphson method
//there is an upper-bound for the while (deltaM > epsilon) {...} cycle (100)
for ( int i = 0; i < 100; i++ )
{
positions[pm] += CalcDeltaXY( pm );
float deltaM = CalculateEnergyGradient( pm );
//real stop condition
if ( deltaM < float.Epsilon )
break;
}
//what if some of the vertices would be exchanged?
if ( Parameters.ExchangeVertices && maxDeltaM < float.Epsilon )
{
float energy = CalcEnergy();
for ( int i = 0; i < n - 1; i++ )
{
for ( int j = i + 1; j < n; j++ )
{
float xenergy = CalcEnergyIfExchanged( i, j );
if ( energy > xenergy )
{
float2 p = positions[i];
positions[i] = positions[j];
positions[j] = p;
return;
}
}
}
}
#endregion
if ( ReportOnIterationEndNeeded )
Report( currentIteration );
}
Report( Parameters.MaxIterations );
}
protected void Report( int currentIteration )
{
#region Copy the calculated positions
//poz<6F>ci<63>k <20>tm<74>sol<6F>sa a VertexPositions-ba
for ( int i = 0; i < vertices.Length; i++ )
VertexPositions[vertices[i]] = positions[i];
#endregion
OnIterationEnded( currentIteration, (float)currentIteration / (float)Parameters.MaxIterations, "Iteration " + currentIteration + " finished.", true );
}
/// <returns>
/// Calculates the energy of the state where
/// the positions of the vertex 'p' & 'q' are exchanged.
/// </returns>
private float CalcEnergyIfExchanged( int p, int q )
{
float energy = 0;
for ( int i = 0; i < vertices.Length - 1; i++ )
{
for ( int j = i + 1; j < vertices.Length; j++ )
{
int ii = ( i == p ) ? q : i;
int jj = ( j == q ) ? p : j;
float l_ij = edgeLengths[i, j];
float k_ij = springConstants[i, j];
float dx = positions[ii].x - positions[jj].x;
float dy = positions[ii].y - positions[jj].y;
energy += k_ij / 2 * ( dx * dx + dy * dy + l_ij * l_ij -
2 * l_ij * sqrt( dx * dx + dy * dy ) );
}
}
return energy;
}
/// <summary>
/// Calculates the energy of the spring system.
/// </summary>
/// <returns>Returns with the energy of the spring system.</returns>
private float CalcEnergy()
{
float energy = 0, dist, l_ij, k_ij, dx, dy;
for ( int i = 0; i < vertices.Length - 1; i++ )
{
for ( int j = i + 1; j < vertices.Length; j++ )
{
dist = distances[i, j];
l_ij = edgeLengths[i, j];
k_ij = springConstants[i, j];
dx = positions[i].x - positions[j].x;
dy = positions[i].y - positions[j].y;
energy += k_ij / 2 * ( dx * dx + dy * dy + l_ij * l_ij -
2 * l_ij * sqrt( dx * dx + dy * dy ) );
}
}
return energy;
}
/// <summary>
/// Determines a step to new position of the vertex m.
/// </summary>
/// <returns></returns>
private float2 CalcDeltaXY( int m )
{
float dxm = 0, dym = 0, d2xm = 0, dxmdym = 0, dymdxm = 0, d2ym = 0;
float l, k, dx, dy, d, ddd;
for ( int i = 0; i < vertices.Length; i++ )
{
if ( i != m )
{
//common things
l = edgeLengths[m, i];
k = springConstants[m, i];
dx = positions[m].x - positions[i].x;
dy = positions[m].y - positions[i].y;
//distance between the points
d = sqrt( dx * dx + dy * dy );
ddd = pow( d, 3 );
dxm += k * ( 1 - l / d ) * dx;
dym += k * ( 1 - l / d ) * dy;
//TODO isn't it wrong?
d2xm += k * ( 1 - l * pow( dy, 2 ) / ddd );
//d2E_d2xm += k_mi * ( 1 - l_mi / d + l_mi * dx * dx / ddd );
dxmdym += k * l * dx * dy / ddd;
//d2E_d2ym += k_mi * ( 1 - l_mi / d + l_mi * dy * dy / ddd );
//TODO isn't it wrong?
d2ym += k * ( 1 - l * pow( dx, 2 ) / ddd );
}
}
// d2E_dymdxm equals to d2E_dxmdym
dymdxm = dxmdym;
float denomi = d2xm * d2ym - dxmdym * dymdxm;
float deltaX = ( dxmdym * dym - d2ym * dxm ) / denomi;
float deltaY = ( dymdxm * dxm - d2xm * dym ) / denomi;
return new float2( deltaX, deltaY );
}
/// <summary>
/// Calculates the gradient energy of a vertex.
/// </summary>
/// <param name="m">The index of the vertex.</param>
/// <returns>Calculates the gradient energy of the vertex <code>m</code>.</returns>
private float CalculateEnergyGradient( int m )
{
float dxm = 0, dym = 0, dx, dy, d, common;
// { 1, if m < i
// sign = {
// { -1, if m > i
for ( int i = 0; i < vertices.Length; i++ )
{
if ( i == m )
continue;
//differences of the positions
dx = ( positions[m].x - positions[i].x );
dy = ( positions[m].y - positions[i].y );
//distances of the two vertex (by positions)
d = sqrt( dx * dx + dy * dy );
common = springConstants[m, i] * ( 1 - edgeLengths[m, i] / d );
dxm += common * dx;
dym += common * dy;
}
// delta_m = sqrt((dE/dx)^2 + (dE/dy)^2)
return sqrt( dxm * dxm + dym * dym );
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8b20148a582857e4d89cfe8721fe5814
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,113 @@
namespace GraphSharp.Algorithms.Layout.Simple.FDP
{
public class KKLayoutParameters : LayoutParametersBase
{
private float width = 300;
/// <summary>
/// Width of the bounding box.
/// </summary>
public float Width
{
get { return width; }
set
{
width = value;
NotifyPropertyChanged("Width");
}
}
private float height = 300;
/// <summary>
/// Height of the bounding box.
/// </summary>
public float Height
{
get { return height; }
set
{
height = value;
NotifyPropertyChanged("Height");
}
}
private int maxIterations = 200;
/// <summary>
/// Maximum number of the iterations.
/// </summary>
public int MaxIterations
{
get { return maxIterations; }
set
{
maxIterations = value;
NotifyPropertyChanged("MaxIterations");
}
}
private float _k = 1;
public float K
{
get { return _k; }
set
{
_k = value;
NotifyPropertyChanged("K");
}
}
private bool adjustForGravity;
/// <summary>
/// If true, then after the layout process, the vertices will be moved, so the barycenter will be
/// in the center point of the bounding box.
/// </summary>
public bool AdjustForGravity
{
get { return adjustForGravity; }
set
{
adjustForGravity = value;
NotifyPropertyChanged("AdjustForGravity");
}
}
private bool exchangeVertices;
public bool ExchangeVertices
{
get { return exchangeVertices; }
set
{
exchangeVertices = value;
NotifyPropertyChanged("ExchangeVertices");
}
}
private float lengthFactor = 1;
/// <summary>
/// Multiplier of the ideal edge length. (With this parameter the user can modify the ideal edge length).
/// </summary>
public float LengthFactor
{
get { return lengthFactor; }
set
{
lengthFactor = value;
NotifyPropertyChanged("LengthFactor");
}
}
private float disconnectedMultiplier = 0.5f;
/// <summary>
/// Ideal distance between the disconnected points (1 is equal the ideal edge length).
/// </summary>
public float DisconnectedMultiplier
{
get { return disconnectedMultiplier; }
set
{
disconnectedMultiplier = value;
NotifyPropertyChanged("DisconnectedMultiplier");
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1208ce3820e09c944930b6cc628508ce
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,156 @@
using System;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using QuickGraph;
namespace GraphSharp.Algorithms.Layout.Simple.FDP
{
public partial class LinLogLayoutAlgorithm<TVertex, TEdge, TGraph>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IBidirectionalGraph<TVertex, TEdge>
{
class QuadTree
{
#region Properties
private readonly QuadTree[] children = new QuadTree[4];
public QuadTree[] Children
{
get { return children; }
}
private int index;
public int Index
{
get { return index; }
}
private float2 position;
public float2 Position
{
get { return position; }
}
private float weight;
public float Weight
{
get { return weight; }
}
private float2 minPos;
private float2 maxPos;
#endregion
public float Width
{
get
{
return Math.Max( maxPos.x - minPos.x, maxPos.y - minPos.y );
}
}
protected const int maxDepth = 20;
public QuadTree( int index, float2 position, float weight, float2 minPos, float2 maxPos )
{
this.index = index;
this.position = position;
this.weight = weight;
this.minPos = minPos;
this.maxPos = maxPos;
}
public void AddNode( int nodeIndex, float2 nodePos, float nodeWeight, int depth )
{
if ( depth > maxDepth )
return;
if ( index >= 0 )
{
AddNode2( index, position, weight, depth );
index = -1;
}
position.x = ( position.x * weight + nodePos.x * nodeWeight ) / ( weight + nodeWeight );
position.y = ( position.y * weight + nodePos.y * nodeWeight ) / ( weight + nodeWeight );
weight += nodeWeight;
AddNode2( nodeIndex, nodePos, nodeWeight, depth );
}
protected void AddNode2( int nodeIndex, float2 nodePos, float nodeWeight, int depth )
{
//Debug.WriteLine( string.Format( "AddNode2 {0} {1} {2} {3}", nodeIndex, nodePos, nodeWeight, depth ) );
int childIndex = 0;
float middleX = ( minPos.x + maxPos.x ) / 2;
float middleY = ( minPos.y + maxPos.y ) / 2;
if ( nodePos.x > middleX )
childIndex += 1;
if ( nodePos.y > middleY )
childIndex += 2;
//Debug.WriteLine( string.Format( "childIndex: {0}", childIndex ) );
if ( children[childIndex] == null )
{
var newMin = new float2();
var newMax = new float2();
if ( nodePos.x <= middleX )
{
newMin.x = minPos.x;
newMax.x = middleX;
}
else
{
newMin.x = middleX;
newMax.x = maxPos.x;
}
if ( nodePos.y <= middleY )
{
newMin.y = minPos.y;
newMax.y = middleY;
}
else
{
newMin.y = middleY;
newMax.y = maxPos.y;
}
children[childIndex] = new QuadTree( nodeIndex, nodePos, nodeWeight, newMin, newMax );
}
else
{
children[childIndex].AddNode( nodeIndex, nodePos, nodeWeight, depth + 1 );
}
}
/// <summary>
/// Az adott rész pozícióját újraszámítja, levonva belőle a mozgatott node részét.
/// </summary>
/// <param name="oldPos"></param>
/// <param name="newPos"></param>
/// <param name="nodeWeight"></param>
public void MoveNode( float2 oldPos, float2 newPos, float nodeWeight )
{
position += ( ( newPos - oldPos ) * ( nodeWeight / weight ) );
int childIndex = 0;
float middleX = ( minPos.x + maxPos.x ) / 2;
float middleY = ( minPos.y + maxPos.y ) / 2;
if ( oldPos.x > middleX )
childIndex += 1;
if ( oldPos.y > middleY )
childIndex += 1 << 1;
if ( children[childIndex] != null )
children[childIndex].MoveNode( oldPos, newPos, nodeWeight );
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0a3c31153aed4c0419d150995264d375
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

Some files were not shown because too many files have changed in this diff Show more