1 from pyspark.sql import functions as f
2 from pyspark.sql import SparkSession
3 from pyspark.sql import Window
6 import pyarrow.dataset as ds
9 from itertools import islice, chain
10 from pathlib import Path
11 from similarities_helper import pull_tfidf, column_similarities, write_weekly_similarities
12 from scipy.sparse import csr_matrix
13 from multiprocessing import Pool, cpu_count
14 from functools import partial
16 # infile = "/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_authors_test.parquet"
21 # term_colname='author'
22 # outfile = '/gscratch/comdata/output/reddit_similarity/weekly/comment_authors_test.parquet'
23 # included_subreddits=None
25 def _week_similarities(week, simfunc, tfidf_path, term_colname, min_df, max_df, included_subreddits, topN, outdir:Path, subreddit_names, nterms):
27 term_id = term + '_id'
28 term_id_new = term + '_id_new'
29 print(f"loading matrix: {week}")
31 entries = pull_tfidf(infile = tfidf_path,
32 term_colname=term_colname,
35 included_subreddits=included_subreddits,
37 week=week.isoformat(),
40 tfidf_colname='tf_idf'
41 # if the max subreddit id we found is less than the number of subreddit names then we have to fill in 0s
42 mat = csr_matrix((entries[tfidf_colname],(entries[term_id_new]-1, entries.subreddit_id_new-1)),shape=(nterms,subreddit_names.shape[0]))
44 print('computing similarities')
47 sims = pd.DataFrame(sims)
48 sims = sims.rename({i: sr for i, sr in enumerate(subreddit_names.subreddit.values)}, axis=1)
49 sims['_subreddit'] = subreddit_names.subreddit.values
50 outfile = str(Path(outdir) / str(week))
51 write_weekly_similarities(outfile, sims, week, subreddit_names)
53 def pull_weeks(batch):
54 return set(batch.to_pandas()['week'])
56 #tfidf = spark.read.parquet('/gscratch/comdata/users/nathante/subreddit_tfidf_weekly.parquet')
57 def cosine_similarities_weekly(tfidf_path, outfile, term_colname, min_df = None, max_df=None, included_subreddits = None, topN = 500):
59 # do this step in parallel if we have the memory for it.
60 # should be doable with pool.map
62 spark = SparkSession.builder.getOrCreate()
63 df = spark.read.parquet(tfidf_path)
64 subreddit_names = df.select(['subreddit','subreddit_id']).distinct().toPandas()
65 subreddit_names = subreddit_names.sort_values("subreddit_id")
66 nterms = df.select(f.max(f.col(term_colname + "_id")).alias('max')).collect()[0].max
67 weeks = df.select(f.col("week")).distinct().toPandas().week.values
70 print(f"computing weekly similarities")
71 week_similarities_helper = partial(_week_similarities,simfunc=column_similarities, tfidf_path=tfidf_path, term_colname=term_colname, outdir=outfile, min_df=min_df,max_df=max_df,included_subreddits=included_subreddits,topN=topN, subreddit_names=subreddit_names,nterms=nterms)
73 pool = Pool(cpu_count())
75 list(pool.imap(week_similarities_helper,weeks))
77 # with Pool(cpu_count()) as pool: # maybe it can be done with 40 cores on the huge machine?
80 def author_cosine_similarities_weekly(outfile, min_df=2, max_df=None, included_subreddits=None, topN=500):
81 return cosine_similarities_weekly('/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_authors_test.parquet',
89 def term_cosine_similarities_weekly(outfile, min_df=None, max_df=None, included_subreddits=None, topN=500):
90 return cosine_similarities_weekly('/gscratch/comdata/output/reddit_similarity/tfidf_weekly/comment_terms.parquet',
98 if __name__ == "__main__":
99 fire.Fire({'authors':author_cosine_similarities_weekly,
100 'terms':term_cosine_similarities_weekly})