tarjan_tree.rb revision 5ef489668196d4db3b698ac9eb538649d79a1a45
1516N/A#Class for using the Tarjan algorithm to remove cycles in the entity trees.
565N/A
565N/Aclass TarjanTree
565N/A include TSort
565N/A
565N/A def initialize ontology
565N/A @hashed_entities = Hash.new
565N/A subclasses = inheritance_sentences ontology
565N/A subclasses.each do |s|
565N/A c1, c2 = s.hierarchical_class_names
565N/A
565N/A child = ontology.entities.where('name = ? OR iri = ?', c1, c1).first!.id
565N/A parent = ontology.entities.where('name = ? OR iri = ?', c2, c2).first!.id
565N/A if @hashed_entities[parent]
565N/A @hashed_entities[parent] << child
565N/A else
565N/A @hashed_entities[parent] = [child]
565N/A end
565N/A end
565N/A create_tree ontology
565N/A end
926N/A
926N/A def tsort_each_node(&block)
3158N/A @hashed_entities.each_key(&block)
926N/A end
565N/A
2026N/A def tsort_each_child(node, &block)
3094N/A @hashed_entities[node].each(&block) if @hashed_entities[node]
1050N/A end
2524N/A
926N/A # Get SubClassOf Strings without explicit Thing
926N/A def inheritance_sentences ontology
2339N/A ontology.sentences
2339N/A .where("text LIKE '%SubClassOf%' AND text NOT LIKE '%Thing%'")
2339N/A .select do |sentence|
926N/A sentence.text.split(' ').size == 4
926N/A end
926N/A end
838N/A
565N/A def create_tree ontology
2034N/A create_groups ontology
2034N/A create_edges
2034N/A end
1540N/A
1540N/A def create_groups ontology
1540N/A groups = self.strongly_connected_components
1540N/A groups.each do |entity_group|
1540N/A entities = Entity.where(id: entity_group)
1968N/A name = determine_group_name(entities)
1540N/A EntityGroup.create!(ontology: ontology, entities: entities, name: name)
2034N/A end
2034N/A end
2200N/A
2034N/A def create_edges
2034N/A @hashed_entities.each do |parent, children|
2034N/A parent_group = Entity.find(parent).entity_group
565N/A children.each do |child|
2339N/A child_group = Entity.find(child).entity_group
2339N/A unless parent_group == child_group
2339N/A EEdge.find_or_create_by_parent_id_and_child_id(parent_group.id, child_group.id)
2339N/A end
2339N/A end
2339N/A end
2524N/A end
2524N/A
2524N/A def determine_group_name entities
2524N/A name = ""
2524N/A entities.each_with_index do |entity, i|
2524N/A if entity == entities.last
2524N/A name += "#{entity}"
2524N/A else
2524N/A name += "#{entity} ☰ "
2524N/A end
2524N/A end
2524N/A name
2524N/A end
2524N/A
2524N/Aend
2524N/A