1 from pyspark.sql import functions as f
2 from pyspark.sql import SparkSession
3 from pyspark.sql import Window
8 from itertools import islice
9 from pathlib import Path
10 from similarities_helper import *
13 #tfidf = spark.read.parquet('/gscratch/comdata/users/nathante/subreddit_tfidf_weekly.parquet')
14 def cosine_similarities_weekly(tfidf_path, outfile, term_colname, min_df = None, included_subreddits = None, topN = 500):
15 spark = SparkSession.builder.getOrCreate()
16 conf = spark.sparkContext.getConf()
18 tfidf = spark.read.parquet(tfidf_path)
20 if included_subreddits is None:
21 included_subreddits = select_topN_subreddits(topN)
23 included_subreddits = set(open(included_subreddits))
25 print(f"computing weekly similarities for {len(included_subreddits)} subreddits")
27 print("creating temporary parquet with matrix indicies")
28 tempdir = prep_tfidf_entries_weekly(tfidf, term_colname, min_df, included_subreddits)
30 tfidf = spark.read.parquet(tempdir.name)
32 # the ids can change each week.
33 subreddit_names = tfidf.select(['subreddit','subreddit_id_new','week']).distinct().toPandas()
34 subreddit_names = subreddit_names.sort_values("subreddit_id_new")
35 subreddit_names['subreddit_id_new'] = subreddit_names['subreddit_id_new'] - 1
38 d weeks = sorted(list(subreddit_names.week.drop_duplicates()))
40 print(f"loading matrix: {week}")
41 mat = read_tfidf_matrix_weekly(tempdir.name, term_colname, week)
42 print('computing similarities')
43 sims = column_similarities(mat)
46 names = subreddit_names.loc[subreddit_names.week == week]
47 sims = pd.DataFrame(sims.todense())
49 sims = sims.rename({i: sr for i, sr in enumerate(names.subreddit.values)}, axis=1)
50 sims['subreddit'] = names.subreddit.values
52 write_weekly_similarities(outfile, sims, week, names)
55 def author_cosine_similarities_weekly(outfile, min_df=None , included_subreddits=None, topN=500):
56 return cosine_similarities_weekly('/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_authors.parquet',
63 def term_cosine_similarities_weekly(outfile, min_df=None, included_subreddits=None, topN=500):
64 return cosine_similarities_weekly('/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_terms.parquet',
71 if __name__ == "__main__":
72 fire.Fire({'author':author_cosine_similarities_weekly,
73 'term':term_cosine_similarities_weekly})