diff --git a/nate/importers/dataframe_importers.py b/nate/importers/dataframe_importers.py index 426d98a..bcbe23c 100644 --- a/nate/importers/dataframe_importers.py +++ b/nate/importers/dataframe_importers.py @@ -17,6 +17,7 @@ def process_dataframe(temp_data, text: str, unique_id: str = None, time: str = None, + twitter_times: bool = False, columns_to_keep: List = []): """Builds a nate object from a dataframe.""" series_dict = {} @@ -35,8 +36,12 @@ def process_dataframe(temp_data, series_dict[covariate_column] = temp_column.tolist() if time != None: - series_dict['time'] = convert_times(series_dict['times']) - del series_dict['times'] + try: + series_dict['time'] = convert_times(series_dict['times']) + del series_dict['times'] + except: + series_dict['time'] = series_dict['times'] + del series_dict['times'] return Nate(tupleize(series_dict)) @@ -45,6 +50,7 @@ def import_dataframe(input_dataframe: pandas.DataFrame, text: str, unique_id: str = None, time: str = None, + twitter_times: bool = False, columns_to_keep: List = []): """Imports a pandas dataframe into nate. @@ -70,7 +76,11 @@ def import_dataframe(input_dataframe: pandas.DataFrame, be renamed to 'text', 'unique_id', and 'time', accordingly. The names of the columns listed in 'columns_to_keep' will be preserved as-is. """ - return process_dataframe(input_dataframe, text, unique_id, time, + + if time!= None and twitter_times == False: + input_dataframe = input_dataframe.astype({time: 'str'}) + input_dataframe[time] = pandas.to_datetime(input_dataframe[time], infer_datetime_format=True) + return process_dataframe(input_dataframe, text, unique_id, time, twitter_times, columns_to_keep) @@ -78,6 +88,7 @@ def import_csv(file_paths: Union[List, str], text: str, unique_id: str = None, time: str = None, + twitter_times: bool = False, columns_to_keep: List = [], observation_threshold=0): """Imports a comma-separated values file (.csv) into `nate`. @@ -126,12 +137,17 @@ def import_csv(file_paths: Union[List, str], for special_column in [text, unique_id, time]: if special_column != None: columns_to_import.append(special_column) + + dtypes = {} + + if time!= None: + dtypes[time] = "str" if isinstance(file_paths, list): df_list = [] total_len = 0 for entry in file_paths: - temp_df = pandas.read_csv(entry, usecols=columns_to_import) + temp_df = pandas.read_csv(entry, usecols=columns_to_import, dtype = dtypes) df_list.append(temp_df) if observation_threshold != 0: @@ -143,18 +159,23 @@ def import_csv(file_paths: Union[List, str], elif isinstance(file_paths, str): - temp_data = pandas.read_csv(file_paths, usecols=columns_to_import) + temp_data = pandas.read_csv(file_paths, usecols=columns_to_import, dtype = dtypes) else: raise TypeError("file_paths must be either string or list of strings") + + if time!= None and twitter_times == False: + temp_data = temp_data.astype({time: 'str'}) + temp_data[time] = pandas.to_datetime(temp_data[time], infer_datetime_format=True) - return process_dataframe(temp_data, text, unique_id, time, columns_to_keep) + return process_dataframe(temp_data, text, unique_id, time, twitter_times, columns_to_keep) def import_excel(file_paths: Union[List, str], text: str, unique_id: str = None, time: str = None, + twitter_times: bool = False, columns_to_keep: List = [], observation_threshold=0): """Imports an excel file (.xlsx) into nate. @@ -203,6 +224,11 @@ def import_excel(file_paths: Union[List, str], for special_column in [text, unique_id, time]: if special_column != None: columns_to_import.append(special_column) + + dtypes = {} + + if time!= None: + dtypes[time] = "str" print(columns_to_import) print(columns_to_keep) @@ -211,7 +237,7 @@ def import_excel(file_paths: Union[List, str], df_list = [] total_len = 0 for entry in file_paths: - temp_df = pandas.read_excel(entry, usecols=columns_to_import) + temp_df = pandas.read_excel(entry, usecols=columns_to_import, dtype = dtypes) df_list.append(temp_df) if observation_threshold != 0: @@ -223,9 +249,13 @@ def import_excel(file_paths: Union[List, str], elif isinstance(file_paths, str): - temp_data = pandas.read_excel(file_paths, usecols=columns_to_import) + temp_data = pandas.read_excel(file_paths, usecols=columns_to_import, dtype = dtypes) else: raise TypeError("file_paths must be either string or list of strings") + + if time!= None and twitter_times == False: + temp_data = temp_data.astype({time: 'str'}) + temp_data[time] = pandas.to_datetime(temp_data[time], infer_datetime_format=True) - return process_dataframe(temp_data, text, unique_id, time, columns_to_keep) + return process_dataframe(temp_data, text, unique_id, time, twitter_times, columns_to_keep) diff --git a/nate/importers/nate_class.py b/nate/importers/nate_class.py index f7ad7fb..01e4dda 100644 --- a/nate/importers/nate_class.py +++ b/nate/importers/nate_class.py @@ -15,7 +15,7 @@ from nate.cooc.cooc_class import Cooc from nate.cooc.cooc_offsets import cooc_offsets -#from ..socnet.socnet import SOCnet +from nate.socnet.socnet_class import SOCnet from nate.svonet.svonet_class import process_svo, SVOnet from nate.utils import nlp_helpers from nate.utils.mp_helpers import mp, mp2 @@ -296,9 +296,7 @@ class has been supplied with a valid edgelist, either directly or via one of SOCnet: An instance of the `SOCnet` class. """ - print("NOT CURRENTLY IMPLEMENTED") - - return "NOT CURRENTLY IMPLEMENTED" #SOCnet(self.data, self.edgelist[slice(subset)]) + return SOCnet(self.data, self.edgelist[slice(subset)]) def svonet_pipeline(self, sub_tags: bool = False, diff --git a/nate/socnet/alters.py b/nate/socnet/alters.py index 5080a31..52c80ce 100644 --- a/nate/socnet/alters.py +++ b/nate/socnet/alters.py @@ -4,46 +4,35 @@ import pandas as pd import networkx as nx +from collections import namedtuple +alter_tuple = namedtuple('alters', ['vertex', 'betweenness', 'closeness', 'eigenvector']) -def find_alters(tuples): - network = nx.Graph() - pass +def find_alters(edgelist) -> dict: + G = nx.Graph() + G = nx.from_pandas_edgelist(pd.DataFrame(edgelist, columns = ['From', 'To']), source='From', target='To') -edgelist = pd.read_csv("../input/coauthorship_edgeList.csv") -network = nx.from_pandas_edgelist(edgelist, source='From', target='To') + authorlist = [entry.From for entry in edgelist] + authorlist.extend([entry.To for entry in edgelist]) + author_dict = {item: [] for item in set(authorlist)} -author_dict = {} + for author in author_dict: + alter_list = list(G.neighbors(author)) + alter_2_list = [] + for alter in alter_list: + alters_2 = list(G.neighbors(alter)) + alter_2_list.extend(alters_2) -authorlist = [] + alter_list = list(set(alter_list)) + alter_2_list = list(set(alter_2_list)) -for entry in edgelist["From"]: - authorlist.append(entry) -for entry in edgelist["To"]: - authorlist.append(entry) + alter_2_list.remove(author) + for alter in alter_list: + if alter in alter_2_list: + alter_2_list.remove(alter) -author_dict = {item: [] for item in list(set(authorlist))} + author_dict[author] = [alter_list, alter_2_list] -for author in author_dict: - alter_list = list(network.neighbors(author)) - alter_2_list = [] - for alter in alter_list: - alters_2 = list(network.neighbors(alter)) - alter_2_list.extend(alters_2) - - alter_list = list(set(alter_list)) - alter_2_list = list(set(alter_2_list)) - - alter_2_list.remove(author) - for alter in alter_list: - if alter in alter_2_list: - alter_2_list.remove(alter) - - author_dict[author] = [alter_list, alter_2_list] - -author_dataframe = pd.DataFrame.from_dict(author_dict, - orient='index').reset_index() -author_dataframe.columns = ['author', 'alter', 'alter_2'] -author_dataframe.to_pickle("../output/alter_lists.pkl") + return author_dict diff --git a/nate/socnet/centralities.py b/nate/socnet/centralities.py index 5329224..bab3b8f 100644 --- a/nate/socnet/centralities.py +++ b/nate/socnet/centralities.py @@ -1,86 +1,86 @@ -# """ -# This is a MODULE docstring -# """ -# from importlib.util import find_spec -# from collections import namedtuple -# #import igraph as ig - -# cent_tuple = namedtuple('centralities', ['vertex', 'betweenness', 'closeness', 'eigenvector']) - -# def compute_centralities(tuples, force_igraph = False): -# """ -# This is a docstring -# """ - -# if find_spec('graph_tool') != None and force_igraph == False: -# print("using graph-tool") -# return gt_cents(tuples) - -# elif find_spec('igraph') != None: -# print("using igraph") -# return igraph_cents(tuples) - -# else: -# raise Exception("Please ensure that either graph_tool or python_igraph are installed.") - -# def gt_cents(tuples): -# """ -# This is a docstring -# """ -# author_lookup = {} -# author_number = 0 - -# for entry in tuples: -# for i in range(2): -# if entry[i] not in author_lookup: -# author_lookup[entry[i]] = author_number -# author_number += 1 - -# import graph_tool as gt -# from graph_tool.centrality import betweenness, closeness, eigenvector - -# G = gt.Graph(directed=False) - -# for edge in tuples: -# G.add_edge(author_lookup[edge[0]], author_lookup[edge[1]], add_missing=True) - -# betweenness_vertex, _ = betweenness(G) -# closeness_vertex = closeness(G) -# _, eigenvector_vertex = eigenvector(G) - -# return_list = [] - -# for k, v in author_lookup.items(): -# cent = cent_tuple( -# k, -# betweenness_vertex[v], -# closeness_vertex[v], -# eigenvector_vertex[v] -# ) -# return_list.append(cent) - -# return return_list - -# def igraph_cents(tuples): -# """ -# This is a docstring -# """ -# G = ig.Graph.TupleList(tuples, directed = False) - -# vertex_list = G.vs() -# between_list = G.betweenness(directed=False) -# close_list = G.closeness(normalized=True) -# eigen_list = G.eigenvector_centrality(directed=False, scale=True) - -# return_list = [] - -# for i in range(len(vertex_list)): -# cent = cent_tuple( -# vertex_list[i]['name'], -# between_list[i], -# close_list[i], -# eigen_list[i] -# ) -# return_list.append(cent) - -# return return_list +""" +This is a MODULE docstring +""" +from importlib.util import find_spec +import igraph +from collections import namedtuple + +cent_tuple = namedtuple('centralities', ['vertex', 'betweenness', 'closeness', 'eigenvector']) + +def compute_centralities(tuples, force_igraph = False): + """ + This is a docstring + """ + + if find_spec('graph_tool') != None and force_igraph == False: + print("using graph-tool") + return gt_cents(tuples) + + elif find_spec('igraph') != None: + print("using igraph") + return igraph_cents(tuples) + + else: + raise Exception("Please ensure that either graph_tool or python_igraph are installed.") + +def gt_cents(tuples): + """ + This is a docstring + """ + author_lookup = {} + author_number = 0 + + for entry in tuples: + for i in range(2): + if entry[i] not in author_lookup: + author_lookup[entry[i]] = author_number + author_number += 1 + + import graph_tool as gt + from graph_tool.centrality import betweenness, closeness, eigenvector + + G = gt.Graph(directed=False) + + for edge in tuples: + G.add_edge(author_lookup[edge[0]], author_lookup[edge[1]], add_missing=True) + + betweenness_vertex, _ = betweenness(G) + closeness_vertex = closeness(G) + _, eigenvector_vertex = eigenvector(G) + + return_list = [] + + for k, v in author_lookup.items(): + cent = cent_tuple( + k, + betweenness_vertex[v], + closeness_vertex[v], + eigenvector_vertex[v] + ) + return_list.append(cent) + + return return_list + +def igraph_cents(tuples): + """ + This is a docstring + """ + G = igraph.Graph.TupleList(tuples, directed = False) + + vertex_list = G.vs() + between_list = G.betweenness(directed=False) + close_list = G.closeness(normalized=True) + eigen_list = G.eigenvector_centrality(directed=False, scale=True) + + return_list = [] + + for i in range(len(vertex_list)): + cent = cent_tuple( + vertex_list[i]['name'], + between_list[i], + close_list[i], + eigen_list[i] + ) + return_list.append(cent) + + return return_list diff --git a/nate/socnet/dissimilarities.py b/nate/socnet/dissimilarities.py new file mode 100644 index 0000000..46478f9 --- /dev/null +++ b/nate/socnet/dissimilarities.py @@ -0,0 +1,6 @@ + + + +def find_dissimilarities(): + + return \ No newline at end of file diff --git a/nate/socnet/old_temsna/extract_coauthor.py b/nate/socnet/old_temsna/extract_coauthor.py index 110c609..ab8cd90 100644 --- a/nate/socnet/old_temsna/extract_coauthor.py +++ b/nate/socnet/old_temsna/extract_coauthor.py @@ -18,10 +18,7 @@ RC = RCY.yearSplit(2008, 2019) coauth = RC.networkCoAuthor() -# coauth.remove_nodes_from(list(nx.isolates(coauth))) #temporarily commented out until we decide whether to NLP entire network or just giant component -#coauth = max(nx.connected_component_subgraphs(coauth), key=len) #temporarily added - see above -#partition = community.best_partition(coauth) -mk.writeGraph(coauth, '../output/coauthorship') +mk.writeGraph(coauth, 'coauthorship') wos_dict = RC.makeDict( onlyTheseTags=["UT", "AF", "AU", "TI", "ID", "DE", "AB", "TC", "SO", "PY"], @@ -109,11 +106,11 @@ except TypeError: pass -with open("../output/author_metadata.pkl", "wb") as handle: +with open("author_metadata.pkl", "wb") as handle: pickle.dump(author_dict, handle) -with open("../output/comm_abs.pkl", "wb") as handle: +with open("comm_abs.pkl", "wb") as handle: pickle.dump(abs_dict, handle) -with open("../output/cites_dict.yaml", "w") as stream: +with open("cites_dict.yaml", "w") as stream: yaml.dump(cites_dict, stream, default_flow_style=False) diff --git a/nate/socnet/socnet.py b/nate/socnet/socnet.py deleted file mode 100644 index daa85a0..0000000 --- a/nate/socnet/socnet.py +++ /dev/null @@ -1,9 +0,0 @@ -""" -This module accepts a social network that has text attributes for nodes and outputs -the same social network with similarity values between i,j as an edge attribute -""" -# from .centralities import compute_centralities - -# class SOCnet(): -# def __init__(self, data, edgelist): -# self.centrality = compute_centralities(edgelist) diff --git a/nate/socnet/socnet_class.py b/nate/socnet/socnet_class.py new file mode 100644 index 0000000..2a30933 --- /dev/null +++ b/nate/socnet/socnet_class.py @@ -0,0 +1,15 @@ +""" +This module accepts a social network that has text attributes for nodes and outputs +the same social network with similarity values between i,j as an edge attribute +""" +from nate.socnet.centralities import compute_centralities +from nate.socnet.alters import find_alters +from nate.socnet.dissimilarities import find_dissimilarities + +class SOCnet(): + def __init__(self, data, edgelist): + self.data = data + self.edgelist = edgelist + self.centralities = compute_centralities(edgelist) + self.alters = find_alters(edgelist) + self.dissimilarities = None