Exemplo n.º 1
0
 def as_igraph(self):
     """
     Method to export the Graph object to an igraph.Graph object
     :return: igraph.Graph
     """
     from igraph import Graph as iGraph
     as_igraph = iGraph(directed=False)
     as_igraph.add_vertices(range(self.n))
     for i in xrange(len(self.nn)):
         for neighbour in self.nn[i]:
             as_igraph.add_edges([(i, neighbour)])
     as_igraph.simplify()
     return as_igraph
Exemplo n.º 2
0
 def as_igraph(self):
     """
     Method to export the Graph object to an igraph.Graph object
     :return: igraph.Graph
     """
     from igraph import Graph as iGraph
     as_igraph = iGraph(directed=False)
     as_igraph.add_vertices(range(self.n))
     for i in xrange(len(self.nn)):
         for neighbour in self.nn[i]:
             as_igraph.add_edges([(i, neighbour)])
     as_igraph.simplify()
     return as_igraph
Exemplo n.º 3
0
def get_network(my_id, ids):
    friends_id = dict()
    vertex = list()
    for id1, name1 in ids:
        if id1 not in friends_id:
            friends_id[id1] = [len(friends_id), name1]
            vertex.append(name1)

    edges = set()
    for id1, name1 in ids:
        print(name1)
        fr = get_friends(id1)
        if fr == None:
            continue
        fr_ids = get_ids(fr)
        for id2, name2 in fr_ids:
            if id2 == my_id or id2 not in friends_id:
                continue
            edges.add((min(friends_id[id1][0], friends_id[id2][0]),
                       max(friends_id[id1][0], friends_id[id2][0])))
    g = igraph.iGraph(vertex, list(edges))
    #g.vertex[0].color_text = 'red'
    l = igraph.iLayout()
    l.vizualizate(g)
Exemplo n.º 4
0
def get_graph(episodes, object_types={}):
	"""Generates a graph from a set of input episode QSRs.

	:param episodes: list of episodes, where one episode = [[obj_list], {QSR dict}, (start, end_tuple)]
	:type episodes: list
	:param object_types: a dictionary of object ID and object type.
	:type object_types: dict

	:return: igraph.Graph: An igraph graph object containing all the object, spatial and temporal nodes.
	:rtype: igraph.Graph
	"""

	temporal_map = {'>': '<',
					'mi' : 'm',
					'oi': 'o',
					'si': 's',
					'di':'d',
					'fi': 'f'
					}

	spatial_nodes_edges = {"rcc2": 2, "rcc3": 2, "rcc8": 2, "cardir": 2,
				"qtcbs": 2, "qtccs": 2, "qtcbcs": 2, "argd": 2, "argprobd": 2, "mos": 1}

	objects = {}
	spatial_data = []
	spatial_obj_edges, temp_spatial_edges = [], []
	vertex_count = 0
	graph = iGraph(directed=True)

	#print("Looping through the episodes...")
	for (objs, relations, (intv_start, intv_end)) in episodes:
		#print(objs, relations, (intv_start, intv_end))

		#############################################
		#   Object Nodes:                           #
		#############################################
		number_of_edges = set([])
		for rel in relations.keys():
			number_of_edges.add(spatial_nodes_edges[rel])
		if len(number_of_edges) != 1:
			raise ValueError("QSRs with different spatial node edges selected.")
		else:
			spatial_edges = number_of_edges.pop()

		for o in objs:
			if o in objects: continue

			graph.add_vertex(o)
			objects[o] = vertex_count

			if o in object_types:
				graph.vs()[vertex_count]['obj_type'] = object_types[o]

			graph.vs()[vertex_count]['node_type'] = 'object'
			vertex_count += 1

		object_ids = []
		for o in objs:
			object_ids.append(objects[o])
		#print("   OBJECT IDS ", object_ids)
		#############################################
		#   Spatial Nodes:                          #
		#############################################
		graph.add_vertex(relations)
		graph.vs()[vertex_count]['node_type'] = 'spatial_relation'

		# Add edges from spatial node to objects
		edge_from_object = objects[objs[0]]

		#print("adding edge: : ", edge_from_object, vertex_count)
		graph.add_edge(edge_from_object, vertex_count)
		spatial_obj_edges.append((edge_from_object, vertex_count))

		if spatial_edges is 2:
			#print("TWO OBJECTS -- ")
			edge_to_object = objects[objs[1]]
			graph.add_edge(vertex_count, edge_to_object)
			spatial_obj_edges.append( (vertex_count, edge_to_object) )

		elif spatial_edges is 3:
			#print("THREE OBJECTS -- ")
			edge_from_object_2 = objects[objs[1]]
			edge_from_object_3  = objects[objs[2]]
			graph.add_edge(edge_from_object_2, vertex_count)
			graph.add_edge(edge_from_object_3, vertex_count)
			spatial_obj_edges.append( (edge_from_object_2, vertex_count) )
			spatial_obj_edges.append( (edge_from_object_3, vertex_count) )

		spatial_data.append( (object_ids, vertex_count,  (intv_start, intv_end)) )
		vertex_count += 1

	#############################################
	#   Temporal Nodes:                         #
	#############################################
	#print("data: \n", spatial_data)
	#print("objects \n", objects)

	E_s, E_f = utils.get_E_set(objects, spatial_data)
	#print("E_s: ", E_s)
	#print("E_f: ", E_f)

	temporal_vertices = {}
	for epi1, epi2 in combinations(spatial_data, 2):

		# don't create a temporal relation between two episodes in the start set, or two in the end set.
		if ( epi1 in E_s and epi2 in E_s) or ( epi1 in E_f and epi2 in E_f): continue
		(objs1, rels1, frames1) = epi1
		(objs2, rels2, frames2) = epi2

		#print (epi1, epi2)
		temporal_rel = utils.get_allen_relation(frames1, frames2)

		# If temporal_rel is in temporal_map get its value otherwise keep it the same
		# If the edges are directed, then we need to change the direction of the edges
		# if we change change the temporal relation to its inverse
		temporal_rel_new = temporal_map.get(temporal_rel, temporal_rel)
		#print(temporal_rel_new)

		# Add temporal node to the graph
		graph.add_vertex(temporal_rel_new)
		graph.vs()[vertex_count]['node_type'] = 'temporal_relation'
		temporal_rel_vertex_id = vertex_count
		temporal_vertices[temporal_rel_new] = vertex_count
		vertex_count += 1

		if temporal_rel_new == temporal_rel:
			# Add edges from spatial node to temporal node
			graph.add_edge(rels1, temporal_rel_vertex_id)
			graph.add_edge(temporal_rel_vertex_id, rels2)
			temp_spatial_edges.append((rels1, temporal_rel_vertex_id))
			temp_spatial_edges.append((temporal_rel_vertex_id, rels2))
		else:
			# If an inverse temporal relation has been used, switch the edges around
			graph.add_edge(temporal_rel_vertex_id, rels1)
			graph.add_edge(rels2, temporal_rel_vertex_id)
			temp_spatial_edges.append((temporal_rel_vertex_id, rels1))
			temp_spatial_edges.append((rels2, temporal_rel_vertex_id))
	return graph, spatial_obj_edges, temp_spatial_edges
Exemplo n.º 5
0
def get_graph(episodes, object_types={}):
    """Generates a graph from a set of input episode QSRs.

    :param episodes: list of episodes, where one episode = [[obj_list], {QSR dict}, (start, end_tuple)]
    :type episodes: list
    :param object_types: a dictionary of object ID and object type.
    :type object_types: dict

    :return: igraph.Graph: An igraph graph object containing all the object, spatial and temporal nodes.
    :rtype: igraph.Graph
    """

    temporal_map = {
        '>': '<',
        'mi': 'm',
        'oi': 'o',
        'si': 's',
        'di': 'd',
        'fi': 'f'
    }

    spatial_nodes_edges = {
        "rcc2": 2,
        "rcc3": 2,
        "rcc8": 2,
        "cardir": 2,
        "qtcbs": 2,
        "qtccs": 2,
        "qtcbcs": 2,
        "argd": 2,
        "argprobd": 2,
        "mos": 1,
        "tpcc": 2,
        "rcc4": 2,
        "rcc5": 2
    }

    objects = {}
    spatial_data = []
    spatial_obj_edges, temp_spatial_edges = [], []
    vertex_count = 0
    graph = iGraph(directed=True)

    if episodes == []:
        return graph, spatial_obj_edges, temp_spatial_edges

    # ----------------- I WROTE THIS -----------------
    # Initialization for every interaction / pair of objects
    combine_objects = []
    combine_vertices = []
    # ---------------- END OF MY CODE ----------------

    #print("Looping through the episodes...")
    for (objs, relations, (intv_start, intv_end)) in episodes:
        #print(objs, relations, (intv_start, intv_end))

        #############################################
        #   Object Nodes:                           #
        #############################################
        number_of_edges = set([])
        for rel in relations.keys():
            number_of_edges.add(spatial_nodes_edges[rel])
        if len(number_of_edges) != 1:
            raise ValueError(
                "QSRs with different spatial node edges selected.")
        else:
            spatial_edges = number_of_edges.pop()

        for o in objs:
            if o in objects: continue

            graph.add_vertex(o)
            objects[o] = vertex_count

            if o in object_types:
                graph.vs()[vertex_count]['obj_type'] = object_types[o]

                # ----------------- I WROTE THIS -----------------
                # Need the info (object_types[o], vertex_count) to create a
                # dictionary with the objects' i
                combine_objects.append(object_types[o])
                combine_vertices.append(vertex_count)
                #print(object_types[o], vertex_count)
                #dict_object_vertices[object_types[o]] = vertex_count
                # ---------------- END OF MY CODE ----------------

            graph.vs()[vertex_count]['node_type'] = 'object'
            vertex_count += 1
        # ----------------- I WROTE THIS -----------------
        #print(combine_objects, combine_vertices)
        if (len(combine_objects) >= 2):
            dict_key = combine_objects[0] + combine_objects[1]
            dict_value = combine_vertices
            dict_object_vertices[dict_key] = dict_value
            dict_key = list(reversed(combine_objects))[0] + list(
                reversed(combine_objects))[1]
            dict_value = list(reversed(combine_vertices))
            dict_object_vertices[dict_key] = dict_value
            #print(dict_object_vertices)
        # ---------------- END OF MY CODE ----------------

        object_ids = []
        for o in objs:
            object_ids.append(objects[o])
        #print("   OBJECT IDS ", object_ids)
        #############################################
        #   Spatial Nodes:                          #
        #############################################
        graph.add_vertex(relations)
        graph.vs()[vertex_count]['node_type'] = 'spatial_relation'

        # Add edges from spatial node to objects
        edge_from_object = objects[objs[0]]
        #print("adding spatial edge: : ", edge_from_object, vertex_count)
        graph.add_edge(edge_from_object, vertex_count)
        spatial_obj_edges.append((edge_from_object, vertex_count))

        if spatial_edges is 2:
            #print("TWO OBJECTS -- ")
            edge_to_object = objects[objs[1]]
            graph.add_edge(vertex_count, edge_to_object)
            spatial_obj_edges.append((vertex_count, edge_to_object))

        elif spatial_edges is 3:
            #print("THREE OBJECTS -- ")
            edge_from_object_2 = objects[objs[1]]
            edge_from_object_3 = objects[objs[2]]
            graph.add_edge(edge_from_object_2, vertex_count)
            graph.add_edge(edge_from_object_3, vertex_count)
            spatial_obj_edges.append((edge_from_object_2, vertex_count))
            spatial_obj_edges.append((edge_from_object_3, vertex_count))

        # ----------------- I WROTE THIS -----------------
        qsrkey = graph.vs()[vertex_count]['name'].keys()[0]
        #qsrkey = 'rcc4'
        global first_time
        global keep_track_of_spatial_vertex
        if (((keep_track_of_spatial_vertex == []) or
             (vertex_count not in keep_track_of_spatial_vertex))
                and first_time):
            if spatial_edges is 2:
                omy = [objects[objs[0]], objects[objs[1]]]
                omy.sort()
                if keep_objects_in_node_names:
                    graph.vs()[vertex_count]['name'][qsrkey] = graph.vs(
                    )[vertex_count]['name'][qsrkey] + '_' + str(
                        omy[0]) + '_' + str(omy[1])
                else:
                    graph.vs()[vertex_count]['name'][qsrkey] = graph.vs(
                    )[vertex_count]['name'][qsrkey]
            elif spatial_edges is 3:
                omy = [objects[objs[0]], objects[objs[1]], objects[objs[2]]]
                omy.sort()
                if keep_objects_in_node_names:
                    graph.vs()[vertex_count]['name'][qsrkey] = graph.vs(
                    )[vertex_count]['name'][qsrkey] + str(omy[0]) + '_' + str(
                        omy[1]) + '_' + str(omy[2])
                else:
                    graph.vs()[vertex_count]['name'][qsrkey] = graph.vs(
                    )[vertex_count]['name'][qsrkey]
            keep_track_of_spatial_vertex.append(vertex_count)

        #else:
        #    print('ffff', graph.vs()[vertex_count]['name']['rcc2'], vertex_count)

        # ---------------- END OF MY CODE ----------------

        spatial_data.append((object_ids, vertex_count, (intv_start, intv_end)))
        vertex_count += 1

    #############################################
    #   Temporal Nodes:                         #
    #############################################
    #print("data: \n", spatial_data)
    #print("objects \n", objects)

    E_s, E_f = utils.get_E_set(objects, spatial_data)
    #print("E_s: ", E_s)
    #print("E_f: ", E_f)

    temporal_vertices = {}
    for epi1, epi2 in combinations(spatial_data, 2):

        # Comment the line below when want to create temporal_rel between same spatial_rel

        # don't create a temporal relation between two episodes in the start set, or two in the end set.
        if (epi1 in E_s and epi2 in E_s) or (epi1 in E_f and epi2 in E_f):
            continue

        (objs1, rels1, frames1) = epi1
        (objs2, rels2, frames2) = epi2

        #print(epi1, epi2)
        # spatial_relation_1 (rels1) : between objs1[0] and objs1[1]
        # spatial_relation_2 (rels2) : between objs2[0] and objs2[1]
        # frames1, frames2: stand for the duration1, duration2 of every spatial relation in terms of start and end time
        #print(objs1[0], objs1[1], objs2[0], objs2[1])

        temporal_rel = utils.get_allen_relation(frames1, frames2)

        # If temporal_rel is in temporal_map get its value otherwise keep it the same
        # If the edges are directed, then we need to change the direction of the edges
        # if we change change the temporal relation to its inverse
        temporal_rel_new = temporal_map.get(temporal_rel, temporal_rel)
        #print(temporal_rel_new)

        # Add temporal node to the graph
        graph.add_vertex(temporal_rel_new)
        graph.vs()[vertex_count]['node_type'] = 'temporal_relation'
        temporal_rel_vertex_id = vertex_count
        temporal_vertices[temporal_rel_new] = vertex_count
        vertex_count += 1

        # ----------------- I WROTE THIS -----------------
        o1 = [objs1[0], objs1[1]]
        o1.sort()
        o2 = [objs2[0], objs2[1]]
        o2.sort()
        o12 = [o1, o2]
        so12 = sorted(o12, key=lambda x: x[0])

        qsrkey1 = graph.vs()[rels1]['name'].keys()[0]
        qsrkey2 = graph.vs()[rels2]['name'].keys()[0]

        if keep_objects_in_node_names:
            spatial_rel1 = graph.vs()[rels1]['name'][qsrkey1][:-4]
            spatial_rel2 = graph.vs()[rels2]['name'][qsrkey1][:-4]
        else:
            spatial_rel1 = graph.vs()[rels1]['name'][qsrkey1]
            spatial_rel2 = graph.vs()[rels2]['name'][qsrkey1]
        if (spatial_rel1 == spatial_rel2):
            us = graph.vs(
            )[temporal_rel_vertex_id]['name'] + '_' + spatial_rel1
            if keep_objects_in_node_names:
                for i in so12:
                    us += str(i)
            graph.vs()[temporal_rel_vertex_id]['name'] = us
        else:
            rels12 = [spatial_rel1, spatial_rel2]
            rels12.sort()
            us = graph.vs(
            )[temporal_rel_vertex_id]['name'] + '_' + rels12[0] + rels12[1]
            if keep_objects_in_node_names:
                for i in so12:
                    us += str(i)
            graph.vs()[temporal_rel_vertex_id]['name'] = us

        # ---------------- END OF MY CODE ----------------

        if temporal_rel_new == temporal_rel:
            # Add edges from spatial node to temporal node
            graph.add_edge(rels1, temporal_rel_vertex_id)
            graph.add_edge(temporal_rel_vertex_id, rels2)
            temp_spatial_edges.append((rels1, temporal_rel_vertex_id))
            temp_spatial_edges.append((temporal_rel_vertex_id, rels2))
        else:
            # If an inverse temporal relation has been used, switch the edges around
            graph.add_edge(temporal_rel_vertex_id, rels1)
            graph.add_edge(rels2, temporal_rel_vertex_id)
            temp_spatial_edges.append((temporal_rel_vertex_id, rels1))
            temp_spatial_edges.append((rels2, temporal_rel_vertex_id))

    return graph, spatial_obj_edges, temp_spatial_edges
Exemplo n.º 6
0
def get_graph(episodes, object_types={}, vis=False):
    """Generates a graph from a set of input episode QSRs.

    :param episodes: list of episodes, where one episode = [[obj_list], {QSR dict}, (start, end_tuple)]
    :type episodes: list
    :param object_types: a dictionary of object ID and object type.
    :type object_types: dict

    :return: igraph.Graph: An igraph graph object containing all the object, spatial and temporal nodes.
    :rtype: igraph.Graph
    """

    temporal_map = {
        '>': '<',
        'mi': 'm',
        'oi': 'o',
        'si': 's',
        'di': 'd',
        'fi': 'f'
    }

    spatial_nodes_edges = {
        "rcc2": 2,
        "rcc3": 2,
        "rcc8": 2,
        "cardir": 2,
        "qtcbs": 2,
        "qtccs": 2,
        "qtcbcs": 2,
        "argd": 2,
        "argprobd": 2,
        "mos": 1,
        "tpcc": 2,
        "rcc4": 2,
        "rcc5": 2
    }

    objects = {}
    spatial_data = []
    spatial_obj_edges, temp_spatial_edges = [], []
    vertex_count = 0
    graph = iGraph(directed=True)

    if episodes == []:
        return graph, spatial_obj_edges, temp_spatial_edges

    #print("Looping through the episodes...")
    for (objs, relations, (intv_start, intv_end)) in episodes:
        if vis: print("eps:", objs, relations, (intv_start, intv_end))

        #############################################
        #   Object Nodes:                           #
        #############################################
        number_of_edges = set([])
        for rel in relations.keys():
            number_of_edges.add(spatial_nodes_edges[rel])
        if len(number_of_edges) != 1:
            raise ValueError(
                "QSRs with different spatial node edges selected.")
        else:
            spatial_edges = number_of_edges.pop()

        for o in objs:
            if o in objects: continue

            graph.add_vertex(o)
            objects[o] = vertex_count

            if o in object_types:
                graph.vs()[vertex_count]['obj_type'] = object_types[o]

            graph.vs()[vertex_count]['node_type'] = 'object'
            vertex_count += 1

        object_ids = []
        for o in objs:
            object_ids.append(objects[o])
        #print("   OBJECT IDS ", object_ids)
        #############################################
        #   Spatial Nodes:                          #
        #############################################
        graph.add_vertex(relations)
        graph.vs()[vertex_count]['node_type'] = 'spatial_relation'

        # Add edges from spatial node to objects
        edge_from_object = objects[objs[0]]

        #print("adding edge: : ", edge_from_object, vertex_count)
        graph.add_edge(edge_from_object, vertex_count)
        spatial_obj_edges.append((edge_from_object, vertex_count))

        if spatial_edges is 2:
            #print("TWO OBJECTS -- ")
            edge_to_object = objects[objs[1]]
            graph.add_edge(vertex_count, edge_to_object)
            spatial_obj_edges.append((vertex_count, edge_to_object))

        elif spatial_edges is 3:
            #print("THREE OBJECTS -- ")
            edge_from_object_2 = objects[objs[1]]
            edge_from_object_3 = objects[objs[2]]
            graph.add_edge(edge_from_object_2, vertex_count)
            graph.add_edge(edge_from_object_3, vertex_count)
            spatial_obj_edges.append((edge_from_object_2, vertex_count))
            spatial_obj_edges.append((edge_from_object_3, vertex_count))

        spatial_data.append((object_ids, vertex_count, (intv_start, intv_end)))
        vertex_count += 1
    if vis: print("spatial data:", spatial_data)
    #############################################
    #   Temporal Nodes:                         #
    #############################################
    #print("data: \n", spatial_data)
    #print("objects \n", objects)

    # # Es and Ef sets removed. Activity Graph now contains these relations.
    # # Graphlets are not created if they contain two or more nodes which would be in the Es or Ef sets.
    # E_s, E_f = utils.get_E_set(objects, spatial_data)
    # if vis: print("E_s: ", E_s)
    # if vis: print("E_f: ", E_f)

    temporal_vertices = {}
    for epi1, epi2 in combinations(spatial_data, 2):

        # don't create a temporal relation between two episodes in the start set, or two in the end set.
        # if ( epi1 in E_s and epi2 in E_s) or ( epi1 in E_f and epi2 in E_f): continue   # # Removed condition
        (objs1, rels1, frames1) = epi1
        (objs2, rels2, frames2) = epi2

        #print (epi1, epi2)
        temporal_rel = utils.get_allen_relation(frames1, frames2)

        # If temporal_rel is in temporal_map get its value otherwise keep it the same
        # If the edges are directed, then we need to change the direction of the edges
        # if we change change the temporal relation to its inverse
        temporal_rel_new = temporal_map.get(temporal_rel, temporal_rel)
        #print(temporal_rel_new)

        # Add temporal node to the graph
        graph.add_vertex(temporal_rel_new)
        graph.vs()[vertex_count]['node_type'] = 'temporal_relation'
        temporal_rel_vertex_id = vertex_count
        temporal_vertices[temporal_rel_new] = vertex_count
        vertex_count += 1

        if temporal_rel_new == temporal_rel:
            # Add edges from spatial node to temporal node
            graph.add_edge(rels1, temporal_rel_vertex_id)
            graph.add_edge(temporal_rel_vertex_id, rels2)
            temp_spatial_edges.append((rels1, temporal_rel_vertex_id))
            temp_spatial_edges.append((temporal_rel_vertex_id, rels2))
        else:
            # If an inverse temporal relation has been used, switch the edges around
            graph.add_edge(temporal_rel_vertex_id, rels1)
            graph.add_edge(rels2, temporal_rel_vertex_id)
            temp_spatial_edges.append((temporal_rel_vertex_id, rels1))
            temp_spatial_edges.append((rels2, temporal_rel_vertex_id))
    return graph, spatial_obj_edges, temp_spatial_edges