/// <summary> /// Calculates the maximum distance for all values for the provided attribute /// using the provided ISimilarityMeasure /// </summary> /// <param name="attribute">The attribute to retrieve the maximum distance for</param> /// <param name="measure">The ISimilarityMeasure to use to calculate the distance</param> /// <returns>the maximum distance value for all values for the given attribute</returns> private double CalculateMaxDistance(Data.Attributes.Attribute attribute, ISimilarityMeasure measure) { // Ensure that the global collection contains the attribute if (!GlobalAttributeCollection.GetInstance(this.scope).ContainsAttribute(attribute)) { return(0); } double maxDistance = double.MinValue; List <string> values = new List <string>(GlobalAttributeCollection.GetInstance(this.scope).GetAttributeValues(attribute)); //TODO: IS THERE A MORE EFFICIENT METHOD FOR HANDLING THIS?? for (int i = 0; i < values.Count; i++) { // get the value for this item string a = values[i]; // Compare the current item to all other items in the list for (int j = 0; j < i; j++) { // get the value for this item string b = values[j]; double?distance = measure.CalculateDistance(a, b); if (distance != null) { maxDistance = Math.Max(maxDistance, (double)distance); } } } return(maxDistance); }
public void TestGettingSingletonInstanceWithSameNameAreSameInstance() { GlobalAttributeCollection globalAttributeCollection1 = GlobalAttributeCollection.GetInstance("SnagL"); GlobalAttributeCollection globalAttributeCollection2 = GlobalAttributeCollection.GetInstance("SnagL"); Assert.AreEqual <GlobalAttributeCollection>(globalAttributeCollection1, globalAttributeCollection2); }
/// <summary> /// Calculates the maximum distance for all values for the provided attribute /// name using the provided ISimilarityMeasure /// </summary> /// <param name="attributeName">The attribute name to retrieve the maximum distance for</param> /// <param name="measure">The ISimilarityMeasure to use to calculate the distance</param> /// <returns>the maximum distance value for all values for the given attribute</returns> private double CalculateMaxDistance(string attributeName, ISimilarityMeasure measure) { // Get the Attribute instance based on the provided attribute name Data.Attributes.Attribute attributeFound = GlobalAttributeCollection.GetInstance(this.scope).GetAttributes().Where(attribute => attribute.Name == attributeName).FirstOrDefault(); return(CalculateMaxDistance(attributeFound, measure)); }
public void TestGettingSingletonInstancesWithDifferentNamesAreDifferentInstances() { GlobalAttributeCollection globalAttributeCollection1 = GlobalAttributeCollection.GetInstance("SnagL1"); GlobalAttributeCollection globalAttributeCollection2 = GlobalAttributeCollection.GetInstance("SnagL2"); Assert.AreNotEqual <GlobalAttributeCollection>(globalAttributeCollection1, globalAttributeCollection2); }
public void TestCollectionChangedWithUpdate() { bool eventRaised = false; NotifyCollectionChangedAction action = NotifyCollectionChangedAction.Add; Attribute attribute = new SnagL.Infrastructure.Data.Attributes.Attribute("SnagL"); AttributeValue original = new AttributeValue("SnagL"); AttributeValue newValue = new AttributeValue("SnagLNew"); GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); globalAttributeCollection.Clear(); globalAttributeCollection.AttributeListUpdated += (sender, e) => { action = e.Action; eventRaised = true; }; EnqueueCallback(() => globalAttributeCollection.Add(attribute, original)); EnqueueCallback(() => globalAttributeCollection.Update(attribute, newValue, original)); EnqueueConditional(() => eventRaised); EnqueueCallback(() => Assert.IsTrue(action == NotifyCollectionChangedAction.Replace)); EnqueueCallback(() => Assert.IsTrue(eventRaised)); EnqueueTestComplete(); }
/// <summary> /// /// </summary> /// <param name="targetNode"></param> /// <param name="attribute"></param> /// <param name="attributeValue"></param> private void UpdateAttributeCollection(Node targetNode, Data.Attributes.Attribute attribute, AttributeValue attributeValue) { // Add the attribute name and value to the nodes attribute collection targetNode.Attributes.Add(attribute.Name, attributeValue); // Update the global attribute collection GlobalAttributeCollection.GetInstance(generatedGraph.Scope).Add(attribute, attributeValue); }
public void TestContainsAttribute() { GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); Attribute attribute = new Attribute("SnagL"); AttributeValue original = new AttributeValue("SnagL"); globalAttributeCollection.Add(attribute, original); Assert.IsTrue(globalAttributeCollection.ContainsAttribute(attribute)); }
public void TestAttributeAccessor() { GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); Attribute attribute = new Attribute("SnagL"); AttributeValue original = new AttributeValue("SnagL"); globalAttributeCollection.Clear(); globalAttributeCollection.Add(attribute, original); Assert.IsTrue(globalAttributeCollection[attribute].Contains("SnagL")); }
public void TestStringAccessor() { GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); Attribute attribute = new Attribute("SnagL"); AttributeValue original = new AttributeValue("SnagL"); globalAttributeCollection.Clear(); globalAttributeCollection.Add(attribute, original); Assert.IsTrue(globalAttributeCollection["SnagL"].Count > 0); }
public void VerifyCollectionContainsAttributeAfterAddingIt() { GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); Attribute attribute = new Attribute("SnagL"); AttributeValue value = new AttributeValue("SnagL"); bool actual; globalAttributeCollection.Add(attribute, value); actual = globalAttributeCollection.ContainsAttribute(attribute); Assert.IsTrue(actual); }
public void TestGetAttributeByName() { Attribute actual; Attribute expected = new Attribute("SnagL"); AttributeValue value = new AttributeValue("SnagL"); GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); globalAttributeCollection.Add(expected, value); actual = globalAttributeCollection.GetAttribute(expected.Name); Assert.AreEqual <Attribute>(expected, actual); }
/// <summary> /// Returns the preferred similarity measure using the provided attribute /// name /// </summary> /// <param name="attributeName">The name of the target attribute</param> /// <returns>an instance of the Preffered Similarity Measure; otherwise null</returns> private ISimilarityMeasure GetPrefferedSimilarityMeasure(string attributeName) { // Retrieve the Attribute instance from the GlobalAttributeCollection Data.Attributes.Attribute attribute = GlobalAttributeCollection.GetInstance(this.scope).GetAttribute(attributeName); if (attribute == null) { return(null); } else { return(GetPrefferedSimilarityMeasure(attribute)); } }
public void TestRemoveByAttributeRemovesAttribute() { GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); Attribute attribute = new Attribute("SnagL"); AttributeValue original = new AttributeValue("SnagL"); globalAttributeCollection.Add(attribute, original); if (!globalAttributeCollection.ContainsAttribute(attribute)) { Assert.Inconclusive("The Attribute that was just added to the GlobalAttributeCollection was not found"); } globalAttributeCollection.Remove(attribute); Assert.IsFalse(globalAttributeCollection.ContainsAttribute(attribute)); }
public void TestAddMethodThrowsExceptionIfNullAttributeValue() { bool exceptionCaught = false; GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); Attribute attribute = new Attribute("SnagL"); try { globalAttributeCollection.Add(attribute, null); } catch (System.ArgumentNullException) { exceptionCaught = true; } Assert.IsTrue(exceptionCaught); }
public void TestClearMethodClearsGlobalAttributeCollection() { GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); Attribute attribute = new Attribute("SnagL"); AttributeValue original = new AttributeValue("SnagL"); globalAttributeCollection.Add(attribute, original); // Make sure everything is working. Otherwise, we might have an invalid test. if (!(globalAttributeCollection.GetAttributes().Count > 0)) { Assert.Inconclusive("Attribute collection count wasn't > 0 after attribute added."); } globalAttributeCollection.Clear(); Assert.IsTrue(globalAttributeCollection.GetAttributes().Count == 0); }
public static NodeMapData GetNode(NodeViewModelBase uiNodeVM) { NodeMapData objNode; if (uiNodeVM.GetType().Equals(typeof(IconNodeViewModel))) { objNode = new IconNodeMapData(uiNodeVM.ParentNode.ID); // Property IconNodeViewModel iconNodeVM = (IconNodeViewModel)uiNodeVM; if (iconNodeVM.ImageSource != null) { ((IconNodeMapData)objNode).ImageSource = new System.Uri(iconNodeVM.ImageSource, UriKind.Relative); } } else { objNode = new TextNodeMapData(uiNodeVM.ParentNode.ID); } // Properties objNode.Description = uiNodeVM.Description; objNode.Label = uiNodeVM.DisplayValue; Size dimension = new Size(uiNodeVM.Width, uiNodeVM.Height); objNode.Dimension = dimension; objNode.Position = uiNodeVM.Position; objNode.IsHidden = uiNodeVM.IsHidden; objNode.BackgroundColor = uiNodeVM.BackgroundColor.Color; objNode.SelectionColor = uiNodeVM.SelectionColor.Color; // Attributes foreach (KeyValuePair <string, AttributeValue> uiNodeVMAttrKVP in uiNodeVM.ParentNode.Attributes) { Attributes.Attribute uiNodeVMAttribute = GlobalAttributeCollection.GetInstance(uiNodeVM.Scope).GetAttribute(uiNodeVMAttrKVP.Key); AttributeMapData objNodeAttribute = new AttributeMapData(uiNodeVMAttrKVP.Key, uiNodeVMAttrKVP.Value.Value); objNode.Attributes.Add(objNodeAttribute.Name, objNodeAttribute); objNodeAttribute.SemanticType = uiNodeVMAttribute.SemanticType; objNodeAttribute.SimilarityMeasure = uiNodeVMAttribute.PreferredSimilarityMeasure; objNodeAttribute.IsHidden = !uiNodeVMAttribute.Visible; } return(objNode); }
public void TestCollectionChangedWithAdd() { bool eventRaised = false; Attribute attribute = new SnagL.Infrastructure.Data.Attributes.Attribute("SnagL"); AttributeValue newValue = new AttributeValue("SnagL"); GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); globalAttributeCollection.Clear(); globalAttributeCollection.AttributeListUpdated += (sender, e) => { eventRaised = true; }; EnqueueCallback(() => globalAttributeCollection.Add(attribute, newValue)); EnqueueConditional(() => eventRaised); EnqueueCallback(() => Assert.IsTrue(eventRaised)); EnqueueTestComplete(); }
/// <summary> /// Create a new instance of the SimilarityClustering class /// </summary> public SimilarityClustering() { this.scope = GraphManager.Instance.DefaultGraphComponentsInstance.Scope; clusterHighlights = new ClusterHighlights(scope); // Get a reference to the GlobaleAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance(scope); // Initialize the AttributeSimilarityManager and obtain a reference to it AttributeSimilarityManager.InitialSetup(scope); attributeSimilarityManager = AttributeSimilarityManager.Instance; // Initialize the background worker worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.DoWork += new DoWorkEventHandler(DoWorkHandler); worker.ProgressChanged += new ProgressChangedEventHandler(ProgressChangedHandler); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompletedHandler); }
/// <summary> /// Initialize an instance of the AttributeSimilarityManager class /// </summary> private void Initialize() { ExtensionManager.ComposeParts(this); // Add the attributes currently in the Global Attribute // Collection to our list. foreach (Data.Attributes.Attribute attribute in GlobalAttributeCollection.GetInstance(this.scope).GetAttributes()) { if (attribute.Visible) { this.managedAttributes.Add(attribute.Name); } } this.managedAttributes.CollectionChanged += new NotifyCollectionChangedEventHandler(managedAttributes_CollectionChanged); this.distancesCache = new Dictionary <Tuple <string, string>, double>(); // Setup a listener for the AttributeListUpdated event GlobalAttributeCollection.GetInstance(this.scope).AttributeListUpdated += new EventHandler <AttributeEventArgs>(GlobalAttributeCollection_AttributeListUpdated); }
/// <summary> /// Returns a collection of all Similarity Measures that are valid for /// the specified attribute /// </summary> /// <param name="attributeName">The attribute name to retrieve valid Similarity /// Measures for</param> /// <returns>a collection of all Similarity Measures that are valid /// for the specified attribute</returns> public ICollection <ISimilarityMeasure> GetValidSimilarityMeasures(string attributeName) { // Validate the parameter if (string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("AttributeName", "No valid attribute name was provided"); } List <ISimilarityMeasure> validMeasures = new List <ISimilarityMeasure>(); // Retrieve the Attribute instance from the GlobalAttributeCollection Data.Attributes.Attribute attribute = GlobalAttributeCollection.GetInstance(this.scope).GetAttribute(attributeName); // Make sure that the SimilairyMeasures collection has values //if (this.SimilarityMeasures.IsValueCreated) //{ // Loop over the MEF maintained similarity collection foreach (ISimilarityMeasure currentMeasure in SimilarityMeasures) { SimilarityMeasureBase measure = currentMeasure as SimilarityMeasureBase; // Check if current measure is valid based on allowed // semantic types if (measure.SemanticTypes.HasFlag(attribute.SemanticType)) { validMeasures.Add(measure); } else { // If we are here, appropriate semantic types not matching so // something was setup wrong initially //TODO: HANDLE THIS } } //} return(validMeasures); }
/// <summary> /// Returns an instance of the default SimilarityMeasure for /// the provided attribute. This method does not check the /// cache because the cache contains the currently associated /// Similarity Measure, which is not neccessairly the default. /// </summary> /// <param name="attributeName">The name of the targetAttribute</param> /// <returns>the default ISimilarityMeasure that should be used for the provided attribute</returns> public ISimilarityMeasure GetDefaultSimilarityMeasure(string attributeName) { // Validate parameter if (string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("AttributeName", "No valid attribute name was provided"); } ISimilarityMeasure defaultMeasure = null; // Attempt to get the default similairy measure using the assigned // preffered similarity measure defaultMeasure = GetPrefferedSimilarityMeasure(attributeName); // If we have a good measure, we can return it if (defaultMeasure != null) { return(defaultMeasure); } // No preffered similarity measure is set so we will determine // the default by analyzing the type of data stored in the attribute string firstValue = GlobalAttributeCollection.GetInstance(this.scope).GetAttributeValues(attributeName).FirstOrDefault(); string secondValue = GlobalAttributeCollection.GetInstance(this.scope).GetAttributeValues(attributeName).LastOrDefault(); if (string.IsNullOrEmpty(firstValue) || string.IsNullOrEmpty(secondValue)) { return(GetSimilarityMeasureInstance(typeof(LevenshteinDistanceStringSimilarityMeasure).FullName)); } // Determine the default by analyzing data stored in the specified // attribute defaultMeasure = DetermineSimilarityMeasure(attributeName, firstValue, secondValue); return(defaultMeasure); }
public void TestAttributeValueUpdated() { bool eventRaised = false; GlobalAttributeCollection globalAttributeCollection = GlobalAttributeCollection.GetInstance("SnagL"); Attribute attribute = new Attribute("SnagL"); AttributeValue original = new AttributeValue("SnagL"); AttributeValue expected = new AttributeValue("SnagLNew"); AttributeValue actual = null; globalAttributeCollection.AttributeListUpdated += (sender, e) => { actual = e.NewValue; eventRaised = true; }; EnqueueCallback(() => globalAttributeCollection.Clear()); EnqueueCallback(() => globalAttributeCollection.Add(attribute, original)); EnqueueCallback(() => globalAttributeCollection.Update(attribute, expected, original)); EnqueueConditional(() => eventRaised); EnqueueCallback(() => Assert.IsTrue(globalAttributeCollection[attribute].Contains(expected.Value))); EnqueueCallback(() => Assert.AreEqual(expected.Value, actual.Value)); EnqueueTestComplete(); }
/// <summary> /// Imports GraphML into SnagL on a new graph /// </summary> /// <param name="data">The graph data to place on the graph</param> /// <param name="scope">Specifies the graphs scope</param> /// <param name="format">Specifies the graph data format</param> public void ImportData(string data, string scope, GraphDataFormatBase format) { SnaglEventAggregator.DefaultInstance.GetEvent <UI.TimeConsumingTaskExecutingEvent>().Publish(new UI.TimeConsumingTaskEventArgs()); GraphComponents components = null; // Check if the provided scope is null or empty if (string.IsNullOrEmpty(scope)) { // This is a new graph so we will generate new GraphComponents // for it components = new GraphComponents(); } else { // Attempt to get the graph components instance for // the given scope components = GetGraphComponents(scope); // If we were unable to get an instance, create a // new one if (components == null) { components = new GraphComponents(); } } components.Clear(); GlobalAttributeCollection.GetInstance(scope).Clear(); // Import the data into the provided components format.Import(data, components, CreationType.Imported); // Check if the default instance (which is the first instance // created) has been initialized yet if (this.defaultComponentInstanceScope == string.Empty) { // TODO: ENSURE THIS IS VALID IN THE FUTURE AS THE MAIN GRAPH MAY NOT ALWAYS POPULATE FIRST (BUT SHOULD BE) // Save the newly created components as the default this.defaultComponentInstanceScope = components.Scope; } // Now we need to update or add the components to the collection of components // Check if the collection has never been initialized if (this.graphComponentsInstances == null) { // Initialize the collection this.graphComponentsInstances = new Dictionary <string, GraphComponents>(); } // Check if we have no items if (this.graphComponentsInstances.Count == 0) { // Add the components instance to the collection this.graphComponentsInstances.Add(components.Scope, components); } else { // Ensure that the scope doesn't already exist if (this.graphComponentsInstances.ContainsKey(components.Scope)) { // Update the components instance for the specified scope this.graphComponentsInstances[components.Scope] = components; } else { // Add the new instance for the specified scope this.graphComponentsInstances.Add(components.Scope, components); } } //TODO MAKE SURE THAT WE HAVE DATA // Fire the DataLoaded event DispatcherHelper.UIDispatcher.BeginInvoke(() => SnaglEventAggregator.DefaultInstance.GetEvent <DataLoadedEvent>().Publish(new DataLoadedEventArgs(components.Scope, CreationType.Imported)) ); SnaglEventAggregator.DefaultInstance.GetEvent <TimeConsumingTaskCompletedEvent>().Publish(new TimeConsumingTaskEventArgs()); }
/// <summary> /// Returns a list of tuples that contain the calculated distances /// and the frequency of those distances /// </summary> /// <param name="attributeName">The name of the attribute that /// distances are being calculated for</param> /// <param name="measure">The similarity measure to be used</param> /// <returns>a collection of distances and the number of times /// that those distances occur</returns> private List <Tuple <double, int> > CalculateDistances(string attributeName, ISimilarityMeasure measure) { if (!GlobalAttributeCollection.GetInstance(this.scope).ContainsAttribute(attributeName)) { return(null); } List <Tuple <double, int> > distances = new List <Tuple <double, int> >(); double frequencyTotal = 0; int nodeCount = 0; // Get the values for the attribute List <string> attributeValues = new List <string>(GlobalAttributeCollection.GetInstance(this.scope).GetAttributeValues(attributeName)); // Loop over all the attribute values for (int i = 0; i <= attributeValues.Count - 1; i++) { // Get the frequency at which the source attribute value occurrs int sourceFrequency = GlobalAttributeCollection.GetInstance(this.scope).GetFrequency(attributeName, attributeValues[i]); nodeCount += sourceFrequency; // Compare the current attribute value to all other // attribute values for (int j = 0; j < i; j++) { // Compute the distance for the two values double?distance = measure.CalculateDistance(attributeValues[i], attributeValues[j]); if (distance != null) { // Get the frequency at which the target attribute value occurrs int targetFrequency = GlobalAttributeCollection.GetInstance(this.scope).GetFrequency(attributeName, attributeValues[j]); distances.Add(Tuple.Create <double, int>(distance.Value, sourceFrequency * targetFrequency)); // Keep a running total of the frequencies frequencyTotal += sourceFrequency * targetFrequency; } } } // Since we only loop over unique attribute values we never make // the comparisons against nodes where the values would be the // same. We need to determine if this case has occurred and insert // the appropriate number of zero distance items. // Use binomial function to determine the number of possible combinations //double combinations = (MathUtils.LogFactorial(nodeCount) / (2 * (MathUtils.LogFactorial(nodeCount - 2)))); double combinations = Math.Exp(MathUtils.LogFactorial(nodeCount) - MathUtils.LogFactorial(2) - MathUtils.LogFactorial(nodeCount - 2)); // Add in all the zero distance items that we need for (int i = 1; i <= combinations - frequencyTotal; i++) { distances.Add(Tuple.Create <double, int>(0, 1)); } //foreach (Tuple<double, int> distanceCount in distances) //{ // System.Diagnostics.Debug.WriteLine("[{0},{1}]", distanceCount.Item1, distanceCount.Item2); //} return(distances); }
/// <summary> /// Adds the specificed node /// </summary> /// <param name="graphComponents">The Graph that data is being imported into</param> /// <param name="creationType">The specified CreationType</param> /// <param name="objNode">Node to be added</param> public static void AddNode(GraphComponents graphComponents, CreationType creationType, NodeMapData objNode) { // Create new node Node uiNode = new Node(objNode.Id); uiNode.SourceMechanism = creationType; // TODO as NodeMapData types expands, this needs to be adjusted NodeTypes uiNodeType = NodeTypes.Simple; if (objNode is IconNodeMapData) { uiNodeType = NodeTypes.Icon; } else if (objNode is TextNodeMapData) { uiNodeType = NodeTypes.Text; } NodeViewModelBase uiNodeVM = NodeViewModelBase.GetNodeViewModel(uiNodeType, uiNode, graphComponents.Scope); // Properties if (uiNodeType == NodeTypes.Icon) { IconNodeMapData objIconNode = (IconNodeMapData)objNode; if (objIconNode.ImageSource != null) { ((IconNodeViewModel)uiNodeVM).ImageSource = objIconNode.ImageSource.ToString(); } } uiNodeVM.Description = objNode.Description; uiNodeVM.DisplayValue = objNode.Label; uiNodeVM.Width = objNode.Dimension.Width; uiNodeVM.Height = objNode.Dimension.Height; uiNodeVM.Position = objNode.Position; uiNodeVM.IsHidden = objNode.IsHidden; SolidColorBrush uiBackgroundColorBrush = new SolidColorBrush(objNode.BackgroundColor); uiNodeVM.BackgroundColor = uiBackgroundColorBrush; SolidColorBrush uiSelectionColorBrush = new SolidColorBrush(objNode.SelectionColor); uiNodeVM.SelectionColor = uiSelectionColorBrush; if (uiNodeVM.Height == 0) { uiNodeVM.Height = 45; } if (uiNodeVM.Width == 0) { uiNodeVM.Width = 45; } // Add the node to the graph graphComponents.AddNodeViewModel(uiNodeVM); // Attributes foreach (KeyValuePair <string, AttributeMapData> objNodeAttrKVP in objNode.Attributes) { Attributes.Attribute uiNodeAttribute = new Attributes.Attribute(objNodeAttrKVP.Value.Name); AttributeValue uiNodeAttributeValue = new AttributeValue(objNodeAttrKVP.Value.Value); uiNode.Attributes.Add(uiNodeAttribute.Name, uiNodeAttributeValue); GlobalAttributeCollection.GetInstance(graphComponents.Scope).Add(uiNodeAttribute, uiNodeAttributeValue); uiNodeAttribute.SemanticType = objNodeAttrKVP.Value.SemanticType; uiNodeAttribute.PreferredSimilarityMeasure = objNodeAttrKVP.Value.SimilarityMeasure; uiNodeAttribute.Visible = !objNodeAttrKVP.Value.IsHidden; } }